@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/render.js ADDED
@@ -0,0 +1,186 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { apiPath, defineRenderers, pickWords, RichText, sitePath, StreamField } from "tansy/react";
3
+ import { embedUrl, money, orderLessons, percentDone } from "./logic";
4
+ import { CertificateCheck, CourseOffer, EnrollButton, MarkComplete, MyCourses, Progress, Quiz, SubscribedNotice, SubscribeToPlan } from "./parts";
5
+ import { siteMessages } from "./site-messages";
6
+ import { lmsWords } from "./words";
7
+ import "./lms.css";
8
+ const text = (value) => (typeof value === "string" ? value : "");
9
+ const idOf = (value) => (typeof value === "number" ? value : null);
10
+ const items = (list) => list?.items ?? [];
11
+ const fileHref = (id, thumb) => apiPath(`/files/${encodeURIComponent(id)}${thumb ? `?thumb=${thumb}` : ""}`);
12
+ /** The LMS's words for a client part, and no one else's. */
13
+ const forParts = (words) => (words ? pickWords(words, "lms") : undefined);
14
+ /**
15
+ * Builds the outline from a page's `data`: `outline`, `sections`, `lessons`, `progress` and `enrollment`, as this plugin's queries name them.
16
+ * Pass the template's `words` so lesson links stay in the page's language.
17
+ */
18
+ export function courseOutline(data, words) {
19
+ const sections = items(data.sections);
20
+ const links = new Map(items(data.lessons).map((lesson) => [lesson.id, text(lesson.recordPath) ? sitePath(words, text(lesson.recordPath)) : null]));
21
+ const finished = new Set(items(data.progress).map((row) => idOf(row.lesson)));
22
+ const ordered = orderLessons(items(data.outline), sections).map((lesson) => ({
23
+ id: lesson.id,
24
+ title: text(lesson.title),
25
+ href: links.get(lesson.id) ?? null,
26
+ preview: lesson.preview === true,
27
+ done: finished.has(lesson.id),
28
+ minutes: typeof lesson.durationMinutes === "number" ? lesson.durationMinutes : null,
29
+ section: idOf(lesson.section),
30
+ }));
31
+ const groups = [];
32
+ for (const lesson of ordered) {
33
+ const section = sections.find((candidate) => candidate.id === lesson.section);
34
+ const last = groups.at(-1);
35
+ if (last && last.id === (section?.id ?? null))
36
+ last.lessons.push(lesson);
37
+ else
38
+ groups.push({ id: section?.id ?? null, title: text(section?.title), lessons: [lesson] });
39
+ }
40
+ return { sections: groups, ordered, enrolled: items(data.enrollment).length > 0, done: ordered.filter((lesson) => lesson.done).length };
41
+ }
42
+ /** The outline as a list, with finished lessons ticked and the current one marked. */
43
+ export function Outline({ outline, current, words }) {
44
+ const { t } = lmsWords(words);
45
+ if (!outline.ordered.length)
46
+ return _jsx("p", { className: "lms-muted", children: t("lms.noLessons") });
47
+ return (_jsx("nav", { className: "lms-outline", "aria-label": t("lms.outline"), children: outline.sections.map((section, index) => (_jsxs("section", { children: [section.title && _jsx("h3", { children: section.title }), _jsx("ol", { children: section.lessons.map((lesson) => (_jsxs("li", { className: lesson.done ? "lms-done" : undefined, "aria-current": lesson.id === current ? "page" : undefined, children: [_jsx("span", { className: "lms-tick", "aria-hidden": true, children: lesson.done ? "✓" : lesson.href ? "○" : "🔒" }), lesson.href ? _jsx("a", { href: lesson.href, children: lesson.title }) : _jsx("span", { children: lesson.title }), lesson.preview && !outline.enrolled && _jsx("span", { className: "lms-badge", children: t("lms.preview") }), lesson.done && _jsxs("span", { className: "sr-only", children: [" ", t("lms.completedMark")] }), lesson.minutes !== null && _jsxs("span", { className: "lms-muted", children: [" \u00B7 ", t("lms.minutes", { count: lesson.minutes })] })] }, lesson.id))) })] }, section.id ?? `loose-${index}`))) }));
48
+ }
49
+ const ids = (value) => (Array.isArray(value) ? value : [value]).filter((id) => typeof id === "number");
50
+ const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
51
+ /** A plan record from the Payments plugin, as the LMS's parts take it. */
52
+ export function planOption(plan) {
53
+ return {
54
+ name: text(plan.name),
55
+ title: text(plan.title) || text(plan.name),
56
+ amount: num(plan.amount),
57
+ annualAmount: num(plan.annualAmount),
58
+ currency: text(plan.currency) || null,
59
+ featured: plan.featured === true,
60
+ };
61
+ }
62
+ /** Cheapest first, and plans with no price shown last. */
63
+ export const sortPlans = (plans) => [...plans].sort((a, b) => (a.amount ?? Number.MAX_VALUE) - (b.amount ?? Number.MAX_VALUE));
64
+ /** The price a plan shows, such as "$19.00 a month", or null when it shows none. */
65
+ export function planPrice(plan, words, annual = false) {
66
+ const amount = annual ? plan.annualAmount : plan.amount;
67
+ if (amount === null || !plan.currency)
68
+ return null;
69
+ return lmsWords(words).t(annual ? "lms.perYear" : "lms.perMonth", { price: money(amount, plan.currency, words?.locale ?? "en") });
70
+ }
71
+ /**
72
+ * Which published plans include a course, and whether the visitor's own plans already do, from
73
+ * a page's `plans`, `access` and `entitlements` lists, as this plugin's queries name them. Plans
74
+ * come from the Payments plugin as data. Without it the lists are empty, and so is this.
75
+ *
76
+ * A plan includes a course when one of its access opens every course (`lms-courses`), or is one
77
+ * the course is "Included in".
78
+ */
79
+ export function coursePlans(course, data) {
80
+ const whole = new Set(items(data.access).filter((access) => Array.isArray(access.collections) && access.collections.includes("lms-courses")).map((access) => access.id));
81
+ const own = new Set(ids(course.included));
82
+ const opening = new Set([...whole, ...own]);
83
+ const plans = sortPlans(items(data.plans).filter((plan) => ids(plan.includes).some((id) => opening.has(id))).map(planOption));
84
+ const mine = (items(data.entitlements)[0]?.access ?? []);
85
+ const covered = Array.isArray(mine) && (mine.includes("lms-courses") || mine.some((id) => typeof id === "number" && own.has(id)));
86
+ return { plans, covered };
87
+ }
88
+ /** Plans that include the course, each with its price and a Subscribe button. */
89
+ export function PlanOffers({ plans, heading, words }) {
90
+ if (!plans.length)
91
+ return null;
92
+ return (_jsxs("div", { className: "lms-plans", children: [heading && _jsx("p", { className: "lms-muted", children: heading }), _jsx("ul", { children: plans.map((plan) => (_jsxs("li", { children: [_jsx("strong", { children: plan.title }), planPrice(plan, words) && _jsxs("span", { className: "lms-muted", children: [" \u00B7 ", planPrice(plan, words)] }), _jsx(SubscribeToPlan, { plan: plan, words: forParts(words) })] }, plan.name))) })] }));
93
+ }
94
+ /**
95
+ * Enroll, continue or completed, by what this visitor's enrollment says. Someone whose plan
96
+ * covers the course enrolls with one click. Anyone else is offered the plans that include it,
97
+ * beside buying it when it's sold.
98
+ */
99
+ export function CourseAction({ course, outline, data, words }) {
100
+ const { t } = lmsWords(words);
101
+ const next = outline.ordered.find((lesson) => !lesson.done && lesson.href) ?? null;
102
+ if (outline.enrolled) {
103
+ if (outline.ordered.length && outline.done === outline.ordered.length)
104
+ return _jsx("p", { className: "lms-success", children: t("lms.courseCompleted") });
105
+ return next ? _jsx("p", { children: _jsx("a", { className: "lms-button", href: next.href, children: t(outline.done ? "lms.continue" : "lms.start", { title: next.title }) }) }) : null;
106
+ }
107
+ if (course.access === "free")
108
+ return _jsx(EnrollButton, { courseId: course.id, continueHref: null, words: forParts(words) });
109
+ const { plans, covered } = data ? coursePlans(course, data) : { plans: [], covered: false };
110
+ if (covered)
111
+ return _jsx(EnrollButton, { courseId: course.id, continueHref: null, label: t("lms.startWithPlan"), words: forParts(words) });
112
+ return (_jsxs(_Fragment, { children: [_jsx(SubscribedNotice, { words: forParts(words) }), course.access === "paid" && _jsx(CourseOffer, { courseId: course.id, words: forParts(words) }), course.access !== "paid" && !plans.length && _jsx("p", { className: "lms-muted", children: t("lms.staffEnroll") }), _jsx(PlanOffers, { plans: plans, heading: course.access === "paid" ? t("lms.orPlan") : t("lms.withPlan"), words: words })] }));
113
+ }
114
+ const LEVELS = new Set(["beginner", "intermediate", "advanced"]);
115
+ function Course({ record, data, stream, fileUrl, fileText, t, words }) {
116
+ if (!record)
117
+ return null;
118
+ const outline = courseOutline(data, words);
119
+ const level = text(record.level);
120
+ return (_jsxs("main", { className: "lms-main", children: [_jsxs("header", { className: "lms-hero", children: [level && _jsx("p", { className: "lms-kicker", children: LEVELS.has(level) ? t(`lms.levels.${level}`) : level }), _jsx("h1", { children: text(record.title) }), text(record.summary) && _jsx("p", { className: "lms-lead", children: text(record.summary) }), text(record.byline) && _jsx("p", { className: "lms-muted", children: t("lms.taughtBy", { name: text(record.byline) }) }), outline.enrolled && outline.ordered.length > 0 && _jsx(Progress, { percent: percentDone(outline.done, outline.ordered.length), label: t("lms.lessonsDone", { done: outline.done, total: outline.ordered.length }), name: t("lms.progress") }), _jsx(CourseAction, { course: record, outline: outline, data: data, words: words })] }), text(record.cover) && _jsx("img", { className: "lms-cover", src: fileUrl(text(record.cover), "800x0"), alt: fileText(text(record.cover)).alt }), Array.isArray(record.description) && record.description.length > 0 && _jsx("div", { className: "lms-body", children: _jsx(StreamField, { blocks: record.description, ...stream }) }), _jsx("h2", { children: t("lms.outline") }), _jsx(Outline, { outline: outline, words: words })] }));
121
+ }
122
+ function Lesson({ record, data, stream, t, words }) {
123
+ if (!record)
124
+ return null;
125
+ const outline = courseOutline(data, words);
126
+ const course = items(data.course)[0];
127
+ const index = outline.ordered.findIndex((lesson) => lesson.id === record.id);
128
+ const previous = index > 0 ? outline.ordered[index - 1] : null;
129
+ const next = index >= 0 ? outline.ordered.slice(index + 1).find((lesson) => lesson.href) ?? null : null;
130
+ return (_jsxs("div", { className: "lms-classroom", children: [_jsxs("aside", { className: "lms-sidebar", children: [course && _jsx("p", { className: "lms-kicker", children: text(course.recordPath) ? _jsx("a", { href: sitePath(words, text(course.recordPath)), children: text(course.title) }) : text(course.title) }), outline.enrolled && _jsx(Progress, { percent: percentDone(outline.done, outline.ordered.length), label: t("lms.done", { done: outline.done, total: outline.ordered.length }), name: t("lms.progress") }), _jsx(Outline, { outline: outline, current: record.id, words: words })] }), _jsxs("main", { className: "lms-main lms-lesson", children: [_jsx("h1", { children: text(record.title) }), _jsx("div", { className: "lms-body", children: _jsx(StreamField, { blocks: record.content, ...stream }) }), outline.enrolled
131
+ ? _jsx(MarkComplete, { lessonId: record.id, done: outline.ordered[index]?.done ?? false, nextHref: next?.href ?? null, words: forParts(words) })
132
+ : course && _jsxs("p", { className: "lms-muted", children: [t("lms.previewNotice"), " ", _jsx("a", { href: text(course.recordPath) ? sitePath(words, text(course.recordPath)) : "#", children: t("lms.enrollToTrack") })] }), _jsxs("nav", { className: "lms-pager", "aria-label": t("lms.lessons"), children: [previous?.href ? _jsxs("a", { href: previous.href, rel: "prev", children: ["\u2190 ", previous.title] }) : _jsx("span", {}), next?.href && _jsxs("a", { href: next.href, rel: "next", children: [next.title, " \u2192"] })] })] })] }));
133
+ }
134
+ function SingletonPage({ record, children }) {
135
+ return (_jsxs("main", { className: "lms-main", children: [_jsx("h1", { children: text(record?.title) }), record?.intro !== undefined && record?.intro !== null && _jsx("div", { className: "lms-body", children: _jsx(RichText, { doc: record.intro }) }), children] }));
136
+ }
137
+ const MyCoursesPage = ({ record, words }) => _jsx(SingletonPage, { record: record, children: _jsx(MyCourses, { words: forParts(words) }) });
138
+ const CertificatePage = ({ record, words }) => _jsx(SingletonPage, { record: record, children: _jsx(CertificateCheck, { words: forParts(words) }) });
139
+ const TextBlock = ({ value }) => _jsx(RichText, { doc: value.body });
140
+ function Video({ value, words }) {
141
+ const { t } = lmsWords(words);
142
+ const file = text(value.file);
143
+ const src = embedUrl(text(value.url));
144
+ const title = text(value.title) || t("lms.video");
145
+ return (_jsxs("figure", { className: "lms-figure", children: [file
146
+ ? _jsx("video", { className: "lms-video", src: fileHref(file), controls: true, preload: "metadata", title: title })
147
+ : src && _jsx("div", { className: "lms-embed", children: _jsx("iframe", { src: src, title: title, loading: "lazy", allow: "encrypted-media; picture-in-picture; fullscreen", referrerPolicy: "strict-origin-when-cross-origin", sandbox: "allow-scripts allow-same-origin allow-presentation" }) }), value.transcript !== undefined && value.transcript !== null && _jsxs("details", { children: [_jsx("summary", { children: t("lms.transcript") }), _jsx(RichText, { doc: value.transcript })] })] }));
148
+ }
149
+ function Download({ value, words }) {
150
+ const file = text(value.file);
151
+ if (!file)
152
+ return null;
153
+ return _jsx("p", { className: "lms-download", children: _jsx("a", { href: fileHref(file), download: true, children: text(value.label) || lmsWords(words).t("lms.download") }) });
154
+ }
155
+ function QuizBlock({ value, words }) {
156
+ const quiz = idOf(value.quiz);
157
+ return quiz === null ? null : _jsx(Quiz, { quizId: quiz, words: forParts(words) });
158
+ }
159
+ /** Lessons and the learner's own records are read as the viewer, so rules decide what each person gets. */
160
+ const viewer = (query) => ({ ...query, viewer: true });
161
+ const outlineFor = (course) => ({
162
+ outline: { collection: "lms-outline", filter: `course = ${course}`, perPage: 200 },
163
+ sections: { collection: "lms-sections", filter: `course = ${course}`, perPage: 200, fields: "id,title,position" },
164
+ lessons: viewer({ collection: "lms-lessons", filter: `course = ${course}`, perPage: 200, fields: "id", urls: "1" }),
165
+ progress: viewer({ collection: "lms-progress", filter: `course = ${course}`, perPage: 200, fields: "lesson" }),
166
+ enrollment: viewer({ collection: "lms-enrollments", filter: `course = ${course} && state != "revoked" && state != "lapsed"`, perPage: 1, fields: "id,state" }),
167
+ });
168
+ /**
169
+ * Plans that may include a course, from the Payments plugin: published plans and access are public,
170
+ * for pricing pages, and each person reads only their own entitlements. Without Payments, empty lists.
171
+ */
172
+ export const PLAN_QUERIES = {
173
+ plans: { collection: "payments-plans", filter: 'status = "published"', perPage: 50, fields: "id,name,title,description,amount,annualAmount,currency,featured,includes" },
174
+ access: { collection: "payments-access", filter: 'status = "published"', perPage: 200, fields: "id,name,description,collections" },
175
+ entitlements: viewer({ collection: "payments-entitlements", perPage: 1, fields: "access" }),
176
+ };
177
+ export { Progress, SubscribedNotice, SubscribeToPlan } from "./parts";
178
+ export default defineRenderers({
179
+ messages: siteMessages,
180
+ blocks: { lms_text: TextBlock, lms_video: Video, lms_download: Download, lms_quiz: QuizBlock },
181
+ templates: { "lms-courses": Course, "lms-lessons": Lesson, "lms-my-courses": MyCoursesPage, "lms-certificate": CertificatePage },
182
+ queries: {
183
+ "lms-courses": { ...outlineFor("@record.id"), ...PLAN_QUERIES },
184
+ "lms-lessons": { ...outlineFor("@record.course"), course: { collection: "lms-courses", filter: "id = @record.course", perPage: 1, fields: "id,title", urls: "1" } },
185
+ },
186
+ });