Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | 1x 1x 5x 5x 5x 5x 5x 5x 5x 10x 10x 10x 17x 17x 17x 17x 12x 17x 17x 17x 17x 17x 10x 5x 5x 5x 5x 5x 2x 1x 1x 1x 1x 5x 5x 5x 5x 6x 6x 2x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 2x 6x 2x 2x 2x 2x 2x 4x 4x 4x 4x 2x 2x 5x 8x 8x 8x 8x 5x 5x 8x 4x 5x 5x 15x 5x 5x 5x 7x 21x 7x 7x 2x 5x 5x 8x 5x 5x 5x 5x 5x 5x 5x 5x 5x 10x 13x 7x 13x 6x 10x | import { useEffect, useState } from 'react';
import {
IconArrowBack,
IconArrowForward,
IconChevronRight,
IconClock,
IconThumbDown,
IconThumbUp,
} from '@tabler/icons-react';
import {
Accordion,
ActionIcon,
Avatar,
Badge,
Box,
Button,
Card,
Group,
MantineTheme,
Paper,
rem,
Slider,
Stack,
Text,
Tooltip,
Transition,
} from '@mantine/core';
// Types for our conversation system
export interface Dimension {
id: string;
name: string;
description: string;
}
export interface Vote {
userId: string;
value: number; // -5 to 5
dimension: string;
}
export interface ConversationBranch {
id: string;
parentId: string | null;
content: string;
author: {
id: string;
name: string;
avatar?: string;
isAI: boolean;
};
timestamp: Date;
votes: Vote[];
isSelected: boolean;
isViable: boolean;
isHidden: boolean;
}
export interface Thread {
id: string;
title: string;
branches: ConversationBranch[];
dimensions: Dimension[];
activeInterval: number | null; // null means no active interval (manually selecting)
}
// Custom hook for timer
const useInterval = (callback: () => void, delay: number | null) => {
useEffect(() => {
Iif (delay === null) {
return;
}
const id = setInterval(callback, delay);
return () => {
clearInterval(id);
};
}, [callback, delay]);
};
// Component to display a vote slider for a specific dimension
function DimensionVoteSlider({
dimension,
_branchId,
initialValue = 0,
onVote,
}: {
dimension: Dimension;
_branchId: string;
initialValue?: number;
onVote: (dimensionId: string, value: number) => void;
}) {
const [value, setValue] = useState(initialValue);
return (
<Box mb="xs">
<Group mb={5} justify="space-between">
<Text size="sm" fw={500}>
{dimension.name}
</Text>
<Badge variant="light" size="sm">
{value}
</Badge>
</Group>
<Slider
marks={[
{ value: -5, label: '-5' },
{ value: 0, label: '0' },
{ value: 5, label: '5' },
]}
min={-5}
max={5}
step={1}
value={value}
onChange={(newValue) => {
setValue(newValue);
onVote(dimension.id, newValue);
}}
/>
</Box>
);
}
// Component to display a single branch
function Branch({
branch,
dimensions,
isMainBranch = false,
onVote,
onExpand,
onSelect,
}: {
branch: ConversationBranch;
dimensions: Dimension[];
isMainBranch?: boolean;
onVote: (branchId: string, dimensionId: string, value: number) => void;
onExpand?: () => void;
onSelect?: () => void;
}) {
const [expanded, setExpanded] = useState(false);
const { author, content, timestamp, isSelected, isViable } = branch;
// Calculate average vote score across all dimensions
const averageScore =
branch.votes.length > 0
? branch.votes.reduce((sum, vote) => sum + vote.value, 0) / branch.votes.length
: 0;
// Format the timestamp
const formattedTime = new Date(timestamp).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
});
const handleExpand = () => {
setExpanded(!expanded);
if (onExpand) {
onExpand();
}
};
// Display branch differently based on its status
return (
<Card
withBorder
shadow={isMainBranch ? 'md' : 'sm'}
padding={isMainBranch ? 'md' : 'sm'}
radius="md"
mb="md"
styles={{
root: (theme: MantineTheme) => ({
borderLeft: isSelected ? `${rem(4)} solid ${theme.colors.blue[5]}` : undefined,
opacity: !isViable && !isSelected ? 0.7 : 1,
backgroundColor: isMainBranch ? theme.colors.gray[0] : undefined,
maxWidth: isMainBranch ? '100%' : '95%',
marginLeft: isMainBranch ? 0 : 'auto',
}),
}}
>
<Group justify="space-between" mb="xs">
<Group>
<Avatar src={author.avatar} radius="xl" size="md" color={author.isAI ? 'blue' : 'red'}>
{author.name.charAt(0)}
</Avatar>
<div>
<Text fw={500}>{author.name}</Text>
<Group gap="xs">
<Text size="xs" c="dimmed">
{formattedTime}
</Text>
{author.isAI ? (
<Badge size="xs" variant="outline" color="blue">
AI
</Badge>
) : null}
{isSelected ? (
<Badge size="xs" color="green">
Selected
</Badge>
) : null}
{!isSelected && isViable ? (
<Badge size="xs" color="yellow">
Viable
</Badge>
) : null}
</Group>
</div>
</Group>
<Group gap="xs">
<Badge
leftSection={
averageScore > 0 ? (
<IconThumbUp size={12} />
) : averageScore < 0 ? (
<IconThumbDown size={12} />
) : null
}
color={averageScore > 0 ? 'green' : averageScore < 0 ? 'red' : 'gray'}
>
{averageScore.toFixed(1)}
</Badge>
{!isMainBranch && (
<Tooltip label="Select this branch">
<ActionIcon onClick={onSelect} variant="light" color="blue" disabled={isSelected}>
<IconChevronRight size={18} />
</ActionIcon>
</Tooltip>
)}
</Group>
</Group>
<Text size={isMainBranch ? 'md' : 'sm'} mb="md">
{content}
</Text>
{!isMainBranch && (
<Accordion
value={expanded ? 'votes' : null}
onChange={() => {
handleExpand();
}}
>
<Accordion.Item value="votes">
<Accordion.Control>Rate this response</Accordion.Control>
<Accordion.Panel>
<Stack gap="xs">
{dimensions.map((dimension) => (
<DimensionVoteSlider
key={dimension.id}
dimension={dimension}
_branchId={branch.id}
onVote={(dimensionId, value) => {
onVote(branch.id, dimensionId, value);
}}
/>
))}
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
)}
</Card>
);
}
// Main component that displays the threaded conversation
export function ThreadedConversation({ thread }: { thread: Thread }) {
const [activeThread, setActiveThread] = useState<Thread>(thread);
const [timeUntilNextSelection, setTimeUntilNextSelection] = useState<number | null>(
thread.activeInterval ?? null
);
// Update the timer every second
useInterval(() => {
if (timeUntilNextSelection !== null && timeUntilNextSelection > 0) {
setTimeUntilNextSelection(timeUntilNextSelection - 1000);
} else if (timeUntilNextSelection === 0) {
// Auto-select the highest rated branch
selectHighestRatedBranch();
// Reset the timer
setTimeUntilNextSelection(thread.activeInterval);
E}
}, 1000);
// Organize branches by their parent-child relationships
const organizedBranches = organizeBranches(activeThread.branches);
// Handler for voting on a branch
const handleVote = (branchId: string, dimensionId: string, value: number) => {
// Find the branch to update
const updatedBranches = activeThread.branches.map((branch) => {
if (branch.id === branchId) {
// Check if there's already a vote for this dimension
const existingVoteIndex = branch.votes.findIndex(
(vote) => vote.dimension === dimensionId && vote.userId === 'current-user'
);
if (existingVoteIndex >= 0) {
// Update existing vote
const updatedVotes = [...branch.votes];
const existingVote = updatedVotes[existingVoteIndex];
if (existingVote) {
updatedVotes[existingVoteIndex] = {
...existingVote,
value,
};
}
return { ...branch, votes: updatedVotes };
}
// Add new vote
return {
...branch,
votes: [...branch.votes, { userId: 'current-user', dimension: dimensionId, value }],
};
}
return branch;
});
setActiveThread({
...activeThread,
branches: updatedBranches,
});
};
// Select a branch manually
const handleSelectBranch = (branchId: string) => {
// Mark the selected branch and update viable branches
const updatedBranches = activeThread.branches.map((branch) => {
if (branch.id === branchId) {
return { ...branch, isSelected: true };
} else if (branch.parentId === getParentIdForBranch(branchId)) {
// For branches with the same parent, determine if they should remain viable
const shouldRemainViable = calculateBranchScore(branch) > 0;
return {
...branch,
isSelected: false,
isViable: shouldRemainViable,
isHidden: !shouldRemainViable && branch.id !== branchId,
};
}
return branch;
});
setActiveThread({
...activeThread,
branches: updatedBranches,
});
// Reset the timer if we're on automatic mode
if (activeThread.activeInterval !== null) {
setTimeUntilNextSelection(activeThread.activeInterval);
E}
};
// Automatically select the highest rated branch among the current options
const selectHighestRatedBranch = () => {
// Get all viable branches that are not yet selected
const currentLevelBranches = activeThread.branches.filter(
(branch) => !branch.isSelected && !branch.isHidden && branch.isViable
);
const firstBranch = currentLevelBranches[0];
Iif (currentLevelBranches.length === 0 || !firstBranch) {
return;
}
// Find branch with highest score
let highestRatedBranch = firstBranch;
let highestScore = calculateBranchScore(highestRatedBranch);
currentLevelBranches.forEach((branch) => {
const score = calculateBranchScore(branch);
Iif (score > highestScore) {
highestRatedBranch = branch;
highestScore = score;
}
});
// Select the highest rated branch
handleSelectBranch(highestRatedBranch.id);
};
// Helper function to calculate a branch's score based on votes
const calculateBranchScore = (branch: ConversationBranch): number => {
Iif (branch.votes.length === 0) {
return 0;
}
return branch.votes.reduce((sum, vote) => sum + vote.value, 0) / branch.votes.length;
};
// Helper to get the parent ID for a branch
const getParentIdForBranch = (branchId: string): string | null => {
const branch = activeThread.branches.find((b) => b.id === branchId);
return branch ? branch.parentId : null;
};
// Helper function to organize branches into a threaded structure
function organizeBranches(branches: ConversationBranch[]): ConversationBranch[][] {
const result: ConversationBranch[][] = [];
const rootBranches = branches.filter((b) => b.parentId === null);
// Add root branches
result.push(rootBranches);
// Now build the thread by following selected branches
let currentParentId: string | null = rootBranches.find((b) => b.isSelected)?.id ?? null;
while (currentParentId !== null) {
const childBranches = branches.filter(
(b) => b.parentId === currentParentId && (!b.isHidden || b.isSelected)
);
if (childBranches.length === 0) {
break;
}
result.push(childBranches);
// Find the next selected branch
const nextSelected = childBranches.find((b) => b.isSelected);
currentParentId = nextSelected?.id ?? null;
}
return result;
}
// Format the time until next selection
const formatTimeRemaining = (ms: number) => {
const seconds = Math.floor(ms / 1000);
return `${String(seconds)}s`;
};
return (
<Stack>
<Paper p="md" withBorder>
<Group justify="space-between">
<Text size="xl" fw={700}>
{activeThread.title}
</Text>
{timeUntilNextSelection !== null && (
<Group gap="xs">
<IconClock size={16} />
<Text size="sm">
Next selection in: {formatTimeRemaining(timeUntilNextSelection)}
</Text>
</Group>
)}
</Group>
</Paper>
{organizedBranches.map((levelBranches, level) => (
<Box key={`level-${String(level)}`} pl={level > 0 ? 20 : 0}>
{/* Display selected branch for this level as main */}
{levelBranches
.filter((b) => b.isSelected)
.map((branch) => (
<Branch
key={branch.id}
branch={branch}
dimensions={activeThread.dimensions}
isMainBranch
onVote={handleVote}
/>
))}
{/* Display other branches (viable alternatives) */}
{levelBranches
.filter((b) => !b.isSelected && !b.isHidden)
.map((branch) => (
<Transition
key={branch.id}
mounted={!branch.isHidden}
transition="fade"
duration={400}
>
{(styles) => (
<div style={styles}>
<Branch
branch={branch}
dimensions={activeThread.dimensions}
onVote={handleVote}
onSelect={() => {
handleSelectBranch(branch.id);
}}
/>
</div>
)}
</Transition>
))}
</Box>
))}
{activeThread.activeInterval !== null && (
<Group justify="center" mt="md">
<Button
variant="outline"
leftSection={<IconArrowBack size={16} />}
onClick={() => {
// Reset the timer
setTimeUntilNextSelection(activeThread.activeInterval);
}}
>
Reset Timer
</Button>
<Button
color="blue"
leftSection={<IconArrowForward size={16} />}
onClick={selectHighestRatedBranch}
>
Select Top Branch Now
</Button>
</Group>
)}
</Stack>
);
}
|