Add Historias Incompletas: web+APK story game with Gemini-powered daily deck

Node/Express backend generates 5 lateral-thinking mystery stories a day via
Gemini and serves the latest batch; React/Vite frontend (Capacitor-wrapped
for Android) plays them pass-and-play style, falling back to a bundled set
of 16 original stories when the backend has nothing new or is unreachable.
Includes systemd/nginx deploy config for a Docker-less Debian LXC.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5 committed 2026-08-12 07:15:54 +00:00
1 parent de0dfec6af
commit 7f3e6cc839
97 files changed
+6803 -1

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
.DS_Store
*.log
.vscode/
.idea/
+86 -1
View File
@@ -1,2 +1,87 @@
# juego-historias
# Historias Incompletas
Juego de historias de pensamiento lateral (estilo "cuenta un enigma, el resto
adivina la explicación completa haciendo preguntas de sí/no") para 2 o más
jugadores compartiendo un mismo dispositivo. Web + APK (Capacitor).
- Un jugador narra: elige una historia, lee en voz alta el enigma, y
responde preguntas de sí/no del resto del grupo hasta que adivinan (o se
rinden) la solución completa.
- La app trae un mazo de historias por defecto embebido, y además intenta
bajar un mazo "actualizado" desde un backend propio que genera 5 historias
nuevas por día con la API de Gemini. Si no hay conexión o el backend no
tiene nada disponible, se usa el mazo default.
## Estructura del repo
```
backend/ API en Node/Express que sirve /api/stories y genera historias
nuevas con Gemini (backend/README.md)
frontend/ App React + Vite, empaquetable como APK con Capacitor
(frontend/README.md)
deploy/ Unidades systemd + config de nginx de ejemplo para producción
docs/ Guía de deploy paso a paso (docs/DEPLOY.md)
```
## Desarrollo local
### Backend
```bash
cd backend
npm install
cp .env.example .env # completa GEMINI_API_KEY y ADMIN_TOKEN
npm run dev # http://localhost:8787
```
Generar historias manualmente (usa tu GEMINI_API_KEY real):
```bash
npm run generate
```
### Frontend (web)
```bash
cd frontend
npm install
cp .env.example .env # VITE_API_URL=http://localhost:8787 en dev
npm run dev # http://localhost:5173
```
### Frontend (APK con Capacitor)
Requiere Android Studio / Android SDK + JDK 17 instalados en tu máquina de
desarrollo (esto no se puede generar en este entorno). Una vez instalados:
```bash
cd frontend
npm run cap:sync # build web + copia assets a android/
npm run android:open # abre el proyecto en Android Studio para compilar/firmar el APK
```
También podés compilar por línea de comandos una vez que tengas el SDK:
```bash
cd frontend/android
./gradlew assembleDebug
# APK en frontend/android/app/build/outputs/apk/debug/
```
## Contenido por defecto
`frontend/src/data/defaultStories.json` tiene 16 historias originales
escritas para este proyecto (no extraídas de ningún juego comercial de
terceros), usadas como fallback cuando no hay conexión al backend o todavía
no se generó ningún lote.
## Producción
Ver [`docs/DEPLOY.md`](docs/DEPLOY.md) para el paso a paso de deploy en un
LXC de Debian sin Docker, con systemd + nginx + certbot, apuntando a tu
propio dominio.
## API key de Gemini
Conseguila en https://aistudio.google.com/apikey y ponela en
`backend/.env` como `GEMINI_API_KEY`.
+21
View File
@@ -0,0 +1,21 @@
# Puerto donde escucha la API
PORT=8787
# Origen permitido para CORS (la URL desde donde se sirve el frontend/PWA).
# Usa "*" solo en desarrollo.
CORS_ORIGIN=*
# API key de Google Gemini (https://aistudio.google.com/apikey)
GEMINI_API_KEY=
# Modelo de Gemini a usar para generar historias
GEMINI_MODEL=gemini-2.5-flash
# Cuantas historias nuevas generar por dia
STORIES_PER_DAY=5
# Carpeta donde se guardan las historias generadas (JSON), relativa al backend
DATA_DIR=./data
# Token secreto para poder disparar la generacion manualmente via POST /api/admin/generate
ADMIN_TOKEN=cambia-este-token
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
data
.env
*.log
+39
View File
@@ -0,0 +1,39 @@
# Backend — Historias Incompletas
API en Node/Express (TypeScript) que sirve el mazo de historias "actualizado"
y lo regenera una vez al día llamando a la API de Gemini.
## Endpoints
- `GET /api/health` — chequeo de salud.
- `GET /api/stories` — último lote de historias generado. `204` si todavía
no se generó ninguno (el cliente debe usar su set default en ese caso).
- `POST /api/admin/generate` — dispara una generación manual con Gemini.
Requiere header `x-admin-token` igual a `ADMIN_TOKEN`.
## Desarrollo
```bash
npm install
cp .env.example .env # completa GEMINI_API_KEY y ADMIN_TOKEN
npm run dev # http://localhost:8787
npm run generate # genera un lote nuevo a mano (llama a Gemini de verdad)
```
## Producción
```bash
npm run build
npm start # corre dist/index.js
npm run generate:built # corre dist/scripts/generateDaily.js (lo usa el systemd timer)
```
Ver [`../docs/DEPLOY.md`](../docs/DEPLOY.md) para el setup completo con
systemd + nginx en un LXC de Debian.
## Almacenamiento
Las historias generadas se guardan como JSON plano en `data/` (configurable
con `DATA_DIR`): un archivo por día (`YYYY-MM-DD.json`) y `latest.json`, que
es lo que sirve `GET /api/stories`. No hay base de datos — a este volumen
(5 historias/día) un archivo JSON con escritura atómica alcanza y sobra.
+1555
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "historias-backend",
"version": "1.0.0",
"private": true,
"description": "API que sirve el mazo diario de historias y genera 5 historias nuevas por dia con Gemini",
"type": "module",
"engines": {
"node": ">=20"
},
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.json",
"start": "node dist/index.js",
"generate": "tsx src/scripts/generateDaily.ts",
"generate:built": "node dist/scripts/generateDaily.js"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^22.9.0",
"tsx": "^4.19.2",
"typescript": "^5.6.3"
}
}
+18
View File
@@ -0,0 +1,18 @@
import "dotenv/config";
import path from "node:path";
function required(name: string, value: string | undefined, fallback?: string): string {
if (value && value.length > 0) return value;
if (fallback !== undefined) return fallback;
throw new Error(`Falta la variable de entorno ${name}`);
}
export const config = {
port: Number(process.env.PORT ?? 8787),
corsOrigin: process.env.CORS_ORIGIN ?? "*",
geminiApiKey: process.env.GEMINI_API_KEY ?? "",
geminiModel: process.env.GEMINI_MODEL ?? "gemini-2.5-flash",
storiesPerDay: Number(process.env.STORIES_PER_DAY ?? 5),
dataDir: path.resolve(process.cwd(), process.env.DATA_DIR ?? "./data"),
adminToken: required("ADMIN_TOKEN", process.env.ADMIN_TOKEN, "cambia-este-token"),
};
+105
View File
@@ -0,0 +1,105 @@
import { config } from "./config.js";
import { GeminiStoryBatchSchema, type Story } from "./storySchema.js";
const GEMINI_ENDPOINT = (model: string) =>
`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`;
// Subconjunto de OpenAPI que acepta el "structured output" de Gemini.
const RESPONSE_SCHEMA = {
type: "OBJECT",
properties: {
stories: {
type: "ARRAY",
items: {
type: "OBJECT",
properties: {
id: { type: "STRING" },
title: { type: "STRING" },
difficulty: { type: "STRING", enum: ["easy", "medium", "hard"] },
tags: { type: "ARRAY", items: { type: "STRING" } },
teaser: { type: "STRING" },
hints: { type: "ARRAY", items: { type: "STRING" } },
solution: { type: "STRING" },
},
required: ["id", "title", "difficulty", "tags", "teaser", "hints", "solution"],
},
},
},
required: ["stories"],
};
function buildPrompt(count: number, avoidTitles: string[]): string {
const avoidList = avoidTitles.length
? `Evita repetir o parafrasear estos titulos ya usados: ${avoidTitles.join(", ")}.`
: "";
return `Sos un escritor experto en acertijos narrativos de pensamiento lateral, en el estilo del juego de mesa "historias negras"/"black stories": se cuenta un enigma breve y desconcertante (el "teaser"), y los jugadores deben adivinar la explicacion completa (la "solution") haciendo preguntas de si/no.
Genera exactamente ${count} historias completamente ORIGINALES en español (no copies acertijos clasicos ni de ningun juego comercial existente). Cada historia debe tener:
- id: slug corto en minusculas separado por guiones, unico, derivado del titulo.
- title: titulo corto y evocador.
- difficulty: "easy", "medium" o "hard", variando entre las ${count} historias.
- tags: 1 a 3 palabras clave en minusculas.
- teaser: 2 a 4 frases. Presenta una situacion extraña o aparentemente inexplicable, resoluble con preguntas de si/no. No debe insinuar la solucion.
- hints: entre 3 y 4 pistas progresivas (de mas vaga a mas reveladora) que el narrador puede leer si los jugadores estan trabados, sin regalar la solucion completa en las primeras.
- solution: la explicacion completa y coherente que resuelve el enigma, respondiendo a todo lo planteado en el teaser. 4 a 8 frases.
Las historias deben ser aptas para todo publico (sin violencia grafica extrema, sin contenido sexual), pueden ser misteriosas, agridulces o con un giro emotivo, pero siempre con una explicacion logica y satisfactoria. ${avoidList}
Devolve unicamente el JSON que respeta el schema indicado.`;
}
interface GeminiResponse {
candidates?: Array<{
content?: { parts?: Array<{ text?: string }> };
}>;
}
export async function generateStoriesWithGemini(
count: number,
avoidTitles: string[] = []
): Promise<Story[]> {
if (!config.geminiApiKey) {
throw new Error("GEMINI_API_KEY no esta configurada");
}
const body = {
contents: [{ parts: [{ text: buildPrompt(count, avoidTitles) }] }],
generationConfig: {
responseMimeType: "application/json",
responseSchema: RESPONSE_SCHEMA,
temperature: 1,
},
};
const res = await fetch(`${GEMINI_ENDPOINT(config.geminiModel)}?key=${config.geminiApiKey}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const errText = await res.text().catch(() => "");
throw new Error(`Gemini API error ${res.status}: ${errText}`);
}
const data = (await res.json()) as GeminiResponse;
const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
if (!text) {
throw new Error("Respuesta de Gemini sin contenido de texto");
}
const parsedJson = JSON.parse(text);
const validated = GeminiStoryBatchSchema.parse(parsedJson);
// Aseguramos ids unicos por si el modelo repite alguno.
const seen = new Set<string>();
for (const story of validated.stories) {
let id = story.id;
while (seen.has(id)) id = `${id}-2`;
seen.add(id);
story.id = id;
}
return validated.stories.slice(0, count);
}
+19
View File
@@ -0,0 +1,19 @@
import cors from "cors";
import express from "express";
import { config } from "./config.js";
import { storiesRouter } from "./routes/stories.js";
const app = express();
app.use(cors({ origin: config.corsOrigin }));
app.use(express.json());
app.get("/api/health", (_req, res) => {
res.json({ ok: true });
});
app.use("/api", storiesRouter);
app.listen(config.port, () => {
console.log(`API de historias escuchando en http://localhost:${config.port}`);
});
+42
View File
@@ -0,0 +1,42 @@
import { Router } from "express";
import { config } from "../config.js";
import { generateStoriesWithGemini } from "../gemini.js";
import { getLatestStories, saveDailyStories } from "../storyStore.js";
export const storiesRouter = Router();
/** GET /api/stories: devuelve el ultimo lote generado, o 204 si no hay ninguno todavia. */
storiesRouter.get("/stories", async (_req, res) => {
const latest = await getLatestStories();
if (!latest) {
res.status(204).end();
return;
}
res.set("Cache-Control", "public, max-age=300");
res.json(latest);
});
/**
* POST /api/admin/generate: dispara manualmente una generacion con Gemini.
* Requiere header "x-admin-token" que coincida con ADMIN_TOKEN.
* Pensado para pruebas manuales; la generacion diaria real la dispara el
* systemd timer llamando al script generateDaily.
*/
storiesRouter.post("/admin/generate", async (req, res) => {
const token = req.header("x-admin-token");
if (!token || token !== config.adminToken) {
res.status(401).json({ error: "token invalido" });
return;
}
try {
const previous = await getLatestStories();
const avoidTitles = previous?.stories.map((s) => s.title) ?? [];
const stories = await generateStoriesWithGemini(config.storiesPerDay, avoidTitles);
const saved = await saveDailyStories(stories);
res.json(saved);
} catch (err) {
console.error("Error generando historias:", err);
res.status(500).json({ error: "fallo la generacion", detail: String(err) });
}
});
+29
View File
@@ -0,0 +1,29 @@
/**
* Script pensado para correr una vez al dia via systemd timer / cron.
* Genera STORIES_PER_DAY historias nuevas con Gemini y las guarda como el
* nuevo "latest.json" que sirve la API.
*
* Uso: npm run generate (dev, con tsx)
* npm run generate:built (prod, tras "npm run build")
*/
import { config } from "../config.js";
import { generateStoriesWithGemini } from "../gemini.js";
import { getLatestStories, saveDailyStories } from "../storyStore.js";
async function main() {
console.log(`[${new Date().toISOString()}] Generando ${config.storiesPerDay} historias nuevas con ${config.geminiModel}...`);
const previous = await getLatestStories();
const avoidTitles = previous?.stories.map((s) => s.title) ?? [];
const stories = await generateStoriesWithGemini(config.storiesPerDay, avoidTitles);
const saved = await saveDailyStories(stories);
console.log(`[${new Date().toISOString()}] OK: ${saved.stories.length} historias guardadas.`);
for (const s of saved.stories) console.log(` - (${s.difficulty}) ${s.title}`);
}
main().catch((err) => {
console.error("Fallo la generacion diaria:", err);
process.exitCode = 1;
});
+27
View File
@@ -0,0 +1,27 @@
import { z } from "zod";
export const DifficultySchema = z.enum(["easy", "medium", "hard"]);
export const StorySchema = z.object({
id: z.string().min(1),
title: z.string().min(1),
difficulty: DifficultySchema,
tags: z.array(z.string()).default([]),
teaser: z.string().min(1),
hints: z.array(z.string()).min(1).max(5),
solution: z.string().min(1),
});
export type Story = z.infer<typeof StorySchema>;
export const StoryListSchema = z.object({
version: z.number().int().nonnegative(),
generatedAt: z.string().nullable(),
source: z.enum(["default", "gemini"]),
stories: z.array(StorySchema),
});
export type StoryList = z.infer<typeof StoryListSchema>;
// Esquema que le pedimos a Gemini que respete (sin el wrapper de version/source).
export const GeminiStoryBatchSchema = z.object({
stories: z.array(StorySchema).min(1),
});
+66
View File
@@ -0,0 +1,66 @@
import { promises as fs } from "node:fs";
import path from "node:path";
import { config } from "./config.js";
import { StoryListSchema, type Story, type StoryList } from "./storySchema.js";
const LATEST_FILE = "latest.json";
async function ensureDataDir(): Promise<void> {
await fs.mkdir(config.dataDir, { recursive: true });
}
function dailyFileName(date: Date): string {
const iso = date.toISOString().slice(0, 10); // YYYY-MM-DD
return `${iso}.json`;
}
/** Escritura atomica: escribe a un archivo temporal y luego renombra. */
async function writeJsonAtomic(filePath: string, data: unknown): Promise<void> {
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
await fs.writeFile(tmpPath, JSON.stringify(data, null, 2), "utf8");
await fs.rename(tmpPath, filePath);
}
/**
* Guarda un nuevo lote de historias generado hoy, tanto en un archivo fechado
* (historial) como en latest.json (lo que sirve la API).
*/
export async function saveDailyStories(stories: Story[]): Promise<StoryList> {
await ensureDataDir();
const list: StoryList = {
version: Date.now(),
generatedAt: new Date().toISOString(),
source: "gemini",
stories,
};
StoryListSchema.parse(list);
const dailyPath = path.join(config.dataDir, dailyFileName(new Date()));
const latestPath = path.join(config.dataDir, LATEST_FILE);
await writeJsonAtomic(dailyPath, list);
await writeJsonAtomic(latestPath, list);
return list;
}
/**
* Devuelve el ultimo lote de historias generado (puede ser de un dia anterior
* si la generacion de hoy todavia no corrio o fallo). Si nunca se genero
* nada, devuelve null y el cliente debe usar su set default embebido.
*/
export async function getLatestStories(): Promise<StoryList | null> {
const latestPath = path.join(config.dataDir, LATEST_FILE);
try {
const raw = await fs.readFile(latestPath, "utf8");
const parsed = StoryListSchema.parse(JSON.parse(raw));
return parsed;
} catch (err: unknown) {
if (isNodeError(err) && err.code === "ENOENT") return null;
throw err;
}
}
function isNodeError(err: unknown): err is NodeJS.ErrnoException {
return typeof err === "object" && err !== null && "code" in err;
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": false,
"sourceMap": false
},
"include": ["src"]
}
+31
View File
@@ -0,0 +1,31 @@
# Ejemplo de virtual host para nginx en el LXC de Debian.
# Sirve el frontend (build estatica de Vite) y reversa-proxea /api al backend
# Node que corre en localhost:8787 via el servicio systemd story-api.
#
# Copialo a /etc/nginx/sites-available/historias, ajusta el dominio y la ruta,
# y despues:
# ln -s /etc/nginx/sites-available/historias /etc/nginx/sites-enabled/historias
# nginx -t && systemctl reload nginx
# Para TLS con Let's Encrypt: certbot --nginx -d tu-dominio.com
server {
listen 80;
listen [::]:80;
server_name tu-dominio.com;
root /opt/historias/frontend/dist;
index index.html;
location /api/ {
proxy_pass http://127.0.0.1:8787/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri /index.html;
}
}
+22
View File
@@ -0,0 +1,22 @@
[Unit]
Description=API de Historias Incompletas
After=network.target
[Service]
Type=simple
User=historias
Group=historias
WorkingDirectory=/opt/historias/backend
EnvironmentFile=/opt/historias/backend/.env
ExecStart=/usr/bin/node /opt/historias/backend/dist/index.js
Restart=on-failure
RestartSec=5
# Endurecimiento basico del sandbox systemd
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/historias/backend/data
PrivateTmp=true
[Install]
WantedBy=multi-user.target
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=Genera 5 historias nuevas del dia con Gemini
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=historias
Group=historias
WorkingDirectory=/opt/historias/backend
EnvironmentFile=/opt/historias/backend/.env
ExecStart=/usr/bin/node /opt/historias/backend/dist/scripts/generateDaily.js
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Dispara la generacion diaria de historias (story-generate.service)
[Timer]
OnCalendar=*-*-* 06:00:00
RandomizedDelaySec=600
Persistent=true
[Install]
WantedBy=timers.target
+114
View File
@@ -0,0 +1,114 @@
# Deploy en un LXC de Debian (sin Docker, sin proveedor externo)
Esta guia asume un contenedor LXC Debian 12 con acceso root, sin Docker, y
que vas a exponer la app en tu propio dominio con nginx + Let's Encrypt.
## 1. Preparar el sistema
```bash
apt update && apt upgrade -y
apt install -y curl git nginx certbot python3-certbot-nginx
# Node.js 22 LTS via NodeSource
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
apt install -y nodejs
node -v # deberia mostrar v22.x
```
Crea un usuario de sistema dedicado (sin login) para correr la app:
```bash
useradd --system --create-home --home-dir /opt/historias --shell /usr/sbin/nologin historias
```
## 2. Clonar y preparar el proyecto
```bash
cd /opt/historias
git clone <url-de-tu-repo> app
cd app
# Backend
cd backend
npm ci
cp .env.example .env
# Editar .env: GEMINI_API_KEY, ADMIN_TOKEN, CORS_ORIGIN=https://tu-dominio.com
npm run build
# Frontend
cd ../frontend
npm ci
cp .env.example .env
# Editar .env: VITE_API_URL=https://tu-dominio.com
npm run build # genera frontend/dist, servido por nginx
chown -R historias:historias /opt/historias
```
> Los paths de los ejemplos en `deploy/*.service` asumen que el repo termina
> viviendo en `/opt/historias/backend` y `/opt/historias/frontend`. Si tu
> checkout usa otra carpeta (por ejemplo `/opt/historias/app/backend`),
> ajusta `WorkingDirectory` y `ExecStart` en los archivos `.service` antes de
> instalarlos.
## 3. Servicio de la API (systemd)
```bash
cp deploy/story-api.service /etc/systemd/system/story-api.service
systemctl daemon-reload
systemctl enable --now story-api
systemctl status story-api
curl http://127.0.0.1:8787/api/health # {"ok":true}
```
## 4. Generacion diaria de historias (systemd timer)
```bash
cp deploy/story-generate.service /etc/systemd/system/story-generate.service
cp deploy/story-generate.timer /etc/systemd/system/story-generate.timer
systemctl daemon-reload
systemctl enable --now story-generate.timer
# Probar la generacion manualmente una vez (usa tu GEMINI_API_KEY real):
systemctl start story-generate.service
journalctl -u story-generate.service -n 50 --no-pager
```
El timer corre todos los dias a las 06:00 (hora del sistema del LXC) con
hasta 10 minutos de retraso aleatorio. Ajusta `OnCalendar` en el `.timer` si
preferis otro horario.
## 5. nginx + TLS
```bash
cp deploy/nginx.conf.example /etc/nginx/sites-available/historias
# Editar server_name y la ruta de "root" si corresponde
ln -s /etc/nginx/sites-available/historias /etc/nginx/sites-enabled/historias
nginx -t && systemctl reload nginx
certbot --nginx -d tu-dominio.com
```
## 6. Actualizar la app despues de un cambio
```bash
cd /opt/historias/app
git pull
cd backend && npm ci && npm run build
cd ../frontend && npm ci && npm run build
systemctl restart story-api
```
## Notas
- Las historias generadas se guardan en `backend/data/*.json` (no se versionan
en git). Hace backup de esa carpeta si te importa el historial generado.
- Si Gemini falla un dia (cuota, red, etc.), `story-generate.service` termina
con error y `latest.json` simplemente no se actualiza: la API sigue
sirviendo el ultimo lote bueno, y si nunca hubo ninguno, el cliente cae a
las historias default embebidas en la app.
- `ADMIN_TOKEN` protege `POST /api/admin/generate`, util para forzar una
generacion manual sin esperar al timer:
`curl -X POST https://tu-dominio.com/api/admin/generate -H "x-admin-token: <token>"`
- Revisa logs con `journalctl -u story-api -f` y `journalctl -u story-generate -f`.
+4
View File
@@ -0,0 +1,4 @@
# URL absoluta de la API del backend (tu dominio). Se usa tanto en la build
# web como en la app empaquetada con Capacitor (esta ultima no tiene "same
# origin", asi que siempre necesita una URL absoluta).
VITE_API_URL=https://tu-dominio.com
+35
View File
@@ -0,0 +1,35 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
.env
# Android (Capacitor)
android/app/build
android/build
android/.gradle
android/captures
android/local.properties
android/.idea
*.keystore
*.jks
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+34
View File
@@ -0,0 +1,34 @@
# Frontend — Historias Incompletas
App React + Vite. Se empaqueta como sitio web y, con Capacitor, como APK
Android.
## Desarrollo
```bash
npm install
cp .env.example .env # VITE_API_URL apuntando a tu backend
npm run dev
```
## Build web
```bash
npm run build # genera dist/
```
## APK (Capacitor)
Ver instrucciones completas en el [README raíz](../README.md#frontend-apk-con-capacitor).
Resumen: `npm run cap:sync` (build + `cap sync android`) y después
`npm run android:open` o `cd android && ./gradlew assembleDebug` con Android
SDK/JDK instalados.
## Estructura relevante
- `src/api.ts` — obtiene el mazo de historias del backend, con fallback a
cache local y al set default embebido.
- `src/data/defaultStories.json` — historias por defecto (contenido
original).
- `src/screens/` — Home, selector de historia y vista del narrador.
- `capacitor.config.ts` — config de la app nativa.
+101
View File
@@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+54
View File
@@ -0,0 +1,54 @@
apply plugin: 'com.android.application'
android {
namespace = "com.historiasincompletas.app"
compileSdk = rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.historiasincompletas.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
@@ -0,0 +1,19 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
@@ -0,0 +1,5 @@
package com.historiasincompletas.app;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">Historias Incompletas</string>
<string name="title_activity_main">Historias Incompletas</string>
<string name="package_name">com.historiasincompletas.app</string>
<string name="custom_url_scheme">com.historiasincompletas.app</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
+29
View File
@@ -0,0 +1,29 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
@@ -0,0 +1,3 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
+22
View File
@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+16
View File
@@ -0,0 +1,16 @@
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
}
+13
View File
@@ -0,0 +1,13 @@
import type { CapacitorConfig } from "@capacitor/cli";
const config: CapacitorConfig = {
appId: "com.historiasincompletas.app",
appName: "Historias Incompletas",
webDir: "dist",
backgroundColor: "#14101c",
android: {
backgroundColor: "#14101c",
},
};
export default config;
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#14101c" />
<title>Historias Incompletas</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2476
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "historias-frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview",
"cap:sync": "npm run build && npx cap sync android",
"android:open": "npx cap open android"
},
"dependencies": {
"@capacitor/android": "^8.5.0",
"@capacitor/core": "^8.5.0",
"react": "^19.2.8",
"react-dom": "^19.2.8"
},
"devDependencies": {
"@capacitor/cli": "^8.5.0",
"@types/node": "^24.13.3",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.4",
"oxlint": "^1.75.0",
"typescript": "~6.0.2",
"vite": "^8.2.0"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated

After

Width:  |  Height:  |  Size: 9.3 KiB

+71
View File
@@ -0,0 +1,71 @@
import { useEffect, useState } from "react";
import { loadStories } from "./api";
import Home from "./screens/Home";
import NarratorView from "./screens/NarratorView";
import StoryPicker from "./screens/StoryPicker";
import { getUsedStoryIds, markStoryUsed, resetUsedStories } from "./state/gameStorage";
import type { Story, StoryList } from "./types";
type Screen = "home" | "picker" | "narrator";
function App() {
const [screen, setScreen] = useState<Screen>("home");
const [storyList, setStoryList] = useState<StoryList | null>(null);
const [loading, setLoading] = useState(true);
const [usedIds, setUsedIds] = useState<string[]>(getUsedStoryIds());
const [activeStory, setActiveStory] = useState<Story | null>(null);
useEffect(() => {
loadStories()
.then(setStoryList)
.finally(() => setLoading(false));
}, []);
function handlePick(story: Story) {
setActiveStory(story);
setScreen("narrator");
}
function handleFinishStory() {
if (activeStory) {
markStoryUsed(activeStory.id);
setUsedIds(getUsedStoryIds());
}
setActiveStory(null);
setScreen("picker");
}
function handleResetUsed() {
resetUsedStories();
setUsedIds([]);
}
return (
<div className="app-shell">
{screen === "home" && (
<Home
loading={loading}
storyList={storyList}
usedCount={usedIds.length}
onPlay={() => setScreen("picker")}
onResetUsed={handleResetUsed}
/>
)}
{screen === "picker" && storyList && (
<StoryPicker
stories={storyList.stories}
usedIds={usedIds}
onPick={handlePick}
onBack={() => setScreen("home")}
/>
)}
{screen === "narrator" && activeStory && (
<NarratorView story={activeStory} onFinish={handleFinishStory} />
)}
</div>
);
}
export default App;
+65
View File
@@ -0,0 +1,65 @@
import defaultStoriesRaw from "./data/defaultStories.json";
import type { StoryList } from "./types";
const API_URL = (import.meta.env.VITE_API_URL ?? "").replace(/\/+$/, "");
const CACHE_KEY = "historias.cachedServerList.v1";
const FETCH_TIMEOUT_MS = 5000;
const defaultStories = defaultStoriesRaw as StoryList;
function readCachedServerList(): StoryList | null {
try {
const raw = localStorage.getItem(CACHE_KEY);
if (!raw) return null;
return JSON.parse(raw) as StoryList;
} catch {
return null;
}
}
function writeCachedServerList(list: StoryList): void {
try {
localStorage.setItem(CACHE_KEY, JSON.stringify(list));
} catch {
// localStorage puede fallar (modo privado, cuota llena); no es critico.
}
}
async function fetchWithTimeout(url: string, ms: number): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await fetch(url, { signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
/**
* Intenta obtener la lista de historias actualizada del backend.
* Si el backend no responde, no tiene historias todavia (204), o falla la
* red: usa la ultima lista del servidor que haya quedado cacheada localmente
* y, si tampoco existe, cae en el set de historias default embebido en la app.
*/
export async function loadStories(): Promise<StoryList> {
try {
const res = await fetchWithTimeout(`${API_URL}/api/stories`, FETCH_TIMEOUT_MS);
if (res.status === 200) {
const data = (await res.json()) as StoryList;
if (Array.isArray(data.stories) && data.stories.length > 0) {
writeCachedServerList(data);
return data;
}
}
// 204 (sin historias generadas aun) u otra respuesta vacia: seguimos abajo.
} catch {
// sin conexion, timeout, CORS, etc.: seguimos abajo.
}
const cached = readCachedServerList();
if (cached && cached.stories.length > 0) {
return { ...cached, source: "cache" };
}
return defaultStories;
}
+215
View File
@@ -0,0 +1,215 @@
{
"version": 1,
"generatedAt": null,
"source": "default",
"stories": [
{
"id": "faro-apagado",
"title": "El faro apagado",
"difficulty": "medium",
"tags": ["misterio", "costa"],
"teaser": "Un farero apaga su faro a propósito una noche de tormenta. A la mañana siguiente lo arrestan. ¿Por qué?",
"hints": [
"El faro seguía funcionando perfectamente; nadie lo dañó.",
"Esa noche pasó un barco que no debía ser visto por nadie más.",
"El farero no ganó dinero por lo que hizo, y volvería a hacerlo."
],
"solution": "El faro marcaba la frontera marítima entre dos países en conflicto. Esa noche, un pequeño bote cruzaba la zona llevando a la hermana del farero, que huía de una zona de guerra. Si la luz del faro la iluminaba, la patrulla fronteriza la detectaría. El farero apagó la luz el tiempo justo para que el bote pasara sin ser visto. La patrulla, extrañada por la oscuridad repentina, investigó y descubrió que el apagado había sido intencional; lo arrestaron por poner en riesgo la navegación, sin saber jamás el verdadero motivo."
},
{
"id": "foto-sin-rostro",
"title": "La foto sin rostro",
"difficulty": "easy",
"tags": ["familia", "objetos"],
"teaser": "Una mujer guarda con cariño una fotografía en la que no se ve ningún rostro. Aun así, es su recuerdo más preciado.",
"hints": [
"La foto no está dañada ni borrosa.",
"En la foto sí hay personas.",
"La cámara la sostenía alguien muy importante para ella, por primera vez."
],
"solution": "La fotografía muestra la espalda de la mujer y de su pareja, tomados de la mano, mirando hacia un atardecer. La tomó su hijo de cuatro años, sosteniendo la cámara por primera vez en su vida, apuntando mal a propósito porque quería que sus padres 'miraran el sol y no a él'. Fue el primer regalo que el niño hizo sin ayuda de nadie, y por eso, aunque no se vea ningún rostro, es la foto más valiosa que tiene."
},
{
"id": "pianista-silencioso",
"title": "El pianista silencioso",
"difficulty": "medium",
"tags": ["música", "teatro"],
"teaser": "Un pianista se sienta frente al público, coloca las manos sobre el teclado y no toca ni una sola nota durante cuatro minutos y medio. El público aplaude de pie al final.",
"hints": [
"El piano funciona perfectamente.",
"El pianista no olvidó la partitura ni está enfermo.",
"El silencio era, en sí mismo, la obra."
],
"solution": "El pianista estaba interpretando una pieza compuesta deliberadamente en silencio, pensada para que el público prestara atención a los sonidos del propio teatro: la respiración de la gente, una tos lejana, el crujido de una butaca. La obra buscaba demostrar que no existe el silencio absoluto y que el ambiente mismo puede ser música. El público, que conocía la naturaleza de la pieza, aplaudió al reconocer haber 'escuchado' algo real."
},
{
"id": "regalo-repetido",
"title": "El regalo repetido",
"difficulty": "easy",
"tags": ["tradiciones", "familia"],
"teaser": "Cada año, un hombre recibe de su abuela el mismo regalo exacto: un par de calcetines de lana gris. Él los agradece siempre con lágrimas en los ojos.",
"hints": [
"No es que a la abuela se le olvide lo que ya regaló.",
"El valor no está en el objeto en sí, sino en quién los teje.",
"La abuela dejó de poder ver hace varios años."
],
"solution": "La abuela quedó ciega hace años, pero se niega a dejar de tejer para su nieto. Cada par de calcetines lo hace de memoria, guiándose solo por el tacto, y tarda meses en terminarlo. El nieto llora no por los calcetines, sino porque sabe cuánto esfuerzo y amor representa cada puntada hecha a ciegas, y porque cada par podría ser, sin que nadie lo diga en voz alta, el último."
},
{
"id": "maraton-interrumpida",
"title": "La maratón interrumpida",
"difficulty": "hard",
"tags": ["deporte", "decisiones"],
"teaser": "Una corredora va en primer lugar, a pocos metros de ganar su primera maratón, y se detiene en seco para ayudar a otra corredora desconocida. Pierde la carrera a propósito.",
"hints": [
"La otra corredora no era una rival cercana en la clasificación.",
"No hubo ninguna lesión grave de por medio.",
"Algo que la otra corredora llevaba consigo era más importante que la medalla."
],
"solution": "La corredora desconocida llevaba, prendido en la ropa, un pequeño cartel con la foto de su hijo desaparecido y un número de contacto, como hacen algunos atletas para dar visibilidad a causas personales durante eventos masivos. A pocos metros de la meta, esa corredora se desplomó por la deshidratación y el cartel cayó lejos de su alcance. La líder, reconociendo la foto porque la había visto en las noticias esa misma semana, se detuvo para recogerlo y colocarlo de nuevo junto a ella antes de que las cámaras de la transmisión pasaran por ahí, sabiendo que esa visibilidad valía más que cualquier medalla."
},
{
"id": "paraguas-seco",
"title": "El paraguas seco",
"difficulty": "medium",
"tags": ["lluvia", "cotidiano"],
"teaser": "Un hombre camina bajo la lluvia con un paraguas abierto, pero deja que se moje por completo. El paraguas permanece seco por dentro y por fuera solo en el mango.",
"hints": [
"El paraguas funciona correctamente y no tiene agujeros.",
"El hombre no está probando el paraguas ni jugando.",
"Alguien muy pequeño va debajo de él, no el hombre."
],
"solution": "El hombre lleva a su hija recién nacida en un portabebés pegado al pecho, cubierta bajo su propio abrigo, y sostiene el paraguas inclinado completamente hacia adelante y hacia abajo para proteger a la bebé del viento y la lluvia, dejando que él mismo reciba toda el agua. El único punto seco del paraguas es el mango, que él sostiene con la mano."
},
{
"id": "correo-sin-remitente",
"title": "El correo sin remitente",
"difficulty": "hard",
"tags": ["cartas", "pasado"],
"teaser": "Durante quince años, una mujer recibe una carta anónima el mismo día cada año, sin remitente ni pistas. Al enterarse de que las cartas se detuvieron, se pone feliz en lugar de triste.",
"hints": [
"Las cartas nunca contenían amenazas ni nada negativo.",
"El remitente tenía una razón para no poder firmarlas.",
"Que las cartas se detuvieran era, en realidad, la señal que ella esperaba."
],
"solution": "Las cartas las escribía su hermano, que ingresó a un programa de protección de testigos tras declarar contra una organización criminal y no podía tener ningún contacto directo con su familia. Cada año, en la fecha del cumpleaños de ella, arriesgaba enviar una carta sin firma a través de un intermediario solo para hacerle saber que seguía con vida. Cuando las cartas se detuvieron, ella entendió —por una señal acordada de antemano con las autoridades años atrás— que significaba que el peligro finalmente había terminado y que pronto podrían reencontrarse."
},
{
"id": "receta-incompleta",
"title": "La receta incompleta",
"difficulty": "easy",
"tags": ["cocina", "legado"],
"teaser": "Una chef muy famosa se niega a completar por escrito la receta de su platillo más famoso, aunque se lo pidan editoriales de todo el mundo pagando fortunas.",
"hints": [
"No es por proteger el negocio ni por dinero.",
"La receta sí se puede aprender, pero de una sola manera.",
"Ella también la aprendió así, de otra persona, sin papel de por medio."
],
"solution": "La receta se la enseñó su madre cocinando juntas, corrigiendo cada paso con las manos, el olfato y la mirada, sin usar jamás una medida exacta. La chef considera que poner la receta en papel destruiría lo que la hace especial: que solo se puede transmitir de persona a persona, cocinando codo a codo, tal como ella la aprendió. Por eso solo la enseña en persona, a quien esté dispuesto a sentarse con ella en la cocina."
},
{
"id": "reloj-parado",
"title": "El reloj parado",
"difficulty": "medium",
"tags": ["objetos", "duelo"],
"teaser": "En la sala de un hombre hay un reloj de pared detenido exactamente a las 3:17. Se niega a repararlo o a cambiarle la pila, aunque funciona perfectamente bien.",
"hints": [
"El reloj no está roto por dentro.",
"Esa hora marca algo que ya pasó, no algo que vaya a pasar.",
"Alguien se detuvo a esa hora, no el reloj."
],
"solution": "A las 3:17 de la tarde de un día específico, el hombre recibió la llamada que le avisaba que su esposa había fallecido en un accidente. Ese reloj estaba en la habitación cuando colgó el teléfono, y desde entonces decidió detenerlo en esa hora exacta como un pequeño monumento privado, un recordatorio silencioso que solo él entiende cada vez que entra a esa sala."
},
{
"id": "anillo-en-el-pan",
"title": "El anillo en el pan",
"difficulty": "hard",
"tags": ["panadería", "secretos"],
"teaser": "Cada mañana, un panadero esconde un anillo distinto dentro de una sola hogaza de pan, entre cientos que hornea. Nunca revela cuál es la hogaza elegida, ni cobra más por ella.",
"hints": [
"No busca ganar dinero ni publicidad con esto.",
"No sabe quién comprará esa hogaza en particular.",
"Alguna vez, hace mucho, alguien hizo lo mismo por él, sin saberlo tampoco."
],
"solution": "Cuando era joven y atravesaba una situación económica muy difícil, compró una hogaza de pan cualquiera y encontró dentro un anillo de oro que le permitió salir adelante durante meses. Nunca supo quién lo había puesto ahí ni por qué, y desde entonces decidió replicar ese gesto anónimo cada día de su vida, con la esperanza de que, alguna vez, la persona correcta encuentre esa hogaza en el momento en que más lo necesite, tal como le pasó a él."
},
{
"id": "ultima-llamada",
"title": "La última llamada",
"difficulty": "medium",
"tags": ["tecnología", "familia"],
"teaser": "Un hombre paga cada mes una costosa línea telefónica que no usa para hablar con nadie. Solo la mantiene activa para poder escuchar un mensaje.",
"hints": [
"El mensaje no es suyo.",
"No puede guardar ese audio en ningún otro lugar.",
"La persona que dejó el mensaje ya no puede dejar otro."
],
"solution": "En ese número quedó grabado, en el buzón de voz, el último mensaje que le dejó su padre antes de morir repentinamente. Por razones técnicas del proveedor, el mensaje no se puede descargar ni transferir a otro dispositivo sin perderse: solo existe mientras la línea permanezca activa. Por eso paga la mensualidad cada mes, únicamente para poder marcar ese número de vez en cuando y volver a escuchar, por unos segundos, la voz de su padre."
},
{
"id": "espejo-cubierto",
"title": "El espejo cubierto",
"difficulty": "easy",
"tags": ["hogar", "costumbres"],
"teaser": "En una casa, cubren con una tela todos los espejos durante exactamente siete días. Nadie en la familia se queja ni pregunta por qué.",
"hints": [
"No es por decoración ni por limpieza.",
"Es una costumbre que se repite desde hace generaciones.",
"Está relacionada con honrar a alguien que ya no está."
],
"solution": "La familia sigue una tradición de duelo, similar a costumbres reales de distintas culturas, en la que se cubren los espejos durante los primeros siete días tras la muerte de un familiar cercano, como símbolo de que en ese período el foco no debe estar en la propia imagen ni en la vanidad, sino en recordar y acompañar a quien se fue. Nadie pregunta porque todos en la familia crecieron con esa misma costumbre."
},
{
"id": "bote-vacio",
"title": "El bote vacío",
"difficulty": "hard",
"tags": ["mar", "rescate"],
"teaser": "Un pescador encuentra un bote a la deriva, completamente vacío, y en lugar de remolcarlo a la orilla, lo hunde él mismo en altamar.",
"hints": [
"El bote no estaba dañado ni era peligroso para la navegación.",
"No lo hundió por accidente ni por rabia.",
"Alguien necesitaba, con urgencia, que ese bote nunca fuera encontrado."
],
"solution": "El bote pertenecía a un amigo suyo que había fingido su propia desaparición en el mar para escapar de deudas y amenazas graves, y ya se encontraba a salvo en tierra, con una nueva identidad, gracias a la ayuda del pescador. Si el bote vacío era hallado y remolcado a la costa, reabriría la investigación y pondría en riesgo el plan; hundiéndolo en aguas profundas, el pescador aseguraba que la historia de la desaparición se diera por cerrada para siempre."
},
{
"id": "partida-de-ajedrez",
"title": "La partida de ajedrez",
"difficulty": "medium",
"tags": ["juegos", "amistad"],
"teaser": "Dos ancianos juegan ajedrez en el mismo parque todos los días desde hace veinte años. Ninguno de los dos mueve jamás una sola pieza.",
"hints": [
"El tablero y las piezas están en perfectas condiciones.",
"No es que se hayan olvidado de cómo jugar.",
"Lo importante de esas tardes nunca fue ganar la partida."
],
"solution": "Los dos hombres se conocieron hace veinte años, cada uno recién viudo y sin nadie más con quien hablar, y desde entonces se reúnen cada tarde con el tablero como excusa. Ambos saben, sin decirlo, que ninguno tiene verdadero interés en jugar: el tablero es simplemente el pretexto que les permite sentarse juntos, en silencio o conversando, sin que resulte extraño para dos hombres de su generación admitir que solo se necesitan compañía."
},
{
"id": "testigo-ciego",
"title": "El testigo ciego",
"difficulty": "hard",
"tags": ["misterio", "justicia"],
"teaser": "En un juicio, la única testigo que puede identificar al culpable es ciega de nacimiento. Su testimonio es el que finalmente resuelve el caso.",
"hints": [
"Ella no vio nada con los ojos, pero sí percibió algo clave.",
"Su testimonio no habla de rostros ni de ropa.",
"Confiaron en uno de sus sentidos más entrenados."
],
"solution": "La testigo, al ser ciega desde su nacimiento, había desarrollado un oído extraordinariamente entrenado. Esa noche escuchó una discusión desde su departamento y pudo reconocer, con total seguridad, la voz y el particular tintineo de las llaves de quien discutía, un sonido que había memorizado por haberlo escuchado repetidas veces por ser vecino del edificio. Su testimonio auditivo, corroborado con otras pruebas, fue lo que permitió identificar al culpable, sin haber 'visto' nada en el sentido convencional."
},
{
"id": "cancion-prohibida",
"title": "La canción prohibida",
"difficulty": "medium",
"tags": ["música", "trabajo"],
"teaser": "En una radio local, un locutor tiene terminantemente prohibido volver a poner una canción específica al aire. La prohibición no viene de la dirección de la emisora, sino de él mismo.",
"hints": [
"La canción no tiene ningún problema legal ni de derechos.",
"Es una canción que en algún momento le gustaba mucho.",
"La última vez que la puso al aire, algo cambió para siempre."
],
"solution": "Esa era la canción que sonaba en su auto la noche del accidente en el que perdió a su esposa, mientras conducían juntos hacia su casa. Volver a escucharla, incluso brevemente al ponerla al aire, le provoca un dolor tan intenso que decidió, por su propia salud, prohibirse a sí mismo programarla jamás de nuevo, y se lo pidió también a sus compañeros de la radio."
}
]
}
+262
View File
@@ -0,0 +1,262 @@
:root {
--bg: #14101c;
--bg-elevated: #1e1830;
--bg-card: #241d3a;
--text: #ede9f7;
--text-dim: #b3a9cc;
--accent: #b98cff;
--accent-strong: #d6b8ff;
--danger: #ff6b6b;
--danger-strong: #ff8f8f;
--border: #3a3155;
--easy: #6bcf9c;
--medium: #e8c15a;
--hard: #ff8080;
color-scheme: dark;
font: 16px/1.5 system-ui, "Segoe UI", Roboto, sans-serif;
color: var(--text);
background: var(--bg);
}
* {
box-sizing: border-box;
}
html,
body,
#root {
height: 100%;
margin: 0;
}
body {
background: radial-gradient(circle at top, #241d3a 0%, #14101c 60%);
min-height: 100vh;
}
.app-shell {
max-width: 640px;
margin: 0 auto;
padding: 1.25rem 1.25rem 3rem;
min-height: 100vh;
}
h1,
h2,
h3 {
color: var(--accent-strong);
line-height: 1.25;
}
h1 {
font-size: 1.9rem;
margin-bottom: 0.25rem;
}
.subtitle {
color: var(--text-dim);
margin-top: 0;
}
button {
font: inherit;
cursor: pointer;
border-radius: 12px;
border: 1px solid var(--border);
padding: 0.85rem 1.1rem;
background: var(--bg-elevated);
color: var(--text);
width: 100%;
margin-top: 0.6rem;
transition: transform 0.05s ease, background 0.15s ease;
}
button:active {
transform: scale(0.98);
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
button.primary {
background: var(--accent);
color: #1a1225;
font-weight: 600;
border: none;
}
button.ghost {
background: transparent;
}
button.danger {
background: var(--danger);
color: #2a0f0f;
font-weight: 600;
border: none;
}
.rules-card,
.teaser-card,
.hints-card,
.solution-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 16px;
padding: 1rem 1.15rem;
margin: 1rem 0;
}
.rules-card ol {
padding-left: 1.1rem;
margin: 0.5rem 0 0;
}
.status-row {
margin: 0.75rem 0;
}
.badge {
display: inline-block;
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.35rem 0.8rem;
font-size: 0.85rem;
color: var(--text-dim);
}
.picker-header {
display: flex;
align-items: center;
gap: 0.75rem;
}
.picker-header button {
width: auto;
margin-top: 0;
}
.picker-header h2 {
margin: 0;
}
.picker-controls {
display: flex;
align-items: center;
gap: 1rem;
margin: 1rem 0;
}
.picker-controls .primary {
flex: 1;
margin-top: 0;
}
.checkbox {
display: flex;
align-items: center;
gap: 0.4rem;
color: var(--text-dim);
font-size: 0.9rem;
white-space: nowrap;
}
.story-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.story-card {
text-align: left;
margin-top: 0;
background: var(--bg-card);
position: relative;
}
.story-card-title-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.5rem;
}
.story-title {
font-weight: 600;
}
.difficulty {
font-size: 0.75rem;
padding: 0.15rem 0.55rem;
border-radius: 999px;
white-space: nowrap;
color: #14101c;
}
.difficulty-easy {
background: var(--easy);
}
.difficulty-medium {
background: var(--medium);
}
.difficulty-hard {
background: var(--hard);
}
.tags {
margin-top: 0.4rem;
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
}
.tag {
font-size: 0.75rem;
color: var(--text-dim);
}
.used-flag {
display: block;
margin-top: 0.4rem;
font-size: 0.75rem;
color: var(--danger-strong);
}
.empty {
color: var(--text-dim);
text-align: center;
margin-top: 2rem;
}
.narrator-warning {
background: var(--danger);
color: #2a0f0f;
font-weight: 600;
border-radius: 12px;
padding: 0.7rem 1rem;
margin-bottom: 1rem;
text-align: center;
}
.confirm-row {
display: flex;
flex-direction: column;
gap: 0.5rem;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 16px;
padding: 1rem;
}
.solution-area {
margin: 1rem 0;
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
);
+61
View File
@@ -0,0 +1,61 @@
import type { StoryList } from "../types";
interface HomeProps {
loading: boolean;
storyList: StoryList | null;
usedCount: number;
onPlay: () => void;
onResetUsed: () => void;
}
function sourceLabel(storyList: StoryList | null): string {
if (!storyList) return "";
switch (storyList.source) {
case "gemini":
return `Historias actualizadas (${new Date(storyList.generatedAt ?? "").toLocaleDateString()})`;
case "cache":
return "Historias guardadas (sin conexión ahora)";
default:
return "Historias por defecto";
}
}
export default function Home({ loading, storyList, usedCount, onPlay, onResetUsed }: HomeProps) {
return (
<section className="screen home">
<h1>Historias Incompletas</h1>
<p className="subtitle">
Un jugador narra un enigma, el resto pregunta con sí o no hasta descubrir la historia completa.
</p>
<div className="rules-card">
<h2>Cómo se juega</h2>
<ol>
<li>Elijan quién narra primero. Esa persona toma el celular.</li>
<li>El narrador elige una historia y lee en voz alta solo el enigma.</li>
<li>Los demás jugadores hacen preguntas que se respondan con sí, no, o "no es relevante".</li>
<li>El narrador puede dar pistas si el grupo se traba.</li>
<li>Cuando adivinan (o se rinden), el narrador lee la solución completa.</li>
</ol>
</div>
<div className="status-row">
{loading ? (
<span className="badge">Cargando historias…</span>
) : (
<span className="badge">{sourceLabel(storyList)} · {storyList?.stories.length ?? 0} historias</span>
)}
</div>
<button className="primary" onClick={onPlay} disabled={loading || !storyList}>
Jugar
</button>
{usedCount > 0 && (
<button className="ghost" onClick={onResetUsed}>
Reiniciar historias jugadas ({usedCount})
</button>
)}
</section>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { useState } from "react";
import type { Story } from "../types";
interface NarratorViewProps {
story: Story;
onFinish: () => void;
}
export default function NarratorView({ story, onFinish }: NarratorViewProps) {
const [revealedHints, setRevealedHints] = useState(0);
const [solutionArmed, setSolutionArmed] = useState(false);
const [solutionShown, setSolutionShown] = useState(false);
return (
<section className="screen narrator">
<div className="narrator-warning">Solo para quien narra — no muestres la pantalla al resto del grupo.</div>
<h2>{story.title}</h2>
<div className="teaser-card">
<h3>Enigma (leélo en voz alta)</h3>
<p>{story.teaser}</p>
</div>
{revealedHints > 0 && (
<div className="hints-card">
<h3>Pistas reveladas</h3>
<ol>
{story.hints.slice(0, revealedHints).map((hint, i) => (
<li key={i}>{hint}</li>
))}
</ol>
</div>
)}
{revealedHints < story.hints.length && (
<button className="ghost" onClick={() => setRevealedHints((n) => n + 1)}>
Revelar siguiente pista ({revealedHints}/{story.hints.length})
</button>
)}
<div className="solution-area">
{!solutionShown ? (
<>
{!solutionArmed ? (
<button className="danger" onClick={() => setSolutionArmed(true)}>
Mostrar solución
</button>
) : (
<div className="confirm-row">
<span>¿Seguro? Esto revela el final de la historia.</span>
<button className="danger" onClick={() => setSolutionShown(true)}>
Sí, mostrar
</button>
<button className="ghost" onClick={() => setSolutionArmed(false)}>
Cancelar
</button>
</div>
)}
</>
) : (
<div className="solution-card">
<h3>Solución completa</h3>
<p>{story.solution}</p>
</div>
)}
</div>
<button className="primary" onClick={onFinish}>
Terminar historia y volver
</button>
</section>
);
}
+80
View File
@@ -0,0 +1,80 @@
import { useMemo, useState } from "react";
import type { Difficulty, Story } from "../types";
interface StoryPickerProps {
stories: Story[];
usedIds: string[];
onPick: (story: Story) => void;
onBack: () => void;
}
const DIFFICULTY_LABEL: Record<Difficulty, string> = {
easy: "Fácil",
medium: "Media",
hard: "Difícil",
};
export default function StoryPicker({ stories, usedIds, onPick, onBack }: StoryPickerProps) {
const [hideUsed, setHideUsed] = useState(true);
const usedSet = useMemo(() => new Set(usedIds), [usedIds]);
const visible = useMemo(
() => stories.filter((s) => !hideUsed || !usedSet.has(s.id)),
[stories, hideUsed, usedSet]
);
function pickRandom() {
const pool = stories.filter((s) => !usedSet.has(s.id));
const source = pool.length > 0 ? pool : stories;
const chosen = source[Math.floor(Math.random() * source.length)];
onPick(chosen);
}
return (
<section className="screen picker">
<header className="picker-header">
<button className="ghost" onClick={onBack}>
← Volver
</button>
<h2>Elegí una historia</h2>
</header>
<div className="picker-controls">
<button className="primary" onClick={pickRandom} disabled={stories.length === 0}>
Elegir al azar
</button>
<label className="checkbox">
<input type="checkbox" checked={hideUsed} onChange={(e) => setHideUsed(e.target.checked)} />
Ocultar ya jugadas
</label>
</div>
<ul className="story-list">
{visible.map((story) => (
<li key={story.id}>
<button className="story-card" onClick={() => onPick(story)}>
<div className="story-card-title-row">
<span className="story-title">{story.title}</span>
<span className={`difficulty difficulty-${story.difficulty}`}>
{DIFFICULTY_LABEL[story.difficulty]}
</span>
</div>
{story.tags.length > 0 && (
<div className="tags">
{story.tags.map((tag) => (
<span key={tag} className="tag">
#{tag}
</span>
))}
</div>
)}
{usedSet.has(story.id) && <span className="used-flag">Ya jugada</span>}
</button>
</li>
))}
</ul>
{visible.length === 0 && <p className="empty">No quedan historias sin jugar. Reiniciá desde el inicio.</p>}
</section>
);
}
+28
View File
@@ -0,0 +1,28 @@
const USED_KEY = "historias.usedStoryIds.v1";
export function getUsedStoryIds(): string[] {
try {
const raw = localStorage.getItem(USED_KEY);
return raw ? (JSON.parse(raw) as string[]) : [];
} catch {
return [];
}
}
export function markStoryUsed(id: string): void {
const used = new Set(getUsedStoryIds());
used.add(id);
try {
localStorage.setItem(USED_KEY, JSON.stringify([...used]));
} catch {
// ignorar si localStorage no esta disponible
}
}
export function resetUsedStories(): void {
try {
localStorage.removeItem(USED_KEY);
} catch {
// ignorar
}
}
+18
View File
@@ -0,0 +1,18 @@
export type Difficulty = "easy" | "medium" | "hard";
export interface Story {
id: string;
title: string;
difficulty: Difficulty;
tags: string[];
teaser: string;
hints: string[];
solution: string;
}
export interface StoryList {
version: number;
generatedAt: string | null;
source: "default" | "gemini" | "cache";
stories: Story[];
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
"resolveJsonModule": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})