@tansy/lms 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/outline.js ADDED
@@ -0,0 +1,21 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { adminPath, apiPath, translate, useT } from "tansy/admin";
4
+ /** Enrolls each address that has an account. Says how many, never which, as the route does. */
5
+ export async function enrollByEmail(course, typed) {
6
+ const emails = [...new Set(typed.split(/[\s,;]+/).map((email) => email.trim()).filter(Boolean))];
7
+ const response = await fetch(apiPath("/ext/lms/enrollments"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ course, emails }) });
8
+ const json = await response.json().catch(() => null);
9
+ if (!response.ok)
10
+ return json?.error?.message ?? translate("ext.lms.enroll.failed");
11
+ const counts = { enrolled: json?.enrolled ?? 0, already: json?.already ?? 0, unknown: json?.unknown ?? 0 };
12
+ return translate(counts.unknown ? "ext.lms.enroll.resultUnknown" : "ext.lms.enroll.result", counts);
13
+ }
14
+ /** On a course, section or lesson, a way back to the course builder, where its outline is edited. */
15
+ export function BuilderPanel({ collection, recordId, values }) {
16
+ const { t } = useT();
17
+ const course = collection.slug === "lms-courses" ? Number(recordId) : Number(values.course);
18
+ if (!["lms-courses", "lms-sections", "lms-lessons", "lms-quizzes"].includes(collection.slug) || !Number.isSafeInteger(course) || course <= 0)
19
+ return null;
20
+ return (_jsx("section", { className: "cms-panel cms-cell", children: _jsx("p", { className: "cms-text-sm", children: t("ext.lms.enroll.builderPanel", { link: "\u0000" }).split("\u0000").flatMap((part, index) => (index ? [_jsx("a", { className: "cms-link", href: adminPath(`/ext/lms/courses/${course}`), children: t("ext.lms.enroll.builderLink") }, "link"), part] : [part])) }) }));
21
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@tansy/lms",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Turns tansy into a learning platform: courses, lessons, enrollments, progress, quizzes and certificates.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-plugin",
8
+ "cms",
9
+ "nextjs"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
13
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
17
+ "directory": "plugins/lms"
18
+ },
19
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.ts",
23
+ "default": "./index.js"
24
+ },
25
+ "./admin": {
26
+ "types": "./admin.d.ts",
27
+ "default": "./admin.js"
28
+ },
29
+ "./client": {
30
+ "types": "./client.d.ts",
31
+ "default": "./client.js"
32
+ },
33
+ "./render": {
34
+ "types": "./render.d.ts",
35
+ "default": "./render.js"
36
+ }
37
+ },
38
+ "peerDependencies": {
39
+ "next": "^16.4.6",
40
+ "react": "^19.3.0",
41
+ "tansy": "^0.1.0"
42
+ },
43
+ "dependencies": {
44
+ "zod": "^4.6.7"
45
+ }
46
+ }
package/parts.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { type SiteWords } from "tansy/react";
2
+ /** Enrolls the visitor in a free course, or one their plan covers, sending them to sign in first if they need to. */
3
+ export declare function EnrollButton({ courseId, continueHref, label, words }: {
4
+ courseId: number;
5
+ continueHref: string | null;
6
+ label?: string;
7
+ words?: SiteWords;
8
+ }): import("react").JSX.Element;
9
+ /**
10
+ * A paid course, bought through the Payments plugin. Payments is reached over its API only,
11
+ * so without it, or before a payment provider is connected, the course just isn't on sale yet.
12
+ * After paying, the enrollment arrives from the provider's webhook, so this waits for it.
13
+ */
14
+ export declare function CourseOffer({ courseId, words }: {
15
+ courseId: number;
16
+ words?: SiteWords;
17
+ }): import("react").JSX.Element | null;
18
+ /** A plan from the Payments plugin, as a pricing page or course page shows it. */
19
+ export interface PlanOption {
20
+ name: string;
21
+ title: string;
22
+ amount: number | null;
23
+ annualAmount: number | null;
24
+ currency: string | null;
25
+ featured: boolean;
26
+ }
27
+ /**
28
+ * Subscribes to a plan through the Payments plugin, over its API only, so the LMS never imports it.
29
+ * Back from the provider with `?subscription=success`, it says so: the plan's courses open once the
30
+ * provider confirms, and the person enrolls in each with one click.
31
+ */
32
+ export declare function SubscribeToPlan({ plan, annual, label, className, words }: {
33
+ plan: PlanOption;
34
+ annual?: boolean;
35
+ label?: string;
36
+ className?: string;
37
+ words?: SiteWords;
38
+ }): import("react").JSX.Element;
39
+ /** Says so when the visitor is back from subscribing. */
40
+ export declare function SubscribedNotice({ words }: {
41
+ words?: SiteWords;
42
+ }): import("react").JSX.Element | null;
43
+ /** Marks the lesson done, then moves on to the next one when there is one. */
44
+ export declare function MarkComplete({ lessonId, done, nextHref, words }: {
45
+ lessonId: number;
46
+ done: boolean;
47
+ nextHref: string | null;
48
+ words?: SiteWords;
49
+ }): import("react").JSX.Element;
50
+ /** Loads a quiz's questions without their answers, and sends answers to be graded on the server. */
51
+ export declare function Quiz({ quizId, words }: {
52
+ quizId: number;
53
+ words?: SiteWords;
54
+ }): import("react").JSX.Element;
55
+ /** The signed-in learner's courses, with their progress and where to pick up. */
56
+ export declare function MyCourses({ words }: {
57
+ words?: SiteWords;
58
+ }): import("react").JSX.Element;
59
+ /** `name` is the bar's accessible name, so the page sends one word to the browser rather than all of them. */
60
+ export declare function Progress({ percent, label, name, words }: {
61
+ percent: number;
62
+ label: string;
63
+ name?: string;
64
+ words?: SiteWords;
65
+ }): import("react").JSX.Element;
66
+ /** Checks a certificate code, from the form or the page's ?code=, so a link can carry it. */
67
+ export declare function CertificateCheck({ words }: {
68
+ words?: SiteWords;
69
+ }): import("react").JSX.Element;
package/parts.js ADDED
@@ -0,0 +1,295 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useEffect, useId, useState } from "react";
4
+ import { useSearchParams } from "next/navigation";
5
+ import { apiPath, authPath, contentLocale, sitePath } from "tansy/react";
6
+ import { money } from "./logic";
7
+ import { lmsWords } from "./words";
8
+ /**
9
+ * The LMS's parts with behaviour. Each takes the page's `words` (`pickWords(words, "lms")`
10
+ * from a template) to speak its language, read courses in it and keep links in it. Without them, English.
11
+ */
12
+ const ext = (path) => apiPath(`/ext/lms${path}`);
13
+ /** `?locale=…` on the LMS's reads, on a site with more than one language. */
14
+ const inLanguage = (words) => (contentLocale(words) ? `?locale=${encodeURIComponent(contentLocale(words))}` : "");
15
+ const here = () => `${window.location.pathname}${window.location.search}`;
16
+ const signInHref = () => authPath(`signin?next=${encodeURIComponent(here())}`);
17
+ async function post(path, body) {
18
+ const response = await fetch(ext(path), { method: "POST", headers: body === undefined ? {} : { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
19
+ const json = await response.json().catch(() => null);
20
+ return { status: response.status, ok: response.ok, json };
21
+ }
22
+ /** Enrolls the visitor in a free course, or one their plan covers, sending them to sign in first if they need to. */
23
+ export function EnrollButton({ courseId, continueHref, label, words }) {
24
+ const { t } = lmsWords(words);
25
+ const [busy, setBusy] = useState(false);
26
+ const [error, setError] = useState(null);
27
+ async function enroll() {
28
+ setBusy(true);
29
+ setError(null);
30
+ try {
31
+ const { status, ok } = await post(`/courses/${courseId}/enroll`);
32
+ if (status === 401)
33
+ return void window.location.assign(signInHref());
34
+ if (!ok)
35
+ return setError(t("lms.enrollFailed"));
36
+ // The course's lessons now open, so the page reads them as this learner.
37
+ window.location.assign(continueHref ?? here());
38
+ }
39
+ catch {
40
+ setError(t("lms.enrollOffline"));
41
+ }
42
+ finally {
43
+ setBusy(false);
44
+ }
45
+ }
46
+ return (_jsxs("div", { className: "lms-cta", children: [_jsx("button", { type: "button", className: "lms-button", onClick: enroll, disabled: busy, children: busy ? t("lms.enrolling") : label ?? t("lms.enroll") }), error && _jsx("p", { className: "lms-error", role: "alert", children: error })] }));
47
+ }
48
+ /**
49
+ * A paid course, bought through the Payments plugin. Payments is reached over its API only,
50
+ * so without it, or before a payment provider is connected, the course just isn't on sale yet.
51
+ * After paying, the enrollment arrives from the provider's webhook, so this waits for it.
52
+ */
53
+ export function CourseOffer({ courseId, words }) {
54
+ const { t } = lmsWords(words);
55
+ const params = useSearchParams();
56
+ const returned = params.get("purchase") === "success";
57
+ const sessionId = params.get("session_id");
58
+ const [offer, setOffer] = useState(null);
59
+ const [busy, setBusy] = useState(false);
60
+ const [error, setError] = useState(null);
61
+ const [slow, setSlow] = useState(false);
62
+ useEffect(() => {
63
+ let live = true;
64
+ fetch(apiPath(`/ext/payments/offer?collection=lms-courses&id=${courseId}`))
65
+ .then(async (response) => (response.ok ? (await response.json()) : null))
66
+ .catch(() => null)
67
+ .then((found) => { if (live)
68
+ setOffer(found ?? { forSale: false, amount: null, currency: null, purchased: false }); });
69
+ return () => { live = false; };
70
+ }, [courseId]);
71
+ useEffect(() => {
72
+ if (!returned)
73
+ return;
74
+ // Confirms the payment with the provider through Payments, so the purchase doesn't wait for the webhook.
75
+ if (sessionId)
76
+ void fetch(apiPath("/ext/payments/confirm"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId }) }).catch(() => null);
77
+ let tries = 0;
78
+ const timer = setInterval(async () => {
79
+ tries++;
80
+ const response = await fetch(ext("/me/courses")).catch(() => null);
81
+ const json = response?.ok ? await response.json().catch(() => null) : null;
82
+ if (json?.items?.some((item) => item.course.id === courseId)) {
83
+ clearInterval(timer);
84
+ window.location.assign(window.location.pathname);
85
+ }
86
+ else if (tries >= 20) {
87
+ clearInterval(timer);
88
+ setSlow(true);
89
+ }
90
+ }, 1500);
91
+ return () => clearInterval(timer);
92
+ }, [returned, sessionId, courseId]);
93
+ async function buy() {
94
+ setBusy(true);
95
+ setError(null);
96
+ try {
97
+ const response = await fetch(apiPath("/ext/payments/checkout"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ collection: "lms-courses", id: courseId, returnPath: window.location.pathname }) });
98
+ if (response.status === 401)
99
+ return void window.location.assign(signInHref());
100
+ const json = await response.json().catch(() => null);
101
+ if (!response.ok || !json?.url)
102
+ return setError(t("lms.checkoutFailed"));
103
+ window.location.assign(json.url);
104
+ }
105
+ catch {
106
+ setError(t("lms.checkoutOffline"));
107
+ }
108
+ finally {
109
+ setBusy(false);
110
+ }
111
+ }
112
+ if (returned) {
113
+ return slow
114
+ ? _jsx("p", { className: "lms-muted", role: "status", children: t("lms.paymentSlow") })
115
+ : _jsx("p", { className: "lms-success", role: "status", children: t("lms.paymentReceived") });
116
+ }
117
+ if (!offer)
118
+ return null;
119
+ if (offer.purchased)
120
+ return _jsx("p", { className: "lms-muted", children: t("lms.boughtNotEnrolled") });
121
+ if (!offer.forSale || offer.amount === null || !offer.currency)
122
+ return _jsx("p", { className: "lms-muted", children: t("lms.notForSale") });
123
+ return (_jsxs("div", { className: "lms-cta", children: [_jsx("button", { type: "button", className: "lms-button", onClick: buy, disabled: busy, children: busy ? t("lms.opening") : t("lms.buyFor", { price: money(offer.amount, offer.currency, words?.locale ?? "en") }) }), error && _jsx("p", { className: "lms-error", role: "alert", children: error })] }));
124
+ }
125
+ /**
126
+ * Subscribes to a plan through the Payments plugin, over its API only, so the LMS never imports it.
127
+ * Back from the provider with `?subscription=success`, it says so: the plan's courses open once the
128
+ * provider confirms, and the person enrolls in each with one click.
129
+ */
130
+ export function SubscribeToPlan({ plan, annual = false, label, className, words }) {
131
+ const { t } = lmsWords(words);
132
+ const [busy, setBusy] = useState(false);
133
+ const [error, setError] = useState(null);
134
+ async function subscribe() {
135
+ setBusy(true);
136
+ setError(null);
137
+ try {
138
+ const response = await fetch(apiPath("/ext/payments/subscribe"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ plan: plan.name, annual, returnPath: window.location.pathname }) });
139
+ if (response.status === 401)
140
+ return void window.location.assign(signInHref());
141
+ const json = await response.json().catch(() => null);
142
+ if (!response.ok || !json?.url)
143
+ return setError(t("lms.subscribeFailed"));
144
+ window.location.assign(json.url);
145
+ }
146
+ catch {
147
+ setError(t("lms.subscribeFailed"));
148
+ }
149
+ finally {
150
+ setBusy(false);
151
+ }
152
+ }
153
+ return (_jsxs("div", { className: "lms-cta", children: [_jsx("button", { type: "button", className: className ?? "lms-button", onClick: subscribe, disabled: busy, children: busy ? t("lms.opening") : label ?? t("lms.subscribeTo", { plan: plan.title }) }), error && _jsx("p", { className: "lms-error", role: "alert", children: error })] }));
154
+ }
155
+ /** Says so when the visitor is back from subscribing. */
156
+ export function SubscribedNotice({ words }) {
157
+ const { t } = lmsWords(words);
158
+ return useSearchParams().get("subscription") === "success" ? _jsx("p", { className: "lms-success", role: "status", children: t("lms.subscribed") }) : null;
159
+ }
160
+ /** Marks the lesson done, then moves on to the next one when there is one. */
161
+ export function MarkComplete({ lessonId, done, nextHref, words }) {
162
+ const { t } = lmsWords(words);
163
+ const [state, setState] = useState(done ? "done" : "idle");
164
+ const [error, setError] = useState(null);
165
+ async function complete() {
166
+ setState("busy");
167
+ setError(null);
168
+ const { ok, json } = await post(`/lessons/${lessonId}/complete`).catch(() => ({ ok: false, json: null, status: 0 }));
169
+ if (!ok) {
170
+ setState("idle");
171
+ return setError(t("lms.saveFailed"));
172
+ }
173
+ setState(json?.courseCompleted ? "course" : "done");
174
+ if (nextHref && !json?.courseCompleted)
175
+ window.location.assign(nextHref);
176
+ }
177
+ if (state === "course")
178
+ return _jsx("p", { className: "lms-success", role: "status", children: t("lms.finishedCourse") });
179
+ if (state === "done")
180
+ return _jsxs("p", { className: "lms-success", children: ["\u2713 ", t("lms.completed"), nextHref && _jsxs(_Fragment, { children: [" \u00B7 ", _jsx("a", { href: nextHref, children: t("lms.nextLesson") })] })] });
181
+ return (_jsxs("div", { className: "lms-cta", children: [_jsx("button", { type: "button", className: "lms-button", onClick: complete, disabled: state === "busy", children: state === "busy" ? t("lms.saving") : t("lms.markComplete") }), error && _jsx("p", { className: "lms-error", role: "alert", children: error })] }));
182
+ }
183
+ /** Loads a quiz's questions without their answers, and sends answers to be graded on the server. */
184
+ export function Quiz({ quizId, words }) {
185
+ const { t } = lmsWords(words);
186
+ const language = inLanguage(words);
187
+ const id = useId();
188
+ const [quiz, setQuiz] = useState(null);
189
+ const [failed, setFailed] = useState(null);
190
+ const [answers, setAnswers] = useState({});
191
+ const [result, setResult] = useState(null);
192
+ const [sending, setSending] = useState(false);
193
+ useEffect(() => {
194
+ let live = true;
195
+ fetch(ext(`/quizzes/${quizId}${language}`)).then(async (response) => {
196
+ if (!live)
197
+ return;
198
+ if (response.ok)
199
+ setQuiz(await response.json());
200
+ else
201
+ setFailed(response.status === 401 ? t("lms.quizSignIn") : t("lms.quizLocked"));
202
+ }).catch(() => live && setFailed(t("lms.quizFailed")));
203
+ return () => { live = false; };
204
+ }, [quizId, language, t]);
205
+ if (failed)
206
+ return _jsx("aside", { className: "lms-quiz", children: _jsx("p", { className: "lms-muted", children: failed }) });
207
+ if (!quiz)
208
+ return _jsx("aside", { className: "lms-quiz", children: _jsx("p", { className: "lms-muted", children: t("lms.quizLoading") }) });
209
+ const set = (question, value) => setAnswers((current) => ({ ...current, [question]: value }));
210
+ const toggle = (question, choice) => {
211
+ const current = Array.isArray(answers[question]) ? answers[question] : [];
212
+ set(question, current.includes(choice) ? current.filter((c) => c !== choice) : [...current, choice]);
213
+ };
214
+ const outOfAttempts = quiz.attemptsLeft === 0 || result?.attemptsLeft === 0;
215
+ async function submit(event) {
216
+ event.preventDefault();
217
+ setSending(true);
218
+ const { ok, status, json } = await post(`/quizzes/${quizId}/attempts${language}`, { answers }).catch(() => ({ ok: false, json: null, status: 0 }));
219
+ setSending(false);
220
+ if (!ok)
221
+ return setFailed(status === 409 ? t("lms.noAttempts") : t("lms.sendFailed"));
222
+ setResult(json);
223
+ }
224
+ return (_jsxs("aside", { className: "lms-quiz", "aria-labelledby": `${id}-title`, children: [_jsx("h2", { id: `${id}-title`, children: quiz.title }), _jsx("p", { className: "lms-muted", children: [
225
+ t("lms.passWith", { score: quiz.passingScore }),
226
+ quiz.attemptsLeft !== null ? t("lms.attemptsLeft", { count: result?.attemptsLeft ?? quiz.attemptsLeft }) : "",
227
+ quiz.passed ? t("lms.passedQuiz") : "",
228
+ quiz.best !== null ? t("lms.bestScore", { score: quiz.best }) : "",
229
+ ].filter(Boolean).join(" ") }), result && (_jsxs("p", { className: result.passed ? "lms-success" : "lms-error", role: "status", children: [t("lms.result", { correct: result.correct, total: result.total, score: result.score }), " ", result.passed ? t("lms.passed") : t("lms.notPassed")] })), !outOfAttempts && (_jsxs("form", { onSubmit: submit, children: [_jsx("ol", { className: "lms-questions", children: quiz.questions.map((question) => (_jsx("li", { children: _jsxs("fieldset", { children: [_jsx("legend", { children: question.prompt }), question.kind === "short"
230
+ ? _jsx("input", { "aria-label": t("lms.yourAnswer"), value: typeof answers[question.id] === "string" ? answers[question.id] : "", onChange: (event) => set(question.id, event.target.value), maxLength: 500 })
231
+ : question.choices.map((choice, index) => (_jsxs("label", { className: "lms-choice", children: [_jsx("input", { type: question.kind === "single" ? "radio" : "checkbox", name: `${id}-${question.id}`, checked: question.kind === "single" ? answers[question.id] === index : Array.isArray(answers[question.id]) && answers[question.id].includes(index), onChange: () => (question.kind === "single" ? set(question.id, index) : toggle(question.id, index)) }), choice] }, index)))] }) }, question.id))) }), _jsx("button", { type: "submit", className: "lms-button", disabled: sending, children: sending ? t("lms.grading") : result ? t("lms.tryAgain") : t("lms.submit") })] }))] }));
232
+ }
233
+ /** The signed-in learner's courses, with their progress and where to pick up. */
234
+ export function MyCourses({ words }) {
235
+ const { t } = lmsWords(words);
236
+ const language = inLanguage(words);
237
+ const [items, setItems] = useState(null);
238
+ const [state, setState] = useState("loading");
239
+ useEffect(() => {
240
+ fetch(ext(`/me/courses${language}`)).then(async (response) => {
241
+ if (response.status === 401)
242
+ return setState("signed-out");
243
+ if (!response.ok)
244
+ return setState("error");
245
+ setItems((await response.json()).items);
246
+ setState("ready");
247
+ }).catch(() => setState("error"));
248
+ }, [language]);
249
+ if (state === "loading")
250
+ return _jsx("p", { className: "lms-muted", children: t("lms.loadingCourses") });
251
+ if (state === "signed-out")
252
+ return _jsx("p", { children: _jsx("a", { href: signInHref(), children: t("lms.signInToSee") }) });
253
+ if (state === "error")
254
+ return _jsx("p", { className: "lms-error", children: t("lms.coursesFailed") });
255
+ if (!items?.length)
256
+ return _jsx("p", { className: "lms-muted", children: t("lms.noCourses") });
257
+ return (_jsx("ul", { className: "lms-cards", children: items.map((item) => (_jsxs("li", { className: "lms-card", children: [_jsx("h2", { children: item.course.recordPath ? _jsx("a", { href: sitePath(words, item.course.recordPath), children: item.course.title || t("lms.course") }) : item.course.title || t("lms.course") }), item.course.summary && _jsx("p", { className: "lms-muted", children: item.course.summary }), _jsx(Progress, { percent: item.percent, label: t("lms.lessonsDone", { done: item.completed, total: item.lessons }), name: t("lms.progress") }), item.enrollment.state === "completed"
258
+ ? _jsx("p", { className: "lms-success", children: t("lms.completed") })
259
+ : item.next?.recordPath && _jsx("p", { children: _jsx("a", { className: "lms-button", href: sitePath(words, item.next.recordPath), children: t("lms.continue", { title: item.next.title }) }) })] }, item.enrollment.id))) }));
260
+ }
261
+ /** `name` is the bar's accessible name, so the page sends one word to the browser rather than all of them. */
262
+ export function Progress({ percent, label, name, words }) {
263
+ return (_jsxs("div", { className: "lms-progress", children: [_jsx("div", { className: "lms-bar", role: "progressbar", "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": percent, "aria-label": name ?? lmsWords(words).t("lms.progress"), children: _jsx("span", { style: { width: `${percent}%` } }) }), _jsxs("span", { className: "lms-muted", children: [label, " \u00B7 ", percent, "%"] })] }));
264
+ }
265
+ async function verify(code, language) {
266
+ const response = await fetch(ext(`/certificates/${encodeURIComponent(code.trim())}${language}`)).catch(() => null);
267
+ if (!response)
268
+ return "error";
269
+ if (response.status === 404)
270
+ return "missing";
271
+ return response.ok ? await response.json() : "error";
272
+ }
273
+ /** Checks a certificate code, from the form or the page's ?code=, so a link can carry it. */
274
+ export function CertificateCheck({ words }) {
275
+ const { t, formatDate } = lmsWords(words);
276
+ const language = inLanguage(words);
277
+ const id = useId();
278
+ const given = useSearchParams().get("code")?.slice(0, 40) ?? "";
279
+ const [code, setCode] = useState(given);
280
+ const [result, setResult] = useState(null);
281
+ useEffect(() => {
282
+ let live = true;
283
+ if (given.trim())
284
+ void verify(given, language).then((found) => live && setResult(found));
285
+ return () => { live = false; };
286
+ }, [given, language]);
287
+ const check = (event) => {
288
+ event.preventDefault();
289
+ if (!code.trim())
290
+ return;
291
+ setResult(null);
292
+ void verify(code, language).then(setResult);
293
+ };
294
+ return (_jsxs("div", { children: [_jsxs("form", { className: "lms-form", onSubmit: check, children: [_jsx("label", { htmlFor: `${id}-code`, children: t("lms.certificateCode") }), _jsx("input", { id: `${id}-code`, value: code, onChange: (event) => setCode(event.target.value), maxLength: 40, autoComplete: "off", spellCheck: false }), _jsx("button", { type: "submit", className: "lms-button", children: t("lms.check") })] }), result === "missing" && _jsx("p", { className: "lms-error", role: "status", children: t("lms.noCertificate") }), result === "error" && _jsx("p", { className: "lms-error", role: "status", children: t("lms.checkFailed") }), result && typeof result === "object" && (_jsxs("div", { className: "lms-card", role: "status", children: [_jsxs("p", { className: "lms-success", children: ["\u2713 ", t("lms.genuine")] }), _jsx("p", { children: result.issuedAt ? t("lms.certifiedOn", { name: result.studentName, course: result.course, date: formatDate(result.issuedAt, "long") }) : t("lms.certified", { name: result.studentName, course: result.course }) }), _jsx("p", { className: "lms-muted", children: t("lms.code", { code: result.code }) })] }))] }));
295
+ }
package/render.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { type SiteWords } from "tansy/react";
2
+ import type { SiteRecord, TemplateProps, ThemeQuery } from "tansy/theme";
3
+ import { type PlanOption } from "./parts";
4
+ import "./lms.css";
5
+ /**
6
+ * A course's lessons in reading order, grouped by section, with what this visitor may open and has
7
+ * finished. Titles come from the public outline. Links come from lessons read as the viewer, so a
8
+ * lesson they can't open has none.
9
+ */
10
+ export interface CourseOutline {
11
+ sections: Array<{
12
+ id: number | null;
13
+ title: string;
14
+ lessons: OutlineLesson[];
15
+ }>;
16
+ ordered: OutlineLesson[];
17
+ enrolled: boolean;
18
+ done: number;
19
+ }
20
+ export interface OutlineLesson {
21
+ id: number;
22
+ title: string;
23
+ href: string | null;
24
+ preview: boolean;
25
+ done: boolean;
26
+ minutes: number | null;
27
+ }
28
+ /**
29
+ * Builds the outline from a page's `data`: `outline`, `sections`, `lessons`, `progress` and `enrollment`, as this plugin's queries name them.
30
+ * Pass the template's `words` so lesson links stay in the page's language.
31
+ */
32
+ export declare function courseOutline(data: TemplateProps["data"], words?: SiteWords): CourseOutline;
33
+ /** The outline as a list, with finished lessons ticked and the current one marked. */
34
+ export declare function Outline({ outline, current, words }: {
35
+ outline: CourseOutline;
36
+ current?: number;
37
+ words?: SiteWords;
38
+ }): import("react").JSX.Element;
39
+ /** A plan record from the Payments plugin, as the LMS's parts take it. */
40
+ export declare function planOption(plan: SiteRecord): PlanOption;
41
+ /** Cheapest first, and plans with no price shown last. */
42
+ export declare const sortPlans: (plans: PlanOption[]) => PlanOption[];
43
+ /** The price a plan shows, such as "$19.00 a month", or null when it shows none. */
44
+ export declare function planPrice(plan: PlanOption, words: SiteWords | undefined, annual?: boolean): string | null;
45
+ /**
46
+ * Which published plans include a course, and whether the visitor's own plans already do, from
47
+ * a page's `plans`, `access` and `entitlements` lists, as this plugin's queries name them. Plans
48
+ * come from the Payments plugin as data. Without it the lists are empty, and so is this.
49
+ *
50
+ * A plan includes a course when one of its access opens every course (`lms-courses`), or is one
51
+ * the course is "Included in".
52
+ */
53
+ export declare function coursePlans(course: SiteRecord, data: TemplateProps["data"]): {
54
+ plans: PlanOption[];
55
+ covered: boolean;
56
+ };
57
+ /** Plans that include the course, each with its price and a Subscribe button. */
58
+ export declare function PlanOffers({ plans, heading, words }: {
59
+ plans: PlanOption[];
60
+ heading?: string;
61
+ words?: SiteWords;
62
+ }): import("react").JSX.Element | null;
63
+ /**
64
+ * Enroll, continue or completed, by what this visitor's enrollment says. Someone whose plan
65
+ * covers the course enrolls with one click. Anyone else is offered the plans that include it,
66
+ * beside buying it when it's sold.
67
+ */
68
+ export declare function CourseAction({ course, outline, data, words }: {
69
+ course: SiteRecord;
70
+ outline: CourseOutline;
71
+ data?: TemplateProps["data"];
72
+ words?: SiteWords;
73
+ }): import("react").JSX.Element | null;
74
+ /**
75
+ * Plans that may include a course, from the Payments plugin: published plans and access are public,
76
+ * for pricing pages, and each person reads only their own entitlements. Without Payments, empty lists.
77
+ */
78
+ export declare const PLAN_QUERIES: Record<string, ThemeQuery>;
79
+ export { Progress, SubscribedNotice, SubscribeToPlan, type PlanOption } from "./parts";
80
+ declare const _default: import("tansy/react").Renderers;
81
+ export default _default;