feat: implement role-based access control
Introduce 'gm', 'player', and 'observer' roles to the journal system. This includes: - Restricting command usage and completions to the GM role. - Implementing role-based message emission permissions. - Adding a player list and role indicators in the UI. - Persisting the user's role in localStorage. - Updating the connection logic to include the role in the client ID.
This commit is contained in:
parent
e216b94e25
commit
59236f6dba
|
|
@ -4,12 +4,7 @@
|
||||||
|
|
||||||
import { Component, createSignal, For, Show, createMemo } from "solid-js";
|
import { Component, createSignal, For, Show, createMemo } from "solid-js";
|
||||||
import { registeredTypes, canEmit } from "./registry";
|
import { registeredTypes, canEmit } from "./registry";
|
||||||
import {
|
import { sendMessage, useJournalStream } from "../stores/journalStream";
|
||||||
sendMessage,
|
|
||||||
revertLatest,
|
|
||||||
canRevert,
|
|
||||||
useJournalStream,
|
|
||||||
} from "../stores/journalStream";
|
|
||||||
import type { MessageTypeDef } from "./registry";
|
import type { MessageTypeDef } from "./registry";
|
||||||
import { DynamicForm } from "./DynamicForm";
|
import { DynamicForm } from "./DynamicForm";
|
||||||
|
|
||||||
|
|
@ -20,7 +15,7 @@ export const ComposePanel: Component = () => {
|
||||||
const [error, setError] = createSignal<string | null>(null);
|
const [error, setError] = createSignal<string | null>(null);
|
||||||
const [sending, setSending] = createSignal(false);
|
const [sending, setSending] = createSignal(false);
|
||||||
|
|
||||||
const role = () => stream.myName;
|
const role = () => stream.myRole;
|
||||||
|
|
||||||
// Available types filtered by role
|
// Available types filtered by role
|
||||||
const availableTypes = createMemo(() => {
|
const availableTypes = createMemo(() => {
|
||||||
|
|
@ -51,12 +46,6 @@ export const ComposePanel: Component = () => {
|
||||||
setSending(false);
|
setSending(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRevert = () => {
|
|
||||||
revertLatest();
|
|
||||||
};
|
|
||||||
|
|
||||||
const showRevert = () => canRevert() && stream.myName === "gm";
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="border-t border-gray-200 p-2 space-y-2 bg-white">
|
<div class="border-t border-gray-200 p-2 space-y-2 bg-white">
|
||||||
{/* Type picker */}
|
{/* Type picker */}
|
||||||
|
|
@ -81,16 +70,6 @@ export const ComposePanel: Component = () => {
|
||||||
>
|
>
|
||||||
{sending() ? "..." : "Send"}
|
{sending() ? "..." : "Send"}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<Show when={showRevert()}>
|
|
||||||
<button
|
|
||||||
onClick={handleRevert}
|
|
||||||
class="text-xs text-gray-400 hover:text-red-500"
|
|
||||||
title="Revert last message"
|
|
||||||
>
|
|
||||||
↩
|
|
||||||
</button>
|
|
||||||
</Show>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Dynamic form */}
|
{/* Dynamic form */}
|
||||||
|
|
|
||||||
|
|
@ -21,11 +21,7 @@ import {
|
||||||
Match,
|
Match,
|
||||||
} from "solid-js";
|
} from "solid-js";
|
||||||
import { sendMessage, useJournalStream } from "../stores/journalStream";
|
import { sendMessage, useJournalStream } from "../stores/journalStream";
|
||||||
import {
|
import { useJournalCompletions, ensureCompletions } from "./completions";
|
||||||
useJournalCompletions,
|
|
||||||
ensureCompletions,
|
|
||||||
type CompletionsState,
|
|
||||||
} from "./completions";
|
|
||||||
|
|
||||||
// ---- Helpers ----
|
// ---- Helpers ----
|
||||||
|
|
||||||
|
|
@ -78,6 +74,10 @@ export const JournalInput: Component = () => {
|
||||||
const stream = useJournalStream();
|
const stream = useJournalStream();
|
||||||
const comp = useJournalCompletions();
|
const comp = useJournalCompletions();
|
||||||
|
|
||||||
|
const isObserver = () => stream.myRole === "observer";
|
||||||
|
const isPlayer = () => stream.myRole === "player";
|
||||||
|
const isGm = () => stream.myRole === "gm";
|
||||||
|
|
||||||
const [text, setText] = createSignal("");
|
const [text, setText] = createSignal("");
|
||||||
const [error, setError] = createSignal<string | null>(null);
|
const [error, setError] = createSignal<string | null>(null);
|
||||||
const [sending, setSending] = createSignal(false);
|
const [sending, setSending] = createSignal(false);
|
||||||
|
|
@ -98,6 +98,18 @@ export const JournalInput: Component = () => {
|
||||||
const raw = text().trim();
|
const raw = text().trim();
|
||||||
if (!raw) return;
|
if (!raw) return;
|
||||||
|
|
||||||
|
// Players can't use commands — everything is narrative
|
||||||
|
if (isPlayer() || isObserver()) {
|
||||||
|
const result = sendMessage("narrative", { text: raw });
|
||||||
|
if (!result.success) {
|
||||||
|
setError(result.error);
|
||||||
|
} else {
|
||||||
|
setText("");
|
||||||
|
}
|
||||||
|
textareaRef?.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const parsed = parseInput(raw);
|
const parsed = parseInput(raw);
|
||||||
if (parsed.error) {
|
if (parsed.error) {
|
||||||
setError(parsed.error);
|
setError(parsed.error);
|
||||||
|
|
@ -132,6 +144,8 @@ export const JournalInput: Component = () => {
|
||||||
|
|
||||||
function buildCompletions(): CompletionItem[] {
|
function buildCompletions(): CompletionItem[] {
|
||||||
const raw = text().trim();
|
const raw = text().trim();
|
||||||
|
// Only GM gets completions
|
||||||
|
if (!isGm()) return [];
|
||||||
const data = comp.data;
|
const data = comp.data;
|
||||||
const commands = [
|
const commands = [
|
||||||
{ label: "/roll", kind: "command" as const, insertText: "/roll " },
|
{ label: "/roll", kind: "command" as const, insertText: "/roll " },
|
||||||
|
|
@ -235,9 +249,9 @@ export const JournalInput: Component = () => {
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// If not open and starts with /, open completions
|
// If not open and starts with /, open completions (GM only)
|
||||||
const raw = text();
|
const raw = text();
|
||||||
if (raw.startsWith("/")) {
|
if (isGm() && raw.startsWith("/")) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setShowCompletions(true);
|
setShowCompletions(true);
|
||||||
setSelectedIdx(0);
|
setSelectedIdx(0);
|
||||||
|
|
@ -280,8 +294,8 @@ export const JournalInput: Component = () => {
|
||||||
const raw = input.value;
|
const raw = input.value;
|
||||||
setText(raw);
|
setText(raw);
|
||||||
|
|
||||||
// Completions visibility — keep open while user types any /
|
// Completions visibility — keep open while user types any / (GM only)
|
||||||
if (raw.startsWith("/")) {
|
if (isGm() && raw.startsWith("/")) {
|
||||||
setShowCompletions(true);
|
setShowCompletions(true);
|
||||||
setSelectedIdx(0);
|
setSelectedIdx(0);
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -386,35 +400,49 @@ export const JournalInput: Component = () => {
|
||||||
|
|
||||||
{/* Textarea + actions */}
|
{/* Textarea + actions */}
|
||||||
<div class="flex flex-col">
|
<div class="flex flex-col">
|
||||||
<textarea
|
<Show
|
||||||
ref={textareaRef}
|
when={!isObserver()}
|
||||||
value={text()}
|
fallback={
|
||||||
onInput={handleInput}
|
<div class="px-3 py-4 text-xs text-gray-400 italic text-center">
|
||||||
onKeyDown={handleKeyDown}
|
You are observing. Open this panel on another device to join as GM
|
||||||
placeholder="Type a message, or /roll or /link..."
|
or player.
|
||||||
rows={2}
|
</div>
|
||||||
class="w-full resize-none border-0 px-3 pt-2.5 pb-1 text-sm
|
}
|
||||||
text-gray-800 placeholder-gray-400 focus:outline-none
|
>
|
||||||
bg-transparent min-h-[60px]"
|
<textarea
|
||||||
/>
|
ref={textareaRef}
|
||||||
|
value={text()}
|
||||||
|
onInput={handleInput}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
placeholder={
|
||||||
|
isGm()
|
||||||
|
? "Type a message, or /roll or /link..."
|
||||||
|
: "Type a message..."
|
||||||
|
}
|
||||||
|
rows={2}
|
||||||
|
class="w-full resize-none border-0 px-3 pt-2.5 pb-1 text-sm
|
||||||
|
text-gray-800 placeholder-gray-400 focus:outline-none
|
||||||
|
bg-transparent min-h-[60px]"
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Bottom row: error + buttons */}
|
{/* Bottom row: error + buttons */}
|
||||||
<div class="flex items-center justify-between px-2 pb-2">
|
<div class="flex items-center justify-between px-2 pb-2">
|
||||||
<Show when={error()}>
|
<Show when={error()}>
|
||||||
<p class="text-red-500 text-xs truncate max-w-[60%]">{error()}</p>
|
<p class="text-red-500 text-xs truncate max-w-[60%]">{error()}</p>
|
||||||
</Show>
|
</Show>
|
||||||
<div class="flex items-center gap-1 ml-auto">
|
<div class="flex items-center gap-1 ml-auto">
|
||||||
<button
|
<button
|
||||||
onClick={handleSend}
|
onClick={handleSend}
|
||||||
disabled={sending() || !text().trim()}
|
disabled={sending() || !text().trim()}
|
||||||
class="bg-blue-600 text-white rounded px-3 py-1 text-xs
|
class="bg-blue-600 text-white rounded px-3 py-1 text-xs
|
||||||
hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed
|
hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed
|
||||||
transition-colors"
|
transition-colors"
|
||||||
>
|
>
|
||||||
Send
|
Send
|
||||||
</button>
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import {
|
||||||
hydrateFromServer,
|
hydrateFromServer,
|
||||||
useJournalStream,
|
useJournalStream,
|
||||||
setMyName,
|
setMyName,
|
||||||
|
setMyRole,
|
||||||
setSessionId,
|
setSessionId,
|
||||||
sessions,
|
sessions,
|
||||||
createSession,
|
createSession,
|
||||||
|
|
@ -27,6 +28,12 @@ export interface JournalPanelProps {
|
||||||
export const JournalPanel: Component<JournalPanelProps> = (props) => {
|
export const JournalPanel: Component<JournalPanelProps> = (props) => {
|
||||||
const stream = useJournalStream();
|
const stream = useJournalStream();
|
||||||
|
|
||||||
|
// Player list (exclude gm and observer)
|
||||||
|
const playerEntries = () =>
|
||||||
|
Object.entries(stream.players).filter(
|
||||||
|
([_, p]) => p.role !== "gm" && p.role !== "observer",
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* Backdrop — only on mobile, starts below header */}
|
{/* Backdrop — only on mobile, starts below header */}
|
||||||
|
|
@ -47,6 +54,19 @@ export const JournalPanel: Component<JournalPanelProps> = (props) => {
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<JournalHeader onClose={props.onClose} />
|
<JournalHeader onClose={props.onClose} />
|
||||||
|
|
||||||
|
{/* Player list tabs */}
|
||||||
|
<Show when={stream.connected && playerEntries().length > 0}>
|
||||||
|
<div class="flex items-center gap-1 px-3 py-1.5 border-b border-gray-100 bg-gray-50 overflow-x-auto shrink-0">
|
||||||
|
<For each={playerEntries()}>
|
||||||
|
{([name]) => (
|
||||||
|
<span class="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full whitespace-nowrap">
|
||||||
|
{name}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
</div>
|
||||||
|
</Show>
|
||||||
|
|
||||||
<Show
|
<Show
|
||||||
when={stream.connected}
|
when={stream.connected}
|
||||||
fallback={
|
fallback={
|
||||||
|
|
@ -134,75 +154,88 @@ const JournalHeader: Component<JournalHeaderProps> = (props) => {
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<p class="text-sm font-semibold text-gray-700 truncate leading-tight">
|
<p class="text-sm font-semibold text-gray-700 truncate leading-tight flex items-center gap-1">
|
||||||
{stream.myName}
|
{stream.myName}
|
||||||
</p>
|
<Show when={stream.myRole !== "gm"}>
|
||||||
{/* Clickable subtitle — session dropdown */}
|
<span
|
||||||
<div ref={dropdownRef} class="relative">
|
class={`text-[10px] px-1 rounded ${
|
||||||
<button
|
stream.myRole === "observer"
|
||||||
onClick={() => setDropdownOpen((v) => !v)}
|
? "bg-gray-200 text-gray-500"
|
||||||
class="text-[10px] text-gray-400 hover:text-gray-600 truncate leading-tight cursor-pointer text-left"
|
: "bg-blue-100 text-blue-600"
|
||||||
>
|
}`}
|
||||||
{stream.sessionName || stream.sessionId}{" "}
|
>
|
||||||
<span class="text-gray-300">▾</span>
|
{stream.myRole}
|
||||||
</button>
|
</span>
|
||||||
<Show when={dropdownOpen()}>
|
|
||||||
<div class="absolute top-full left-0 mt-1 w-48 bg-white border border-gray-200 rounded shadow-lg z-50 py-1 max-h-48 overflow-y-auto">
|
|
||||||
<For each={Object.entries(manifest().sessions)}>
|
|
||||||
{([id, meta]) => (
|
|
||||||
<button
|
|
||||||
onClick={() => handleSessionSelect(id)}
|
|
||||||
class={`w-full text-left px-3 py-1 text-xs hover:bg-gray-100 flex items-center gap-1 ${
|
|
||||||
id === stream.sessionId
|
|
||||||
? "bg-blue-50 text-blue-700"
|
|
||||||
: "text-gray-700"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span class="truncate flex-1">{meta.name || id}</span>
|
|
||||||
<Show when={id === stream.sessionId}>
|
|
||||||
<span class="text-blue-500 shrink-0">✓</span>
|
|
||||||
</Show>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
<div class="border-t border-gray-100 my-0.5" />
|
|
||||||
<Show
|
|
||||||
when={!showNewInput()}
|
|
||||||
fallback={
|
|
||||||
<div class="px-3 py-1 flex gap-1">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={newSessionName()}
|
|
||||||
onInput={(e) =>
|
|
||||||
setNewSessionName(e.currentTarget.value)
|
|
||||||
}
|
|
||||||
placeholder="Session name"
|
|
||||||
class="flex-1 border border-gray-300 rounded px-1.5 py-0.5 text-xs"
|
|
||||||
autofocus
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === "Enter") handleCreate();
|
|
||||||
if (e.key === "Escape") setShowNewInput(false);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
onClick={handleCreate}
|
|
||||||
class="bg-blue-600 text-white rounded px-2 py-0.5 text-xs hover:bg-blue-700"
|
|
||||||
>
|
|
||||||
+
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
onClick={() => setShowNewInput(true)}
|
|
||||||
class="w-full text-left px-3 py-1 text-xs text-blue-600 hover:bg-gray-100"
|
|
||||||
>
|
|
||||||
+ New session
|
|
||||||
</button>
|
|
||||||
</Show>
|
|
||||||
</div>
|
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</p>
|
||||||
|
{/* Clickable subtitle — session dropdown (GM only) */}
|
||||||
|
<Show when={stream.myRole === "gm"}>
|
||||||
|
<div ref={dropdownRef} class="relative">
|
||||||
|
<button
|
||||||
|
onClick={() => setDropdownOpen((v) => !v)}
|
||||||
|
class="text-[10px] text-gray-400 hover:text-gray-600 truncate leading-tight cursor-pointer text-left"
|
||||||
|
>
|
||||||
|
{stream.sessionName || stream.sessionId}{" "}
|
||||||
|
<span class="text-gray-300">▾</span>
|
||||||
|
</button>
|
||||||
|
<Show when={dropdownOpen()}>
|
||||||
|
<div class="absolute top-full left-0 mt-1 w-48 bg-white border border-gray-200 rounded shadow-lg z-50 py-1 max-h-48 overflow-y-auto">
|
||||||
|
<For each={Object.entries(manifest().sessions)}>
|
||||||
|
{([id, meta]) => (
|
||||||
|
<button
|
||||||
|
onClick={() => handleSessionSelect(id)}
|
||||||
|
class={`w-full text-left px-3 py-1 text-xs hover:bg-gray-100 flex items-center gap-1 ${
|
||||||
|
id === stream.sessionId
|
||||||
|
? "bg-blue-50 text-blue-700"
|
||||||
|
: "text-gray-700"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span class="truncate flex-1">{meta.name || id}</span>
|
||||||
|
<Show when={id === stream.sessionId}>
|
||||||
|
<span class="text-blue-500 shrink-0">✓</span>
|
||||||
|
</Show>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
<div class="border-t border-gray-100 my-0.5" />
|
||||||
|
<Show
|
||||||
|
when={!showNewInput()}
|
||||||
|
fallback={
|
||||||
|
<div class="px-3 py-1 flex gap-1">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newSessionName()}
|
||||||
|
onInput={(e) =>
|
||||||
|
setNewSessionName(e.currentTarget.value)
|
||||||
|
}
|
||||||
|
placeholder="Session name"
|
||||||
|
class="flex-1 border border-gray-300 rounded px-1.5 py-0.5 text-xs"
|
||||||
|
autofocus
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") handleCreate();
|
||||||
|
if (e.key === "Escape") setShowNewInput(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleCreate}
|
||||||
|
class="bg-blue-600 text-white rounded px-2 py-0.5 text-xs hover:bg-blue-700"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowNewInput(true)}
|
||||||
|
class="w-full text-left px-3 py-1 text-xs text-blue-600 hover:bg-gray-100"
|
||||||
|
>
|
||||||
|
+ New session
|
||||||
|
</button>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -235,16 +268,12 @@ const JournalHeader: Component<JournalHeaderProps> = (props) => {
|
||||||
const ConnectDialog: Component = () => {
|
const ConnectDialog: Component = () => {
|
||||||
const stream = useJournalStream();
|
const stream = useJournalStream();
|
||||||
const [playerName, setPlayerName] = createSignal(stream.myName);
|
const [playerName, setPlayerName] = createSignal(stream.myName);
|
||||||
|
const [role, setRole] = createSignal<"gm" | "player" | "observer">(
|
||||||
|
stream.myRole,
|
||||||
|
);
|
||||||
const [connecting, setConnecting] = createSignal(false);
|
const [connecting, setConnecting] = createSignal(false);
|
||||||
const [error, setError] = createSignal<string | null>(null);
|
const [error, setError] = createSignal<string | null>(null);
|
||||||
|
|
||||||
// Auto-connect if we have a name from localStorage
|
|
||||||
onMount(() => {
|
|
||||||
if (stream.myName && stream.myName !== "gm") {
|
|
||||||
handleConnect();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleConnect = async () => {
|
const handleConnect = async () => {
|
||||||
const name = playerName().trim() || stream.myName;
|
const name = playerName().trim() || stream.myName;
|
||||||
if (!name) return;
|
if (!name) return;
|
||||||
|
|
@ -256,6 +285,7 @@ const ConnectDialog: Component = () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setMyName(name);
|
setMyName(name);
|
||||||
|
setMyRole(role());
|
||||||
const sessionId = stream.sessionId || "default";
|
const sessionId = stream.sessionId || "default";
|
||||||
setSessionId(sessionId);
|
setSessionId(sessionId);
|
||||||
await hydrateFromServer(sessionId);
|
await hydrateFromServer(sessionId);
|
||||||
|
|
@ -263,8 +293,6 @@ const ConnectDialog: Component = () => {
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof Error ? e.message : "Connection failed";
|
const msg = e instanceof Error ? e.message : "Connection failed";
|
||||||
setError(msg);
|
setError(msg);
|
||||||
// If connectStream threw, the error handler also sets connectionStatus to error.
|
|
||||||
// Make sure the error message is captured.
|
|
||||||
} finally {
|
} finally {
|
||||||
setConnecting(false);
|
setConnecting(false);
|
||||||
}
|
}
|
||||||
|
|
@ -273,7 +301,7 @@ const ConnectDialog: Component = () => {
|
||||||
return (
|
return (
|
||||||
<div class="w-full max-w-sm space-y-3">
|
<div class="w-full max-w-sm space-y-3">
|
||||||
<p class="text-sm text-gray-600 text-center">
|
<p class="text-sm text-gray-600 text-center">
|
||||||
Enter your name to join the session.
|
Enter your name and role to join the session.
|
||||||
<br />
|
<br />
|
||||||
<span class="text-xs text-gray-400">
|
<span class="text-xs text-gray-400">
|
||||||
Connecting to {window.location.host}
|
Connecting to {window.location.host}
|
||||||
|
|
@ -284,10 +312,25 @@ const ConnectDialog: Component = () => {
|
||||||
value={playerName()}
|
value={playerName()}
|
||||||
onInput={(e) => setPlayerName(e.currentTarget.value)}
|
onInput={(e) => setPlayerName(e.currentTarget.value)}
|
||||||
onKeyDown={(e) => e.key === "Enter" && handleConnect()}
|
onKeyDown={(e) => e.key === "Enter" && handleConnect()}
|
||||||
placeholder="Your name (GM or player)"
|
placeholder="Your name"
|
||||||
class="w-full border border-gray-300 rounded px-3 py-1.5 text-sm"
|
class="w-full border border-gray-300 rounded px-3 py-1.5 text-sm"
|
||||||
autofocus
|
autofocus
|
||||||
/>
|
/>
|
||||||
|
{/* Role selector */}
|
||||||
|
<div class="flex gap-1">
|
||||||
|
{(["gm", "player", "observer"] as const).map((r) => (
|
||||||
|
<button
|
||||||
|
onClick={() => setRole(r)}
|
||||||
|
class={`flex-1 rounded px-2 py-1.5 text-xs font-medium border transition-colors ${
|
||||||
|
role() === r
|
||||||
|
? "bg-blue-600 text-white border-blue-600"
|
||||||
|
: "bg-white text-gray-600 border-gray-300 hover:border-gray-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{r === "gm" ? "GM" : r === "player" ? "Player" : "Observer"}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={handleConnect}
|
onClick={handleConnect}
|
||||||
disabled={connecting() || !playerName().trim()}
|
disabled={connecting() || !playerName().trim()}
|
||||||
|
|
|
||||||
|
|
@ -5,11 +5,7 @@
|
||||||
import { Component, Show, createMemo } from "solid-js";
|
import { Component, Show, createMemo } from "solid-js";
|
||||||
import type { StreamMessage as StreamMessageType } from "./registry";
|
import type { StreamMessage as StreamMessageType } from "./registry";
|
||||||
import { getMessageType } from "./registry";
|
import { getMessageType } from "./registry";
|
||||||
import {
|
import { revertLatest, useJournalStream } from "../stores/journalStream";
|
||||||
revertLatest,
|
|
||||||
canRevert,
|
|
||||||
useJournalStream,
|
|
||||||
} from "../stores/journalStream";
|
|
||||||
|
|
||||||
export const StreamMessageCard: Component<{
|
export const StreamMessageCard: Component<{
|
||||||
message: StreamMessageType;
|
message: StreamMessageType;
|
||||||
|
|
|
||||||
|
|
@ -46,8 +46,8 @@ export interface MessageTypeDef<P = unknown> {
|
||||||
type: string;
|
type: string;
|
||||||
/** Human-readable label shown in the compose panel dropdown */
|
/** Human-readable label shown in the compose panel dropdown */
|
||||||
label: string;
|
label: string;
|
||||||
/** Which roles can emit this type. Empty array = all roles allowed. */
|
/** Which roles can emit this type. Empty array = all roles (including observer) allowed. */
|
||||||
emitters?: ("gm" | "player")[];
|
emitters?: ("gm" | "player" | "observer")[];
|
||||||
/** Zod schema used to validate payload before publish */
|
/** Zod schema used to validate payload before publish */
|
||||||
schema: ZodType<P>;
|
schema: ZodType<P>;
|
||||||
/** Returns a default payload for compose panel initialization */
|
/** Returns a default payload for compose panel initialization */
|
||||||
|
|
@ -110,7 +110,9 @@ export function validatePayload<P>(
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "),
|
error: result.error.issues
|
||||||
|
.map((i) => `${i.path.join(".")}: ${i.message}`)
|
||||||
|
.join("; "),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -122,5 +124,5 @@ export function canEmit(type: string, role: string): boolean {
|
||||||
if (!def) return false;
|
if (!def) return false;
|
||||||
const emitters = def.emitters;
|
const emitters = def.emitters;
|
||||||
if (!emitters || emitters.length === 0) return true;
|
if (!emitters || emitters.length === 0) return true;
|
||||||
return emitters.includes(role as "gm" | "player");
|
return emitters.includes(role as "gm" | "player" | "observer");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -42,9 +42,7 @@ const RevealLink: Component<ArticleRevealPayload> = (p) => {
|
||||||
|
|
||||||
const displayLabel = () => {
|
const displayLabel = () => {
|
||||||
if (p.label) return p.label;
|
if (p.label) return p.label;
|
||||||
const file = fileNameFromPath(p.path);
|
return fileNameFromPath(p.path);
|
||||||
if (p.section) return `${file} § ${slugToTitle(p.section)}`;
|
|
||||||
return file;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClick = (e: MouseEvent) => {
|
const handleClick = (e: MouseEvent) => {
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ export type NarrativePayload = z.infer<typeof schema>;
|
||||||
registerMessageType<NarrativePayload>({
|
registerMessageType<NarrativePayload>({
|
||||||
type: "narrative",
|
type: "narrative",
|
||||||
label: "Narrative",
|
label: "Narrative",
|
||||||
|
emitters: ["gm", "player"],
|
||||||
schema,
|
schema,
|
||||||
defaultPayload: () => ({ text: "" }),
|
defaultPayload: () => ({ text: "" }),
|
||||||
render: (p) => <p class="text-sm whitespace-pre-wrap">{p.text}</p>,
|
render: (p) => <p class="text-sm whitespace-pre-wrap">{p.text}</p>,
|
||||||
|
|
|
||||||
|
|
@ -41,8 +41,12 @@ export interface JournalStreamState {
|
||||||
connectionError: string | null;
|
connectionError: string | null;
|
||||||
/** This client's identity */
|
/** This client's identity */
|
||||||
myName: string;
|
myName: string;
|
||||||
|
/** Role: gm | player | observer. Immutable while connected. */
|
||||||
|
myRole: "gm" | "player" | "observer";
|
||||||
/** Broker URL, set after connect */
|
/** Broker URL, set after connect */
|
||||||
brokerUrl: string | null;
|
brokerUrl: string | null;
|
||||||
|
/** Active player list (keyed by player name) */
|
||||||
|
players: Record<string, { role: string }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SessionMeta {
|
export interface SessionMeta {
|
||||||
|
|
@ -62,19 +66,22 @@ export interface SessionManifest {
|
||||||
const LS_PLAYER_NAME = "ttrpg.playerName";
|
const LS_PLAYER_NAME = "ttrpg.playerName";
|
||||||
const LS_BROKER_URL = "ttrpg.brokerUrl";
|
const LS_BROKER_URL = "ttrpg.brokerUrl";
|
||||||
const LS_LAST_SESSION = "ttrpg.lastSessionId";
|
const LS_LAST_SESSION = "ttrpg.lastSessionId";
|
||||||
|
const LS_PLAYER_ROLE = "ttrpg.playerRole";
|
||||||
|
|
||||||
function loadPersisted(): {
|
function loadPersisted(): {
|
||||||
myName: string;
|
myName: string;
|
||||||
brokerUrl: string | null;
|
brokerUrl: string | null;
|
||||||
lastSessionId: string | null;
|
lastSessionId: string | null;
|
||||||
|
myRole: string;
|
||||||
} {
|
} {
|
||||||
if (typeof localStorage === "undefined") {
|
if (typeof localStorage === "undefined") {
|
||||||
return { myName: "gm", brokerUrl: null, lastSessionId: null };
|
return { myName: "gm", brokerUrl: null, lastSessionId: null, myRole: "gm" };
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
myName: localStorage.getItem(LS_PLAYER_NAME) || "gm",
|
myName: localStorage.getItem(LS_PLAYER_NAME) || "gm",
|
||||||
brokerUrl: localStorage.getItem(LS_BROKER_URL),
|
brokerUrl: localStorage.getItem(LS_BROKER_URL),
|
||||||
lastSessionId: localStorage.getItem(LS_LAST_SESSION),
|
lastSessionId: localStorage.getItem(LS_LAST_SESSION),
|
||||||
|
myRole: localStorage.getItem(LS_PLAYER_ROLE) || "gm",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -99,7 +106,9 @@ const [state, setState] = createStore<JournalStreamState>({
|
||||||
connectionStatus: "disconnected",
|
connectionStatus: "disconnected",
|
||||||
connectionError: null,
|
connectionError: null,
|
||||||
myName: initialName,
|
myName: initialName,
|
||||||
|
myRole: (persisted.myRole as "gm" | "player" | "observer") || "gm",
|
||||||
brokerUrl: persisted.brokerUrl,
|
brokerUrl: persisted.brokerUrl,
|
||||||
|
players: {},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Sync initial URL params if they came from localStorage (not URL)
|
// Sync initial URL params if they came from localStorage (not URL)
|
||||||
|
|
@ -127,6 +136,17 @@ export function setMyName(name: string): void {
|
||||||
syncUrlParam("player", name);
|
syncUrlParam("player", name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change the current player's role. Persisted to localStorage.
|
||||||
|
* Only callable when disconnected.
|
||||||
|
*/
|
||||||
|
export function setMyRole(role: "gm" | "player" | "observer"): void {
|
||||||
|
setState("myRole", role);
|
||||||
|
if (typeof localStorage !== "undefined") {
|
||||||
|
localStorage.setItem(LS_PLAYER_ROLE, role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the active session ID and sync to URL. Also resolves the human-readable
|
* Set the active session ID and sync to URL. Also resolves the human-readable
|
||||||
* session name from the cached manifest.
|
* session name from the cached manifest.
|
||||||
|
|
@ -270,7 +290,7 @@ export async function connectStream(
|
||||||
|
|
||||||
return new Promise<void>((resolve, reject) => {
|
return new Promise<void>((resolve, reject) => {
|
||||||
const client = mqtt.connect(brokerUrl, {
|
const client = mqtt.connect(brokerUrl, {
|
||||||
clientId: `${state.myName}-${Date.now()}`,
|
clientId: `${state.myName}-${state.myRole}-${Date.now()}`,
|
||||||
protocol: brokerUrl.startsWith("wss") ? "wss" : "ws",
|
protocol: brokerUrl.startsWith("wss") ? "wss" : "ws",
|
||||||
reconnectPeriod: 2000,
|
reconnectPeriod: 2000,
|
||||||
});
|
});
|
||||||
|
|
@ -297,6 +317,19 @@ export async function connectStream(
|
||||||
if (err) console.error("[stream] sessions sub err:", err);
|
if (err) console.error("[stream] sessions sub err:", err);
|
||||||
});
|
});
|
||||||
client.subscribe(`ttrpg/${sessionId}/meta`, { qos: 1 });
|
client.subscribe(`ttrpg/${sessionId}/meta`, { qos: 1 });
|
||||||
|
// Presence tracking
|
||||||
|
client.subscribe(`ttrpg/${sessionId}/presence/+`, { qos: 1 });
|
||||||
|
|
||||||
|
// Publish own presence (retained)
|
||||||
|
const presenceData = JSON.stringify({
|
||||||
|
name: state.myName,
|
||||||
|
role: state.myRole,
|
||||||
|
});
|
||||||
|
client.publish(
|
||||||
|
`ttrpg/${sessionId}/presence/${state.myName}`,
|
||||||
|
presenceData,
|
||||||
|
{ qos: 1, retain: true },
|
||||||
|
);
|
||||||
|
|
||||||
resolve();
|
resolve();
|
||||||
});
|
});
|
||||||
|
|
@ -340,6 +373,33 @@ export async function connectStream(
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Presence: ttrpg/{sessionId}/presence/{playerName}
|
||||||
|
if (
|
||||||
|
parts.length >= 4 &&
|
||||||
|
parts[0] === "ttrpg" &&
|
||||||
|
parts[2] === "presence"
|
||||||
|
) {
|
||||||
|
const playerName = parts[3];
|
||||||
|
if (raw) {
|
||||||
|
try {
|
||||||
|
const presence = JSON.parse(raw);
|
||||||
|
setState("players", playerName, {
|
||||||
|
role: presence.role || "player",
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
setState("players", playerName, { role: "player" });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Tombstone — player disconnected
|
||||||
|
setState(
|
||||||
|
produce((s) => {
|
||||||
|
delete s.players[playerName];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (parts.length >= 3 && parts[0] === "ttrpg" && parts[2] === "stream") {
|
if (parts.length >= 3 && parts[0] === "ttrpg" && parts[2] === "stream") {
|
||||||
try {
|
try {
|
||||||
const msg: StreamMessage = JSON.parse(raw);
|
const msg: StreamMessage = JSON.parse(raw);
|
||||||
|
|
@ -505,12 +565,24 @@ export function revertLatest():
|
||||||
|
|
||||||
export function disconnectStream(): void {
|
export function disconnectStream(): void {
|
||||||
if (_mqttClient) {
|
if (_mqttClient) {
|
||||||
_mqttClient.end(true);
|
// Clear our presence before disconnecting (tombstone)
|
||||||
|
const sessionId = state.sessionId;
|
||||||
|
if (sessionId) {
|
||||||
|
_mqttClient.publish(`ttrpg/${sessionId}/presence/${state.myName}`, "", {
|
||||||
|
qos: 1,
|
||||||
|
retain: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Force disconnect without reconnect
|
||||||
|
_mqttClient.end(true, void 0, () => {
|
||||||
|
// noop
|
||||||
|
});
|
||||||
_mqttClient = null;
|
_mqttClient = null;
|
||||||
_mqttConnected = false;
|
_mqttConnected = false;
|
||||||
}
|
}
|
||||||
setState("connected", false);
|
setState("connected", false);
|
||||||
setState("connectionStatus", "disconnected");
|
setState("connectionStatus", "disconnected");
|
||||||
|
setState("players", {});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue