Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
222 changes: 222 additions & 0 deletions server/api/routes/firebaseAPI.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import express from "express";
import { db, FieldValue } from "../firebase/firebase";
import type { DocumentReference } from "firebase-admin/firestore";

const router = express.Router();

Expand All @@ -8,6 +9,227 @@ const ARTIST_SURVEY_COLLECTION = "artistSurvey";
const POEM_COLLECTION = "poem";
const INCOMPLETE_SESSION_COLLECTION = "artistIncompleteSession";
const ASSIGNMENT_COLLECTION = "artistAssignment";
const DEFAULT_EXHIBITION_STUDY_ID = "6a8cbdb524cc2e2b32049b00";

const PUBLIC_OUTCOME_KEYS = new Set([
"felt_emotion",
"final_intended_meaning",
"intended_emotion",
"expressive_realization",
"csi_able_to_be_creative",
"csi_tools_allowed_expression",
"ownership_own_work",
"ownership_responsibility",
"ownership_personal_connection",
"ownership_emotional_connection",
"creative_control",
"creative_intentionality",
"mental_effort",
"llm_contribution_attribution",
"would_repeat_activity",
"ai_attitude",
]);

const asRecord = (value: unknown): Record<string, unknown> =>
value && typeof value === "object" ? (value as Record<string, unknown>) : {};

const toPublicJson = (value: unknown): unknown => {
if (value === null || value === undefined) return value;
if (Array.isArray(value)) return value.map(toPublicJson);
if (value instanceof Date) return value.toISOString();
if (typeof value !== "object") return value;

const candidate = value as {
toDate?: () => Date;
path?: string;
};
if (typeof candidate.toDate === "function") {
return candidate.toDate().toISOString();
}
if (candidate.path) return undefined;

return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.map(([key, item]) => [key, toPublicJson(item)] as const)
.filter(([, item]) => item !== undefined),
);
};

const filterPublicOutcomes = (answers: Record<string, unknown> = {}) =>
Object.fromEntries(
Object.entries(answers).filter(([key]) => PUBLIC_OUTCOME_KEYS.has(key)),
);

const isDocumentReference = (value: unknown): value is DocumentReference =>
Boolean(
value &&
typeof value === "object" &&
"get" in value &&
typeof (value as { get?: unknown }).get === "function",
);

const publicConversation = (
value: unknown,
defaultStage: "SPARK" | "WRITE",
) => {
if (!Array.isArray(value)) return [];
return value
.map((item, index) => {
const message = asRecord(item);
if (message.role !== "user" && message.role !== "assistant") return null;
if (typeof message.content !== "string") return null;
return {
id: `${defaultStage.toLowerCase()}-${index + 1}`,
role: message.role,
content: message.content,
timestamp: message.timestamp ?? null,
stage:
message.stage === "SPARK" || message.stage === "WRITE"
? message.stage
: defaultStage,
kind: typeof message.kind === "string" ? message.kind : null,
};
})
.filter((message) => message !== null);
};

const publicLlmUsage = (value: unknown) => {
const usage = asRecord(value);
const chatOpenings = Array.isArray(usage.chatOpenings)
? usage.chatOpenings.map((item) => {
const opening = asRecord(item);
return { stage: opening.stage, timestamp: opening.timestamp };
})
: [];
const chatAvailability = Array.isArray(usage.chatAvailability)
? usage.chatAvailability.map((item) => {
const availability = asRecord(item);
return {
stage: availability.stage,
availableAt: availability.availableAt,
};
})
: [];
const requests = Array.isArray(usage.requests)
? usage.requests.map((item) => {
const request = asRecord(item);
return {
stage: request.stage,
status: request.status,
requestedAt: request.requestedAt,
completedAt: request.completedAt,
failedAt: request.failedAt,
};
})
: [];
return { chatOpenings, chatAvailability, requests };
};

const publicTimestampMs = (value: unknown) => {
if (value instanceof Date) return value.getTime();
const candidate = asRecord(value) as { toDate?: () => Date };
if (typeof candidate.toDate === "function") return candidate.toDate().getTime();
const parsed = new Date(String(value ?? "")).getTime();
return Number.isFinite(parsed) ? parsed : 0;
};

router.get("/exhibition", async (req, res) => {
try {
const studyId = String(req.query.studyId ?? "");
const allowedStudyIds = new Set(
(process.env.EXHIBITION_STUDY_IDS ?? DEFAULT_EXHIBITION_STUDY_ID)
.split(",")
.map((id) => id.trim())
.filter(Boolean),
);

if (!studyId || !allowedStudyIds.has(studyId)) {
return res.status(404).json({ error: "Exhibition not found" });
}

const artistSnapshot = await db
.collection(ARTIST_COLLECTION)
.where("prolific.studyId", "==", studyId)
.get();

const hydrated = await Promise.all(
artistSnapshot.docs.map(async (artistDoc) => {
const artist = artistDoc.data();
const poemRef = artist.poem;
const surveyRef = artist.surveyResponse;

if (!isDocumentReference(poemRef) || !isDocumentReference(surveyRef)) {
return null;
}

const [poemSnapshot, surveySnapshot] = await Promise.all([
poemRef.get(),
surveyRef.get(),
]);
if (!poemSnapshot.exists || !surveySnapshot.exists) return null;

const poem = poemSnapshot.data() ?? {};
const survey = surveySnapshot.data() ?? {};
const postSurveyAnswers = filterPublicOutcomes(
(survey.postSurveyAnswers as Record<string, unknown>) ?? {},
);
const completionValue = Array.isArray(artist.timestamps)
? artist.timestamps[artist.timestamps.length - 1]
: poem.taskTiming?.completedAt;

const sparkConversation = publicConversation(
poem.sparkConversation,
"SPARK",
);
const writeConversation = publicConversation(
poem.writeConversation,
"WRITE",
).filter((message) => message?.stage !== "SPARK");

return {
condition: artist.condition,
completedAt: completionValue ?? null,
poem: {
passageId: poem.passageId,
passage: poem.passage,
text: poem.text ?? poem.selectedWordIndexes ?? [],
finalPoem: poem.finalPoem ?? "",
editHistory: poem.editHistory ?? poem.snapshot ?? [],
sparkConversation,
writeConversation,
taskTiming: poem.taskTiming ?? {},
llmUsage: publicLlmUsage(poem.llmUsage),
derivedMetrics: poem.derivedMetrics ?? {},
},
outcomes: postSurveyAnswers,
};
}),
);

const participants = hydrated
.filter((participant) => participant !== null)
.sort(
(a, b) =>
publicTimestampMs(a.completedAt) - publicTimestampMs(b.completedAt),
)
.map((participant, index) => ({
id: `poem-${String(index + 1).padStart(2, "0")}`,
...participant,
}));

res.set("Cache-Control", "public, max-age=0, s-maxage=60");
res.json(
toPublicJson({
studyId,
generatedAt: new Date(),
participants,
}),
);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to load exhibition" });
}
});

router.post("/artist-assignment", async (req, res) => {
try {
Expand Down
100 changes: 100 additions & 0 deletions src/exhibition/ExhibitionApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { useEffect, useState } from "react";
import {
BrowserRouter,
Route,
Routes,
useLocation,
} from "react-router-dom";
import ExhibitionGallery from "./components/ExhibitionGallery";
import PoemDetailRoute from "./components/PoemDetail";
import type { ExhibitionDataset } from "./types";
import "./exhibition.css";

const DEFAULT_STUDY_ID = "6a8cbdb524cc2e2b32049b00";
const STUDY_ID =
import.meta.env.VITE_EXHIBITION_STUDY_ID?.trim() || DEFAULT_STUDY_ID;
const DATA_URL =
import.meta.env.VITE_EXHIBITION_DATA_URL?.trim() ||
`/api/firebase/exhibition?studyId=${encodeURIComponent(STUDY_ID)}`;

function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}

function ExhibitionRoutes({ dataset }: { dataset: ExhibitionDataset }) {
return (
<>
<ScrollToTop />
<Routes>
<Route path="/exhibition" element={<ExhibitionGallery dataset={dataset} />} />
<Route
path="/exhibition/:participantId"
element={<PoemDetailRoute dataset={dataset} />}
/>
</Routes>
</>
);
}

export default function ExhibitionApp() {
const [dataset, setDataset] = useState<ExhibitionDataset | null>(null);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
const previousTitle = document.title;
document.title = "The Blackout Room";
return () => {
document.title = previousTitle;
};
}, []);

useEffect(() => {
const controller = new AbortController();
const load = async () => {
try {
const response = await fetch(DATA_URL, { signal: controller.signal });
if (!response.ok) throw new Error(`Data request failed (${response.status})`);
const payload = (await response.json()) as ExhibitionDataset;
setDataset(payload);
} catch (loadError) {
if (controller.signal.aborted) return;
setError(
loadError instanceof Error
? loadError.message
: "The exhibition data could not be loaded.",
);
}
};
void load();
return () => controller.abort();
}, []);

if (error) {
return (
<main className="ex-status-page">
<p className="ex-status-page__mark">✦</p>
<h1>The exhibition is between states.</h1>
<p>{error}</p>
</main>
);
}

if (!dataset) {
return (
<main className="ex-status-page" aria-live="polite">
<p className="ex-status-page__mark ex-status-page__mark--turning">✦</p>
<p>Preparing the room…</p>
</main>
);
}

return (
<BrowserRouter>
<ExhibitionRoutes dataset={dataset} />
</BrowserRouter>
);
}
34 changes: 34 additions & 0 deletions src/exhibition/components/BlackoutText.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
interface BlackoutTextProps {
passage: string;
visibleIndexes: number[];
activeWordIndex?: number;
compact?: boolean;
}

export default function BlackoutText({
passage,
visibleIndexes,
activeWordIndex,
compact = false,
}: BlackoutTextProps) {
const visible = new Set(visibleIndexes);
const words = passage.split(" ");

return (
<div className={`ex-blackout ${compact ? "ex-blackout--compact" : ""}`}>
{words.map((word, index) => {
const isVisible = visible.has(index);
const isActive = activeWordIndex === index;
return (
<span key={`${index}-${word}`}>
<span
className={`ex-blackout__word ${isVisible ? "is-visible" : "is-covered"} ${isActive ? "is-active" : ""}`}
>
{word}
</span>{" "}
</span>
);
})}
</div>
);
}
Loading