@clarusjs/theme-docs 0.0.1 → 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/LICENSE +21 -0
- package/README.md +23 -1
- package/package.json +49 -5
- package/src/callout.tscl +19 -0
- package/src/copy.tscl +21 -0
- package/src/layout.tscl +122 -0
- package/src/learn-progress.tscl +7 -0
- package/src/learn-status.tscl +40 -0
- package/src/lesson-bar.tscl +126 -0
- package/src/lesson.css +72 -0
- package/src/lesson.tscl +43 -0
- package/src/nav.ts +137 -0
- package/src/page-head.tscl +14 -0
- package/src/pages.d.ts +6 -0
- package/src/progress-board.tscl +64 -0
- package/src/progress.ts +93 -0
- package/src/quiz-choices.tscl +44 -0
- package/src/quiz.tscl +16 -0
- package/src/search.d.ts +25 -0
- package/src/search.js +53 -0
- package/src/search.tscl +75 -0
- package/src/theme-toggle.tscl +23 -0
- package/src/theme.css +340 -0
- package/src/vite.d.ts +47 -0
- package/src/vite.js +203 -0
package/src/nav.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// The theme's settings and the navigation helpers the layout uses. Server-only: the layout is static HTML.
|
|
2
|
+
|
|
3
|
+
/** A sidebar entry; `order` sorts it within its group (lowest first, then by title). */
|
|
4
|
+
export type Item = { title: string; href: string; order?: number }
|
|
5
|
+
export type Group = { title: string; items: Item[] }
|
|
6
|
+
/** A top-level part of the docs (Guide, Reference): its own sidebar groups. */
|
|
7
|
+
export type Section = { key: string; title: string; href: string; groups: Group[] }
|
|
8
|
+
export type Social = { label: string; href: string; icon: 'github' | 'npm' | 'link' }
|
|
9
|
+
/** A heading on the page, for "On this page". */
|
|
10
|
+
export type Heading = { id: string; text: string; level: number }
|
|
11
|
+
|
|
12
|
+
export type ThemeConfig = {
|
|
13
|
+
/** The site's name in the header: `{ text: 'clarus', accent: '.js' }` shows the accent in the brand colour. */
|
|
14
|
+
brand: { text: string; accent?: string; logo?: string }
|
|
15
|
+
/** The site's public address, for structured data (no trailing slash). */
|
|
16
|
+
siteUrl?: string
|
|
17
|
+
sections: Section[]
|
|
18
|
+
/** Icon links at the right of the header (GitHub, npm…). */
|
|
19
|
+
social?: Social[]
|
|
20
|
+
/**
|
|
21
|
+
* "Edit this page": a pattern where `:file` is the page's source file under src/pages (`guide/start.md`, found in
|
|
22
|
+
* `pages`), or a function of the route (the page's source route, for dynamic pages). None without it.
|
|
23
|
+
*/
|
|
24
|
+
editLink?: string | ((path: string) => string)
|
|
25
|
+
/** The pages as themeDocs() reads them: source files for `editLink` patterns, and "Last updated" dates. */
|
|
26
|
+
pages?: PageInfo[]
|
|
27
|
+
/**
|
|
28
|
+
* Learn: the section whose pages are lessons, and its progress page (not a lesson). Progress, XP and badges are
|
|
29
|
+
* kept in the browser (localStorage); an XP chip shows in lesson headers and on the section's pages.
|
|
30
|
+
*/
|
|
31
|
+
learn?: { section: string; progress: string }
|
|
32
|
+
/** A search button (and Ctrl/⌘K, /) in the header; the index comes from the themeDocs() Vite plugin. */
|
|
33
|
+
search?: boolean
|
|
34
|
+
/** The site footer's text. */
|
|
35
|
+
footer?: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const none: Item = { title: '', href: '' }
|
|
39
|
+
const flat = (section: Section) => section.groups.flatMap((g) => g.items)
|
|
40
|
+
|
|
41
|
+
/** The section a page belongs to ('' for pages outside every section, like a home page). */
|
|
42
|
+
export function sectionKey(sections: Section[], path: string): string {
|
|
43
|
+
return sections.find((s) => flat(s).some((i) => i.href === path))?.key ?? ''
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Sidebar groups for the page's section (none outside the sections). */
|
|
47
|
+
export function groupsOf(sections: Section[], path: string): Group[] {
|
|
48
|
+
return sections.find((s) => s.key === sectionKey(sections, path))?.groups ?? []
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** "Guide › Templates" */
|
|
52
|
+
export function crumb(sections: Section[], path: string): string {
|
|
53
|
+
const section = sections.find((s) => s.key === sectionKey(sections, path))
|
|
54
|
+
const group = section?.groups.find((g) => g.items.some((i) => i.href === path))
|
|
55
|
+
return section && group ? `${section.title} › ${group.title}` : ''
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Previous and next pages in sidebar order; an empty item (href '') when there is none. */
|
|
59
|
+
export function pager(sections: Section[], path: string): { prev: Item; next: Item } {
|
|
60
|
+
const section = sections.find((s) => s.key === sectionKey(sections, path))
|
|
61
|
+
const items = section ? flat(section) : []
|
|
62
|
+
const i = items.findIndex((item) => item.href === path)
|
|
63
|
+
return { prev: items[i - 1] ?? none, next: items[i + 1] ?? none }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* A page as `themeDocs()` reads it (`import pages from 'virtual:theme-docs/pages'`): its route, source file under
|
|
68
|
+
* src/pages, last commit time (unix seconds), sidebar entry, and `hidden` when it isn't in the sidebar.
|
|
69
|
+
*/
|
|
70
|
+
export type PageInfo = { href: string; title: string; file: string; group?: string; order?: number; updated?: number; hidden?: boolean }
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The sections with their sidebar filled from the pages under `/<section key>/`: a page sits in its `group` (else the
|
|
74
|
+
* section's title), sorted by `order`, then title. The config wins: its groups come first and its items replace pages
|
|
75
|
+
* with the same href, so it can rename, reorder and add (non-page) entries. An empty section `href` means its first page.
|
|
76
|
+
*/
|
|
77
|
+
export function pagesNav(sections: Section[], pages: PageInfo[]): Section[] {
|
|
78
|
+
return sections.map((section) => {
|
|
79
|
+
const groups = section.groups.map((g) => ({ title: g.title, items: [...g.items] }))
|
|
80
|
+
const listed = new Set(groups.flatMap((g) => g.items.map((i) => i.href)))
|
|
81
|
+
for (const page of pages) {
|
|
82
|
+
const inSection = page.href === `/${section.key}` || page.href.startsWith(`/${section.key}/`)
|
|
83
|
+
if (page.hidden || !inSection || listed.has(page.href)) continue
|
|
84
|
+
const title = page.group ?? section.title
|
|
85
|
+
let group = groups.find((g) => g.title === title)
|
|
86
|
+
if (!group) groups.push(group = { title, items: [] })
|
|
87
|
+
group.items.push(page.order === undefined ? { title: page.title, href: page.href } : { title: page.title, href: page.href, order: page.order })
|
|
88
|
+
}
|
|
89
|
+
const rank = (i: Item) => i.order ?? Infinity
|
|
90
|
+
for (const g of groups) g.items.sort((a, b) => rank(a) - rank(b) || a.title.localeCompare(b.title))
|
|
91
|
+
// New groups (after the config's) in the order of their first item.
|
|
92
|
+
const added = groups.slice(section.groups.length).sort((a, b) => rank(a.items[0]!) - rank(b.items[0]!))
|
|
93
|
+
const all = [...groups.slice(0, section.groups.length), ...added]
|
|
94
|
+
return { ...section, href: section.href || all.find((g) => g.items.length)?.items[0]?.href || '', groups: all }
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** "Edit this page" for a route (its source route, for dynamic pages): '' when there is none. */
|
|
99
|
+
export function editHref(config: ThemeConfig, route: string): string {
|
|
100
|
+
if (typeof config.editLink === 'function') return config.editLink(route)
|
|
101
|
+
const file = config.pages?.find((p) => p.href === route)?.file
|
|
102
|
+
return config.editLink && file ? config.editLink.replace(':file', file) : ''
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** When the page last changed (its source route, for dynamic pages): `{ iso, text }`, or undefined without a date. */
|
|
106
|
+
export function updatedOf(config: ThemeConfig, route: string): { iso: string; text: string } | undefined {
|
|
107
|
+
const seconds = config.pages?.find((p) => p.href === route)?.updated
|
|
108
|
+
if (seconds === undefined) return undefined
|
|
109
|
+
const date = new Date(seconds * 1000)
|
|
110
|
+
return { iso: date.toISOString(), text: date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' }) }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The lessons of the Learn section, in order (its items but the progress page). */
|
|
114
|
+
export function lessonsOf(config: ThemeConfig): Item[] {
|
|
115
|
+
const section = config.sections.find((s) => s.key === config.learn?.section)
|
|
116
|
+
return section ? flat(section).filter((i) => i.href !== config.learn?.progress) : []
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A lesson's place in its section (the config section that lists it; with `learn`, its lessons): where "leave" goes
|
|
121
|
+
* (the section's href), the previous and next lessons, and "Learn · Lesson 2 of 6". total 0 outside every section.
|
|
122
|
+
*/
|
|
123
|
+
export function lessonOf(config: ThemeConfig, path: string): { leave: string; prev: string; next: string; label: string; total: number } {
|
|
124
|
+
const section = config.sections.find((s) => s.key === sectionKey(config.sections, path))
|
|
125
|
+
const items = section ? (section.key === config.learn?.section ? lessonsOf(config) : flat(section)) : []
|
|
126
|
+
const i = items.findIndex((item) => item.href === path)
|
|
127
|
+
return {
|
|
128
|
+
// Learn lessons lead back to the progress page; other lessons to their section's own page, unless that is one
|
|
129
|
+
// of its lessons (leaving would open a lesson): then home.
|
|
130
|
+
leave: section && section.key === config.learn?.section ? config.learn.progress || '/'
|
|
131
|
+
: section?.href && !items.some((item) => item.href === section.href) ? section.href : '/',
|
|
132
|
+
prev: items[i - 1]?.href ?? '',
|
|
133
|
+
next: items[i + 1]?.href ?? '',
|
|
134
|
+
label: section ? `${section.title} · Lesson ${i + 1} of ${items.length}` : '',
|
|
135
|
+
total: items.length,
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{{-- The <head> of every theme page: the saved theme before the first paint, the title and description, JSON-LD. --}}
|
|
2
|
+
@import type { ThemeConfig } from './nav.ts'
|
|
3
|
+
@input config: ThemeConfig
|
|
4
|
+
@input title: string
|
|
5
|
+
@input description: string = ''
|
|
6
|
+
@input url: string = '/'
|
|
7
|
+
|
|
8
|
+
{{-- Runs before the first paint: the saved theme is on <html> before anything shows (no flash). --}}
|
|
9
|
+
<script inline>try{var t=localStorage.getItem('clarusjs-theme');if(t==='light'||t==='dark')document.documentElement.setAttribute('data-theme',t)}catch(e){}</script>
|
|
10
|
+
<meta charset="utf-8">
|
|
11
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
12
|
+
@if (description) {<meta name="description" content="{{ description }}">}
|
|
13
|
+
<title>{{ title }}</title>
|
|
14
|
+
@if (config.siteUrl) {<script type="application/ld+json">{{ { '@context': 'https://schema.org', '@type': 'TechArticle', headline: title, description, url: `${config.siteUrl}${url === '/' ? '' : url}` } }}</script>}
|
package/src/pages.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The pages themeDocs() reads, for the sidebar. Reference it from a .d.ts in your project:
|
|
2
|
+
// /// <reference types="@clarusjs/theme-docs/pages.d.ts" />
|
|
3
|
+
declare module 'virtual:theme-docs/pages' {
|
|
4
|
+
const pages: import('./nav.ts').PageInfo[]
|
|
5
|
+
export default pages
|
|
6
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{{--
|
|
2
|
+
Your progress, read from this browser: XP, lessons done, quiz accuracy, badges and each lesson's state, with Reset.
|
|
3
|
+
Without JavaScript (or with storage blocked) it says so; the lessons are still links.
|
|
4
|
+
--}}
|
|
5
|
+
@input lessons: { title: string; href: string }[]
|
|
6
|
+
|
|
7
|
+
<script>
|
|
8
|
+
import { load, reset, save, stats } from './progress.ts'
|
|
9
|
+
let xp = state(0)
|
|
10
|
+
let done = state(0)
|
|
11
|
+
let accuracy = state('')
|
|
12
|
+
let badges = state([])
|
|
13
|
+
let statuses = state({})
|
|
14
|
+
let mode = state('waiting')
|
|
15
|
+
let confirming = state(false)
|
|
16
|
+
function refresh() {
|
|
17
|
+
const s = stats(load(), lessons.map((l) => l.href))
|
|
18
|
+
xp = s.xp
|
|
19
|
+
done = s.done
|
|
20
|
+
accuracy = s.answered ? Math.round((s.right / s.answered) * 100) + '% (' + s.right + ' of ' + s.answered + ')' : 'no quizzes answered yet'
|
|
21
|
+
badges = s.badges
|
|
22
|
+
statuses = Object.fromEntries(lessons.map((l) => [l.href, s.status(l.href)]))
|
|
23
|
+
}
|
|
24
|
+
function wipe() {
|
|
25
|
+
if (!confirming) { confirming = true; return }
|
|
26
|
+
reset()
|
|
27
|
+
confirming = false
|
|
28
|
+
refresh()
|
|
29
|
+
window.dispatchEvent(new Event('learn:progress'))
|
|
30
|
+
}
|
|
31
|
+
if (typeof document !== 'undefined') {
|
|
32
|
+
// Saving what is there tells us whether this browser keeps it.
|
|
33
|
+
mode = save(load()) ? 'saved' : 'blocked'
|
|
34
|
+
refresh()
|
|
35
|
+
}
|
|
36
|
+
</script>
|
|
37
|
+
|
|
38
|
+
<div class="progress-board">
|
|
39
|
+
@if (mode === 'waiting') {
|
|
40
|
+
<p class="progress-note">Your progress is kept in this browser and shows here with JavaScript on.</p>
|
|
41
|
+
} @else {
|
|
42
|
+
@if (mode === 'blocked') {<p class="progress-note">This browser isn't keeping your progress (storage is blocked), so it lasts until you leave the page.</p>}
|
|
43
|
+
<dl class="progress-stats">
|
|
44
|
+
<div><dt>XP</dt><dd>{{ xp }}</dd></div>
|
|
45
|
+
<div><dt>Lessons</dt><dd>{{ done }} of {{ lessons.length }}</dd></div>
|
|
46
|
+
<div><dt>Quizzes right</dt><dd>{{ accuracy }}</dd></div>
|
|
47
|
+
</dl>
|
|
48
|
+
<h2>Badges</h2>
|
|
49
|
+
<ul class="badges">
|
|
50
|
+
@for (badge of badges; track badge.id) {
|
|
51
|
+
<li [class]="badge.earned ? 'earned' : false"><strong>{{ badge.title }}</strong> <span>{{ badge.text }}</span> <em>{{ badge.earned ? 'Earned' : 'Not yet' }}</em></li>
|
|
52
|
+
}
|
|
53
|
+
</ul>
|
|
54
|
+
}
|
|
55
|
+
<h2>Lessons</h2>
|
|
56
|
+
<ol class="progress-lessons">
|
|
57
|
+
@for (lesson of lessons; track lesson.href) {
|
|
58
|
+
<li [data-status]="statuses[lesson.href] ?? false"><a [href]="lesson.href">{{ lesson.title }}</a>@if (statuses[lesson.href]) { <span class="status-note">({{ statuses[lesson.href] === 'current' ? 'up next' : statuses[lesson.href] === 'done' ? 'done' : 'not started' }})</span>}</li>
|
|
59
|
+
}
|
|
60
|
+
</ol>
|
|
61
|
+
@if (mode !== 'waiting') {
|
|
62
|
+
<button type="button" class="progress-reset" (click)="wipe()">{{ confirming ? 'Click again to erase your progress' : 'Reset progress' }}</button>
|
|
63
|
+
}
|
|
64
|
+
</div>
|
package/src/progress.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Learning progress: steps seen, lessons finished and first answers to quizzes, in one versioned localStorage key.
|
|
2
|
+
// Nothing leaves the browser. XP and badges are computed from it, never stored. Used by the Learn islands.
|
|
3
|
+
|
|
4
|
+
export type Progress = {
|
|
5
|
+
v: 1
|
|
6
|
+
/** Step ids done, by lesson path. */
|
|
7
|
+
steps: Record<string, string[]>
|
|
8
|
+
/** Lesson paths finished. */
|
|
9
|
+
done: string[]
|
|
10
|
+
/** First answer to each quiz (`<lesson>#<quiz name>`): right or not. */
|
|
11
|
+
quizzes: Record<string, boolean>
|
|
12
|
+
}
|
|
13
|
+
type Storage = Pick<globalThis.Storage, 'getItem' | 'setItem' | 'removeItem'>
|
|
14
|
+
|
|
15
|
+
export const KEY = 'clarusjs-learn'
|
|
16
|
+
export const empty = (): Progress => ({ v: 1, steps: {}, done: [], quizzes: {} })
|
|
17
|
+
|
|
18
|
+
// Storage is looked up inside try: a blocked localStorage throws as soon as it is read.
|
|
19
|
+
const local = (): Storage => globalThis.localStorage
|
|
20
|
+
|
|
21
|
+
/** The saved progress; a fresh start when there is none, it is from another version, or storage is blocked. */
|
|
22
|
+
export function load(storage?: Storage): Progress {
|
|
23
|
+
try {
|
|
24
|
+
const saved = JSON.parse((storage ?? local()).getItem(KEY) ?? 'null') as Progress | null
|
|
25
|
+
return saved?.v === 1 && Array.isArray(saved.done) ? saved : empty()
|
|
26
|
+
} catch {
|
|
27
|
+
return empty()
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Saves it; false when storage is blocked (progress then lasts as long as the page). */
|
|
32
|
+
export function save(progress: Progress, storage?: Storage): boolean {
|
|
33
|
+
try {
|
|
34
|
+
(storage ?? local()).setItem(KEY, JSON.stringify(progress))
|
|
35
|
+
return true
|
|
36
|
+
} catch {
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function reset(storage?: Storage): void {
|
|
42
|
+
try { (storage ?? local()).removeItem(KEY) } catch {}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function step(p: Progress, lesson: string, id: string): Progress {
|
|
46
|
+
const seen = p.steps[lesson] ?? []
|
|
47
|
+
return seen.includes(id) ? p : { ...p, steps: { ...p.steps, [lesson]: [...seen, id] } }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function finish(p: Progress, lesson: string): Progress {
|
|
51
|
+
return p.done.includes(lesson) ? p : { ...p, done: [...p.done, lesson] }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Only the first answer counts. */
|
|
55
|
+
export function answer(p: Progress, quiz: string, right: boolean): Progress {
|
|
56
|
+
return quiz in p.quizzes ? p : { ...p, quizzes: { ...p.quizzes, [quiz]: right } }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type Badge = { id: string; title: string; text: string; earned: boolean }
|
|
60
|
+
export type Stats = {
|
|
61
|
+
xp: number
|
|
62
|
+
done: number
|
|
63
|
+
total: number
|
|
64
|
+
right: number
|
|
65
|
+
answered: number
|
|
66
|
+
badges: Badge[]
|
|
67
|
+
/** A lesson's state in the path: done, current (the first not done) or locked (after it). */
|
|
68
|
+
status(lesson: string): 'done' | 'current' | 'locked'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** XP (10 a step, 50 a lesson, 20 a quiz right the first time), counts and badges, for the lessons of a path. */
|
|
72
|
+
export function stats(p: Progress, lessons: string[]): Stats {
|
|
73
|
+
const done = lessons.filter((l) => p.done.includes(l)).length
|
|
74
|
+
const steps = lessons.reduce((n, l) => n + (p.steps[l]?.length ?? 0), 0)
|
|
75
|
+
const answers = Object.values(p.quizzes)
|
|
76
|
+
const right = answers.filter(Boolean).length
|
|
77
|
+
const current = lessons.find((l) => !p.done.includes(l))
|
|
78
|
+
const badges: Badge[] = [
|
|
79
|
+
{ id: 'first-lesson', title: 'First lesson', text: 'Finish a lesson.', earned: done >= 1 },
|
|
80
|
+
{ id: 'halfway', title: 'Halfway', text: 'Finish half the lessons.', earned: lessons.length > 1 && done >= Math.ceil(lessons.length / 2) },
|
|
81
|
+
{ id: 'path', title: 'Path complete', text: 'Finish every lesson.', earned: lessons.length > 0 && done === lessons.length },
|
|
82
|
+
{ id: 'sharp', title: 'Sharp', text: 'Answer 5 quizzes right the first time.', earned: right >= 5 },
|
|
83
|
+
]
|
|
84
|
+
return {
|
|
85
|
+
xp: steps * 10 + done * 50 + right * 20,
|
|
86
|
+
done,
|
|
87
|
+
total: lessons.length,
|
|
88
|
+
right,
|
|
89
|
+
answered: answers.length,
|
|
90
|
+
badges,
|
|
91
|
+
status: (lesson) => (p.done.includes(lesson) ? 'done' : lesson === current ? 'current' : 'locked'),
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{{--
|
|
2
|
+
The interactive part of a quiz (quiz.tscl wraps it): the options, Check and the announcement. Once checked it opens
|
|
3
|
+
the quiz's answer and marks the options. In a lesson, the action bar's Check sends a quiz:check event to the quiz;
|
|
4
|
+
the result goes back as a bubbling quiz:result event ({ ok, done, text }), so the bar can turn green or red.
|
|
5
|
+
--}}
|
|
6
|
+
@input name: string
|
|
7
|
+
@input options: string[]
|
|
8
|
+
@input answer: number
|
|
9
|
+
|
|
10
|
+
<script>
|
|
11
|
+
let picked = state(-1)
|
|
12
|
+
let checked = state(false)
|
|
13
|
+
let status = state('')
|
|
14
|
+
const quiz = () => document.querySelector('[data-quiz="' + name + '"]')
|
|
15
|
+
function check() {
|
|
16
|
+
let detail
|
|
17
|
+
if (picked < 0) {
|
|
18
|
+
status = 'Pick an answer first.'
|
|
19
|
+
detail = { ok: false, done: false, text: status }
|
|
20
|
+
} else {
|
|
21
|
+
checked = true
|
|
22
|
+
const ok = picked === answer
|
|
23
|
+
status = ok ? 'Correct.' : 'Not quite. The answer is: ' + options[answer] + '.'
|
|
24
|
+
detail = { ok, done: true, text: ok ? 'Correct.' : 'The answer is: ' + options[answer] + '.' }
|
|
25
|
+
quiz()?.setAttribute('data-answered', ok ? 'right' : 'wrong')
|
|
26
|
+
const details = quiz()?.querySelector('.quiz-answer')
|
|
27
|
+
if (details) details.open = true
|
|
28
|
+
}
|
|
29
|
+
quiz()?.dispatchEvent(new CustomEvent('quiz:result', { bubbles: true, detail }))
|
|
30
|
+
}
|
|
31
|
+
if (typeof document !== 'undefined') {
|
|
32
|
+
document.addEventListener('quiz:check', (event) => { if (event.target === quiz() && !checked) check() })
|
|
33
|
+
}
|
|
34
|
+
</script>
|
|
35
|
+
|
|
36
|
+
<div class="quiz-choices">
|
|
37
|
+
<div class="quiz-options" role="radiogroup" [aria-labelledby]="name + '-q'">
|
|
38
|
+
@for (option of options; track $index) {
|
|
39
|
+
<label [class]="!checked ? false : $index === answer ? 'right' : $index === picked ? 'wrong' : false"><input type="radio" [name]="name" [value]="$index" [disabled]="checked" (change)="picked = $index"> {{ option }}@if (checked && $index === answer) {<span class="mark">✓ Right answer</span>} @else if (checked && $index === picked) {<span class="mark">✗ Your pick</span>}</label>
|
|
40
|
+
}
|
|
41
|
+
</div>
|
|
42
|
+
<button type="button" class="quiz-check" (click)="check()" [disabled]="checked">Check</button>
|
|
43
|
+
<p class="quiz-status" role="status">{{ status }}</p>
|
|
44
|
+
</div>
|
package/src/quiz.tscl
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{{--
|
|
2
|
+
A quiz (Markdown ::: quiz renders through it): the question, the options (an island: pick, Check, announced), and
|
|
3
|
+
the answer with its explanation (the content) in a <details>. Without JavaScript the options are radios and the
|
|
4
|
+
<details> shows the answer.
|
|
5
|
+
--}}
|
|
6
|
+
@import quizChoices from './quiz-choices.tscl'
|
|
7
|
+
@input name: string
|
|
8
|
+
@input question: string
|
|
9
|
+
@input options: string[]
|
|
10
|
+
@input answer: number
|
|
11
|
+
|
|
12
|
+
<div class="quiz" [data-quiz]="name">
|
|
13
|
+
<p class="quiz-question" [id]="name + '-q'">{{ question }}</p>
|
|
14
|
+
<quizChoices [name]="name" [options]="options" [answer]="answer" />
|
|
15
|
+
<details class="quiz-answer"><summary>Show the answer</summary><p class="quiz-correct">Answer: {{ options[answer] }}</p><slot /></details>
|
|
16
|
+
</div>
|
package/src/search.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type Section = {
|
|
2
|
+
u: string;
|
|
3
|
+
p: string;
|
|
4
|
+
h: string;
|
|
5
|
+
t: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* A search result: a page section (url with #heading, page title, heading, text).
|
|
9
|
+
* @typedef {{ u: string; p: string; h: string; t: string }} Section
|
|
10
|
+
*/
|
|
11
|
+
/** Sections per `s-<n>.json` file. */
|
|
12
|
+
export declare const CHUNK = 64;
|
|
13
|
+
/** @param {string} text @returns {string[]} lowercase words of two or more letters, accents folded */
|
|
14
|
+
export declare function tokens(text: string): string[];
|
|
15
|
+
/** @param {string} word */
|
|
16
|
+
export declare const termFile: (word: string) => string;
|
|
17
|
+
/**
|
|
18
|
+
* Sections matching every word of the query (the last one as a prefix, so results come while typing), best first:
|
|
19
|
+
* a word in a heading counts 10, each use in the text 1 (at most 3).
|
|
20
|
+
* @param {string} query
|
|
21
|
+
* @param {(file: string) => Promise<any>} load a file of the index, parsed
|
|
22
|
+
* @param {number} [limit]
|
|
23
|
+
* @returns {Promise<Section[]>}
|
|
24
|
+
*/
|
|
25
|
+
export declare function search(query: string, load: (file: string) => Promise<any>, limit?: number): Promise<Section[]>;
|
package/src/search.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Search, shared by the build (which writes the index) and the browser (which queries it). Plain JavaScript: the
|
|
2
|
+
// build side runs from vite.config. Types are the JSDoc here; search.d.ts is generated from it (pnpm types; typecheck and prepack run it).
|
|
3
|
+
//
|
|
4
|
+
// The index is many small JSON files, never one big one: `t-<xx>.json` maps the words starting with xx to
|
|
5
|
+
// [section, weight, section, weight…]; `s-<n>.json` holds sections n*64 to n*64+63 ({ u: url, p: page, h: heading,
|
|
6
|
+
// t: text }). A query loads one term file per word and the section files of its best results.
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A search result: a page section (url with #heading, page title, heading, text).
|
|
10
|
+
* @typedef {{ u: string; p: string; h: string; t: string }} Section
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Sections per `s-<n>.json` file. */
|
|
14
|
+
export const CHUNK = 64
|
|
15
|
+
|
|
16
|
+
/** @param {string} text @returns {string[]} lowercase words of two or more letters, accents folded */
|
|
17
|
+
export function tokens(text) {
|
|
18
|
+
return (text.normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase().match(/[a-z0-9]+/g) ?? []).filter((w) => w.length > 1)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param {string} word */
|
|
22
|
+
export const termFile = (word) => `t-${word.slice(0, 2)}.json`
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Sections matching every word of the query (the last one as a prefix, so results come while typing), best first:
|
|
26
|
+
* a word in a heading counts 10, each use in the text 1 (at most 3).
|
|
27
|
+
* @param {string} query
|
|
28
|
+
* @param {(file: string) => Promise<any>} load a file of the index, parsed
|
|
29
|
+
* @param {number} [limit]
|
|
30
|
+
* @returns {Promise<Section[]>}
|
|
31
|
+
*/
|
|
32
|
+
export async function search(query, load, limit = 10) {
|
|
33
|
+
const words = tokens(query)
|
|
34
|
+
if (!words.length) return []
|
|
35
|
+
const shards = await Promise.all(words.map((w) => load(termFile(w)).catch(() => ({}))))
|
|
36
|
+
/** @type {Map<number, number> | undefined} */
|
|
37
|
+
let scores
|
|
38
|
+
for (const [i, word] of words.entries()) {
|
|
39
|
+
const last = i === words.length - 1
|
|
40
|
+
/** @type {Map<number, number>} */
|
|
41
|
+
const found = new Map()
|
|
42
|
+
for (const [term, postings] of Object.entries(/** @type {Record<string, number[]>} */ (shards[i]))) {
|
|
43
|
+
if (term !== word && !(last && term.startsWith(word))) continue
|
|
44
|
+
for (let j = 0; j < postings.length; j += 2) found.set(postings[j], (found.get(postings[j]) ?? 0) + postings[j + 1])
|
|
45
|
+
}
|
|
46
|
+
scores = scores ? new Map([...scores].filter(([id]) => found.has(id)).map(([id, s]) => [id, s + /** @type {number} */ (found.get(id))])) : found
|
|
47
|
+
}
|
|
48
|
+
const best = [...(scores ?? [])].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([id]) => id)
|
|
49
|
+
/** @type {Map<number, Section[]>} */
|
|
50
|
+
const chunks = new Map()
|
|
51
|
+
await Promise.all([...new Set(best.map((id) => Math.floor(id / CHUNK)))].map(async (n) => chunks.set(n, await load(`s-${n}.json`))))
|
|
52
|
+
return best.map((id) => /** @type {Section[]} */ (chunks.get(Math.floor(id / CHUNK)))[id % CHUNK])
|
|
53
|
+
}
|
package/src/search.tscl
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
{{--
|
|
2
|
+
Search: a button in the header (and Ctrl/⌘K or /) opens a modal dialog. A native <dialog>: focus stays inside it,
|
|
3
|
+
Escape closes it and focus goes back. Arrow keys move through the results, Enter opens one. The index is the one
|
|
4
|
+
themeDocs() writes at build time; a query fetches only the files it needs.
|
|
5
|
+
--}}
|
|
6
|
+
<script>
|
|
7
|
+
import { search } from './search.js'
|
|
8
|
+
let query = state('')
|
|
9
|
+
let results = state([])
|
|
10
|
+
let active = state(0)
|
|
11
|
+
let searched = state(false)
|
|
12
|
+
const status = derived(() => !searched ? '' : results.length === 0 ? 'No results for "' + query + '"' : results.length === 1 ? '1 result' : results.length + ' results')
|
|
13
|
+
const base = import.meta.env?.BASE_URL ?? '/'
|
|
14
|
+
const load = (file) => fetch(base + 'search/' + file).then((r) => (r.ok ? r.json() : {}))
|
|
15
|
+
let latest = 0
|
|
16
|
+
async function run(value) {
|
|
17
|
+
query = value
|
|
18
|
+
const mine = ++latest
|
|
19
|
+
const found = value.trim() ? await search(value, load, 8) : []
|
|
20
|
+
if (mine !== latest) return // a newer query already answered
|
|
21
|
+
results = found
|
|
22
|
+
active = 0
|
|
23
|
+
searched = value.trim() !== ''
|
|
24
|
+
}
|
|
25
|
+
const dialog = () => document.querySelector('.search-dialog')
|
|
26
|
+
function open() {
|
|
27
|
+
const d = dialog()
|
|
28
|
+
if (!d || d.open) return
|
|
29
|
+
d.showModal()
|
|
30
|
+
d.querySelector('input').select()
|
|
31
|
+
}
|
|
32
|
+
function move(by) {
|
|
33
|
+
if (!results.length) return
|
|
34
|
+
active = (active + by + results.length) % results.length
|
|
35
|
+
document.getElementById('search-result-' + active)?.scrollIntoView({ block: 'nearest' })
|
|
36
|
+
}
|
|
37
|
+
function key(event) {
|
|
38
|
+
if (event.key === 'ArrowDown') { event.preventDefault(); move(1) }
|
|
39
|
+
else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1) }
|
|
40
|
+
else if (event.key === 'Enter' && results.length) { event.preventDefault(); document.querySelector('#search-result-' + active + ' a')?.click() }
|
|
41
|
+
// One Escape closes (a search field would only clear itself first).
|
|
42
|
+
else if (event.key === 'Escape') { event.preventDefault(); dialog().close() }
|
|
43
|
+
}
|
|
44
|
+
if (typeof document !== 'undefined') {
|
|
45
|
+
document.addEventListener('keydown', (event) => {
|
|
46
|
+
const typing = event.target.closest?.('input, textarea, select, [contenteditable]')
|
|
47
|
+
if ((event.key === 'k' && (event.metaKey || event.ctrlKey)) || (event.key === '/' && !typing)) {
|
|
48
|
+
event.preventDefault()
|
|
49
|
+
open()
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
</script>
|
|
54
|
+
|
|
55
|
+
<div class="search">
|
|
56
|
+
<button type="button" class="search-button" aria-haspopup="dialog" (click)="open()">
|
|
57
|
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="M20 20l-3.5-3.5"></path></svg>
|
|
58
|
+
<span class="search-label">Search</span>
|
|
59
|
+
<kbd aria-hidden="true">⌘K</kbd>
|
|
60
|
+
</button>
|
|
61
|
+
{{-- A click on the backdrop (the dialog itself, outside its box) closes it; so does choosing a result. --}}
|
|
62
|
+
<dialog class="search-dialog" aria-label="Search the docs" (click)="($event.target.matches('dialog') || $event.target.closest('a')) && dialog().close()">
|
|
63
|
+
<div class="search-box">
|
|
64
|
+
<input type="search" role="combobox" aria-label="Search the docs" aria-controls="search-results" aria-autocomplete="list" [aria-expanded]="results.length ? 'true' : 'false'" [aria-activedescendant]="results.length ? 'search-result-' + active : false" placeholder="Search the docs" autocomplete="off" spellcheck="false" (input)="run($event.target.value)" (keydown)="key($event)">
|
|
65
|
+
<p class="search-status" role="status">{{ status }}</p>
|
|
66
|
+
<ul id="search-results" role="listbox" aria-label="Results">
|
|
67
|
+
@for (r of results; track r.u) {
|
|
68
|
+
<li [id]="'search-result-' + $index" role="option" [aria-selected]="$index === active ? 'true' : 'false'">
|
|
69
|
+
<a [href]="r.u" tabindex="-1"><span class="search-heading">{{ r.h }}</span>@if (r.h !== r.p) {<span class="search-page">{{ r.p }}</span>}<span class="search-text">{{ r.t }}</span></a>
|
|
70
|
+
</li>
|
|
71
|
+
}
|
|
72
|
+
</ul>
|
|
73
|
+
</div>
|
|
74
|
+
</dialog>
|
|
75
|
+
</div>
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{{-- Light, dark or the system setting; remembered in localStorage and applied as data-theme on <html>. --}}
|
|
2
|
+
<script>
|
|
3
|
+
const order = ['system', 'light', 'dark']
|
|
4
|
+
let mode = state('system')
|
|
5
|
+
function apply() {
|
|
6
|
+
if (mode === 'system') document.documentElement.removeAttribute('data-theme')
|
|
7
|
+
else document.documentElement.setAttribute('data-theme', mode)
|
|
8
|
+
}
|
|
9
|
+
function cycle() {
|
|
10
|
+
mode = order[(order.indexOf(mode) + 1) % order.length]
|
|
11
|
+
try { localStorage.setItem('clarusjs-theme', mode) } catch {}
|
|
12
|
+
apply()
|
|
13
|
+
}
|
|
14
|
+
// In the browser, start from the saved choice (the server always renders "system").
|
|
15
|
+
if (typeof document !== 'undefined') {
|
|
16
|
+
try { mode = localStorage.getItem('clarusjs-theme') || 'system' } catch {}
|
|
17
|
+
apply()
|
|
18
|
+
}
|
|
19
|
+
</script>
|
|
20
|
+
|
|
21
|
+
<button type="button" class="theme-toggle" (click)="cycle()" [aria-label]="'Theme: ' + mode + ' (change)'" [title]="'Theme: ' + mode">
|
|
22
|
+
@if (mode === 'dark') {☾} @else if (mode === 'light') {☀} @else {◐}
|
|
23
|
+
</button>
|