-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathwidget.tsx
More file actions
335 lines (313 loc) · 14.6 KB
/
Copy pathwidget.tsx
File metadata and controls
335 lines (313 loc) · 14.6 KB
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
import { useState } from "react";
import {
McpUseProvider,
useWidget,
useWidgetTheme,
useCallTool,
type WidgetMetadata,
} from "mcp-use/react";
import { Brand } from "../shared/branding";
import { useFormat, useStrings } from "../shared/i18n";
import { z } from "zod";
// ── Schema ──────────────────────────────────────────────────────────────────
const courseSchema = z.object({
id: z.number(),
title: z.string(),
description: z.string().nullable(),
thumbnail_url: z.string().nullable(),
tags: z.union([z.array(z.string()), z.string(), z.null()]),
lesson_count: z.number(),
enrolled: z.boolean(),
has_access: z.boolean(),
covered_by_plan: z.boolean(),
// Cheapest active product covering this course. `null` = not individually
// for sale. Optional so a payload from an older server still validates.
price: z.number().nullable().optional(),
currency: z.string().nullable().optional(),
});
const propsSchema = z.object({
total: z.number(),
has_subscription: z.boolean(),
courses: z.array(courseSchema),
});
export const widgetMetadata: WidgetMetadata = {
description:
"School course catalog grid showing which courses the student has access to and which their plan covers",
props: propsSchema,
exposeAsTool: false,
metadata: {
invoking: "Browsing catalog...",
invoked: "Catalog ready",
},
};
type Props = z.infer<typeof propsSchema>;
// ── Strings ──────────────────────────────────────────────────────────────────
const STRINGS = {
en: {
loading: "Browsing catalog…",
title: "Course Catalog",
summary: (n: number, s: string) => `${s} published course${n === 1 ? "" : "s"}`,
subscriptionActive: " · subscription active",
empty: "No published courses found",
lessons: (n: number, s: string) => `${s} lesson${n === 1 ? "" : "s"}`,
enrolled: "✓ Enrolled",
// One verb for "get into this course", whichever entitlement gets you in.
start: "Start course",
enrolling: "Enrolling…",
getAccess: "Get access",
notInPlan: "Not in your plan",
free: "Free",
enrollFailed: (title: string) => `Could not enroll in "${title}". Please try again.`,
},
es: {
loading: "Explorando el catálogo…",
title: "Catálogo de cursos",
summary: (n: number, s: string) =>
`${s} ${n === 1 ? "curso publicado" : "cursos publicados"}`,
subscriptionActive: " · suscripción activa",
empty: "No se encontraron cursos publicados",
lessons: (n: number, s: string) => `${s} ${n === 1 ? "lección" : "lecciones"}`,
enrolled: "✓ Inscrito",
start: "Empezar curso",
enrolling: "Inscribiendo…",
getAccess: "Obtener acceso",
notInPlan: "No incluido en tu plan",
free: "Gratis",
enrollFailed: (title: string) =>
`No se pudo inscribir en "${title}". Inténtalo de nuevo.`,
},
};
// ── Helpers ──────────────────────────────────────────────────────────────────
function normalizeTags(tags: string[] | string | null): string[] {
if (!tags) return [];
if (Array.isArray(tags)) return tags;
try {
const parsed = JSON.parse(tags);
if (Array.isArray(parsed)) return parsed;
} catch {
// not JSON
}
return tags.split(",").map((t) => t.trim()).filter(Boolean);
}
// ── Component ────────────────────────────────────────────────────────────────
export default function CourseCatalog() {
const { props, isPending, sendFollowUpMessage } = useWidget<Props>();
const theme = useWidgetTheme();
// Explicit generics: the tool-registry types are generated by `mcp-use dev`
// and this tool is registered in a sibling file not yet picked up locally.
const { callTool: enrollInCourse } = useCallTool<{ course_id: number }>(
"lms_enroll_in_course"
);
// Per-item state, tracked by course_id — one shared hook instance serves
// every card, so which card is pending/enrolled must be tracked separately.
const [pendingIds, setPendingIds] = useState<Set<number>>(new Set());
const [enrolledIds, setEnrolledIds] = useState<Set<number>>(new Set());
const [enrollError, setEnrollError] = useState<string | null>(null);
const dark = theme === "dark";
const t = useStrings(STRINGS);
const fmt = useFormat();
if (isPending) {
return (
<McpUseProvider autoSize>
<Brand />
<div className={dark ? "dark" : ""}>
<div className="bg-zinc-50 p-10 text-center font-sans text-zinc-400 dark:bg-zinc-950 dark:text-zinc-500">
<div className="mx-auto mb-3 size-9 animate-spin rounded-full border-[3px] border-zinc-200 border-t-[var(--brand-600)] dark:border-zinc-800 dark:border-t-[var(--brand-400)]" />
<p className="m-0 text-sm">{t.loading}</p>
</div>
</div>
</McpUseProvider>
);
}
const { total, has_subscription, courses } = props;
const handleEnroll = (courseId: number, title: string) => {
setPendingIds((prev) => new Set(prev).add(courseId));
setEnrollError(null);
enrollInCourse(
{ course_id: courseId },
{
onSuccess: () => {
setEnrolledIds((prev) => new Set(prev).add(courseId));
sendFollowUpMessage(
`I just enrolled in ${title} — what should I start with?`
);
},
onError: () =>
setEnrollError(t.enrollFailed(title)),
onSettled: () => {
setPendingIds((prev) => {
const next = new Set(prev);
next.delete(courseId);
return next;
});
},
}
);
};
return (
<McpUseProvider autoSize>
<Brand />
<div className={dark ? "dark" : ""}>
<div className="mx-auto max-w-[820px] bg-zinc-50 p-6 font-sans dark:bg-zinc-950">
<div className="mb-4.5 flex flex-wrap items-baseline justify-between gap-2">
<h1 className="m-0 text-[22px] font-bold tracking-tight text-zinc-900 dark:text-zinc-100">
{t.title}
</h1>
<span className="text-[13px] text-zinc-500 dark:text-zinc-400">
{t.summary(total, fmt.number(total))}
{has_subscription ? t.subscriptionActive : ""}
</span>
</div>
{enrollError && (
<div
className="mb-3 rounded-[10px] bg-red-50 px-[13px] py-[9px] text-[13px] text-red-700 dark:bg-red-950 dark:text-red-400"
role="alert"
>
{enrollError}
</div>
)}
{courses.length === 0 ? (
<div className="rounded-xl border border-zinc-200 bg-white p-10 text-center dark:border-zinc-800 dark:bg-zinc-900">
<div className="mb-2 text-[32px]">📚</div>
<p className="m-0 text-[15px] font-semibold text-zinc-900 dark:text-zinc-100">
{t.empty}
</p>
</div>
) : (
/*
Four named rows — media, heading, tags, footer — declared on the
grid and adopted by every card via `grid-rows-subgrid`. Optional
blocks then collapse *in step*: a card with no description or no
tags leaves a short row rather than a hole, and the tag rows and
footers line up across the row instead of floating to wherever
each card's own content happened to end. When no card in a row
has a thumbnail the media row collapses to nothing, which is why
the placeholder below can simply not be rendered.
*/
<div className="grid grid-cols-[repeat(auto-fill,minmax(230px,1fr))] grid-rows-[auto_auto_auto_auto] gap-3.5">
{courses.map((course) => {
const tags = normalizeTags(course.tags).slice(0, 3);
const owned = course.enrolled || enrolledIds.has(course.id);
const canEnter = course.covered_by_plan || course.has_access;
const price = course.price ?? null;
const priceLabel =
price === null
? null
: price === 0
? t.free
: fmt.currency(price, course.currency);
return (
<div
key={course.id}
className="row-span-4 grid grid-rows-subgrid overflow-hidden rounded-xl border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-900"
>
{/*
A 96px grey block with a book emoji on every card carried
no information and cost more vertical space than the title
it sat above. With no image there is simply no media row.
*/}
{course.thumbnail_url ? (
<div
className="h-24 bg-zinc-100 bg-cover bg-center dark:bg-zinc-800"
style={{ backgroundImage: `url(${course.thumbnail_url})` }}
/>
) : (
<div />
)}
<div className="px-3.5 pt-3.5">
<div className="text-[14.5px] leading-[1.3] font-semibold text-zinc-900 dark:text-zinc-100">
{course.title}
</div>
{course.description && (
<div className="mt-1 line-clamp-2 text-xs leading-[1.45] text-zinc-400 dark:text-zinc-500">
{course.description}
</div>
)}
</div>
<div className="px-3.5">
{tags.length > 0 && (
<div className="flex flex-wrap gap-[5px] pt-2">
{tags.map((tag) => (
<span
key={tag}
className="rounded-lg bg-zinc-100 px-2 py-0.5 text-[10.5px] font-semibold text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400"
>
{tag}
</span>
))}
</div>
)}
</div>
<div className="flex items-center justify-between gap-2 px-3.5 pt-2 pb-3.5">
<span className="min-w-0 text-[11.5px] text-zinc-400 dark:text-zinc-500">
{t.lessons(course.lesson_count, fmt.number(course.lesson_count))}
{/* Price only where it changes a decision — once the
student is in, what it would have cost is noise. */}
{!owned && !canEnter && priceLabel && (
<span className="ml-1.5 font-semibold text-zinc-900 dark:text-zinc-100">
· {priceLabel}
</span>
)}
</span>
{owned ? (
<span className="shrink-0 rounded-full bg-green-100 px-[9px] py-[3px] text-[11px] font-bold text-green-600 dark:bg-green-900 dark:text-green-400">
{t.enrolled}
</span>
) : course.covered_by_plan ? (
<button
onClick={() => handleEnroll(course.id, course.title)}
disabled={pendingIds.has(course.id)}
className="shrink-0 cursor-pointer rounded-full border-none bg-[var(--brand-600)] px-2.5 py-[3px] text-[11px] font-bold text-white disabled:cursor-default disabled:opacity-60 dark:bg-[var(--brand-400)] dark:text-zinc-950"
>
{pendingIds.has(course.id) ? t.enrolling : t.start}
</button>
) : course.has_access ? (
/*
Already entitled but not enrolled — `lms_enroll_in_course`
only accepts plan-covered courses, so this opens the
course instead of enrolling. Different call, same act
as far as the student is concerned, so the same label.
*/
<button
onClick={() =>
sendFollowUpMessage(
`Open the course "${course.title}" with lms_get_course_content so I can start it.`
)
}
className="shrink-0 cursor-pointer rounded-full border-none bg-[var(--brand-600)] px-2.5 py-[3px] text-[11px] font-bold text-white dark:bg-[var(--brand-400)] dark:text-zinc-950"
>
{t.start}
</button>
) : priceLabel ? (
/*
The old dead end: "Not in plan" in grey, on the only
cards where the student still had a decision to make.
Purchases complete in the app, so this hands off to the
assistant rather than pretending to check out here.
*/
<button
onClick={() =>
sendFollowUpMessage(
`I want access to the course "${course.title}". What are my options — can I buy it or upgrade my plan?`
)
}
className="shrink-0 cursor-pointer rounded-full border border-[var(--brand-600)] bg-transparent px-2.5 py-[3px] text-[11px] font-bold text-[var(--brand-600)] dark:border-[var(--brand-400)] dark:text-[var(--brand-400)]"
>
{t.getAccess}
</button>
) : (
<span className="shrink-0 text-[11px] text-zinc-400 dark:text-zinc-500">
{t.notInPlan}
</span>
)}
</div>
</div>
);
})}
</div>
)}
</div>
</div>
</McpUseProvider>
);
}