@stepr/checklist 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peter Anyawantana
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,573 @@
1
- # Temporary Holding Version
1
+ # stepr-checklist
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lightweight, framework-agnostic onboarding checklist widget for the web.
4
+
5
+ > **Status: v0.1.1, an early release.** It contains the checklist
6
+ > widget, the state controller and optional persistence. Versions follow
7
+ > [semver](https://semver.org/) for 0.x: a **minor** release (0.2.0) may
8
+ > contain breaking changes, a patch release won't. See the
9
+ > [changelog](CHANGELOG.md).
10
+
11
+ `@stepr/checklist` is a small, dependency-free onboarding checklist widget
12
+ that works with any framework, or none. Steps are native buttons. Your app
13
+ decides when a step is complete, and progress can optionally be saved in
14
+ `localStorage`.
15
+
16
+ - [Demo](#demo) · [Quick start](#quick-start) · [Widget](#checklist-widget) ·
17
+ [Controller](#checklist-controller) · [Persistence](#persistence) ·
18
+ [Examples](#examples) · [Stepr integration](#starting-a-stepr-tour-from-a-step)
19
+ · [Limitations](#limitations) · [Browser support](#browser-support) ·
20
+ [License](#license)
21
+
22
+ ## Demo
23
+
24
+ **Live demo: <https://ahlgren1234.github.io/stepr-checklist/>**
25
+
26
+ The [`demo/`](demo/) folder has an interactive page with no framework. It
27
+ shows a made-up app whose onboarding steps are completed by app events,
28
+ programmatic completion, `reset()`, `destroy()`, opt-in persistence, themes, a
29
+ [Stepr](https://github.com/ahlgren1234/stepr) tour started from a step, and
30
+ the README examples with copy buttons.
31
+
32
+ To run it locally:
33
+
34
+ ```sh
35
+ pnpm install
36
+ pnpm demo # builds dist/, then serves http://localhost:4173/demo/
37
+ ```
38
+
39
+ The demo imports the **built package** (`dist/`) through an import map, using
40
+ the same `import … from '@stepr/checklist'` as the examples. Stepr is a
41
+ `devDependency` used only by the demo. It is not a dependency of the package.
42
+ `pnpm test:built` runs the demo and the README examples against `dist/` in
43
+ jsdom. The local server
44
+ ([`scripts/serve-demo.mjs`](scripts/serve-demo.mjs)) listens on `127.0.0.1`
45
+ only, and serves just the `.html`, `.css` and `.js` files in `demo/`, `dist/`
46
+ and `node_modules/stepr/dist/`. It refuses every other path, including
47
+ `.git`, `.env` and config files.
48
+
49
+ ### Deployment
50
+
51
+ Every push to `main` deploys the demo to GitHub Pages with
52
+ [`.github/workflows/pages.yml`](.github/workflows/pages.yml). The workflow can
53
+ also be started by hand from the Actions tab. It runs `pnpm check`, then
54
+ `pnpm build:pages`, which builds `dist/` and runs
55
+ [`scripts/build-pages.mjs`](scripts/build-pages.mjs) to assemble a static
56
+ site in `_site/` with no bundler:
57
+
58
+ - `index.html`, `smoke.html`, `main.js` and `demo.css` from `demo/`, at the
59
+ site root
60
+ - `dist/`: the built package's `.js` files
61
+ - `vendor/stepr/`: Stepr's `.js` files and license, copied from
62
+ `node_modules`
63
+
64
+ The script rewrites the demo's two `../` import paths to `./dist/` and
65
+ `./vendor/stepr/`. All paths are relative, so the site works under the
66
+ `/stepr-checklist/` base path. `pnpm test:built` builds the site and checks
67
+ that every stylesheet, script and module it loads exists inside it. To
68
+ preview the site, serve `_site/` with any static server. The workflow only
69
+ deploys the demo; it never publishes to npm.
70
+
71
+ ## Quick start
72
+
73
+ ```sh
74
+ npm install @stepr/checklist
75
+ ```
76
+
77
+ With a bundler, `import` it as usual. Without one, map the package name in an
78
+ [import map][import-maps] and serve the page over HTTP, because ES modules
79
+ don't load from `file://`:
80
+
81
+ <!-- example: quickstart -->
82
+
83
+ ```html
84
+ <!doctype html>
85
+ <html lang="en">
86
+ <head>
87
+ <meta charset="utf-8" />
88
+ <title>Checklist</title>
89
+ <script type="importmap">
90
+ {
91
+ "imports": {
92
+ "@stepr/checklist": "/node_modules/@stepr/checklist/dist/index.js"
93
+ }
94
+ }
95
+ </script>
96
+ </head>
97
+ <body>
98
+ <div id="onboarding"></div>
99
+ <script type="module">
100
+ import { createChecklist } from '@stepr/checklist';
101
+
102
+ createChecklist({
103
+ container: '#onboarding',
104
+ title: 'Get started',
105
+ steps: [
106
+ {
107
+ id: 'profile',
108
+ label: 'Complete your profile',
109
+ onClick: (step, checklist) => checklist.complete(step.id),
110
+ },
111
+ { id: 'docs', label: 'Read the docs' },
112
+ ],
113
+ });
114
+ </script>
115
+ </body>
116
+ </html>
117
+ ```
118
+
119
+ [import-maps]: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap
120
+
121
+ ## Checklist widget
122
+
123
+ `createChecklist` renders an accessible checklist into an existing element and
124
+ returns the [controller API](#checklist-controller) plus `element` and
125
+ `destroy()`.
126
+
127
+ ```ts
128
+ import { createChecklist } from '@stepr/checklist';
129
+
130
+ const checklist = createChecklist({
131
+ container: '#onboarding', // or an HTMLElement
132
+ title: 'Get started',
133
+ steps: [
134
+ {
135
+ id: 'profile',
136
+ label: 'Complete your profile',
137
+ onClick: (step, checklist) => {
138
+ openProfileForm(); // activation never completes a step by itself
139
+ },
140
+ },
141
+ { id: 'invite', label: 'Invite a teammate', onClick: openInviteDialog },
142
+ { id: 'docs', label: 'Read the docs' }, // no onClick: rendered as text
143
+ ],
144
+ storageKey: 'my-app:onboarding', // optional, see Persistence
145
+ });
146
+
147
+ // Later, e.g. when the profile form is saved:
148
+ checklist.complete('profile');
149
+
150
+ checklist.destroy(); // removes the widget only
151
+ ```
152
+
153
+ | Option | Default | Description |
154
+ | -------------- | ------- | ------------------------------------------------------------------------------------- |
155
+ | `container` | — | `HTMLElement` or CSS selector (`document.querySelector`). The widget is **appended**. |
156
+ | `title` | — | Heading text and the accessible name of the widget's region. Must be non-empty. |
157
+ | `steps` | — | As for the controller. May be empty. |
158
+ | `headingLevel` | `2` | `1`–`6`; pick the level that fits your page outline. |
159
+ | `storageKey` | — | Opt-in `localStorage` persistence (see [Persistence](#persistence)). |
160
+ | `onChange` | — | Called after every state change. |
161
+ | `messages` | English | `{ progress(progress), completed, notCompleted }` text overrides for localization. |
162
+ | `injectStyles` | `true` | Insert the default stylesheet. Set `false` to style it yourself (e.g. strict CSP). |
163
+
164
+ Behavior:
165
+
166
+ - **Rendering:** a `<section>` labelled by its heading, a progress text
167
+ (`"1 of 3 steps complete"`), a native `<progress>` bar and an `<ol>` of
168
+ steps. Steps with `onClick` are native `<button type="button">`s, so mouse,
169
+ touch, Enter and Space all work; steps without `onClick` are plain text.
170
+ Titles and labels are rendered as text, never HTML.
171
+ - **Activation** calls the step's `onClick(step, checklist)` and **never**
172
+ changes completion. Call `checklist.complete(id)` when the task is actually
173
+ done (from `onClick` or anywhere else). Completed steps stay activatable.
174
+ - **Updates:** the widget updates its existing nodes in place on every state
175
+ change, so keyboard focus is not lost.
176
+ - **Errors:** `createChecklist` throws an `Error` — before touching the DOM — if
177
+ the container is not an element, the selector is invalid or matches nothing,
178
+ the title is empty, `headingLevel` is out of range, or the controller options
179
+ are invalid.
180
+ - **Empty steps:** renders the heading, `"No steps"` and an empty progress bar,
181
+ without a list.
182
+ - **Instances** are independent; element ids are unique per instance.
183
+ - **`destroy()`** removes the widget's own element and state subscription, and
184
+ removes the shared stylesheet when no other widget uses it. Other container
185
+ content is untouched. It is idempotent; the controller methods keep working
186
+ afterwards but nothing is rendered.
187
+ - `createChecklist` needs a DOM; importing the package does not.
188
+
189
+ ### Accessibility
190
+
191
+ - Each step's accessible name includes its state, e.g. "Complete your profile,
192
+ completed" (visually hidden text, customizable via `messages`). The visual
193
+ check mark is hidden from assistive technology.
194
+ - The progress text is a polite live region (`role="status"`), so changes are
195
+ announced without moving focus. The `<progress>` bar is labelled by it.
196
+ - Focus is shown with a visible `:focus-visible` outline; targets are at least
197
+ 44px tall; transitions are disabled under `prefers-reduced-motion`.
198
+ - With the default colors, the incomplete and completed step markers have at
199
+ least 3:1 contrast against the widget and hover backgrounds (see
200
+ [Styling](#styling)).
201
+ - No dialog, ARIA widget roles or custom key handling: only native elements.
202
+
203
+ What has been verified: the structure above (roles, names, live region,
204
+ focus retention) is covered by jsdom tests, and keyboard operation and focus
205
+ retention were checked in Playwright's bundled browsers (see
206
+ [Browser support](#browser-support)). It has **not** been tested with a screen
207
+ reader, and the widget hasn't been audited against WCAG. See
208
+ [docs/manual-testing.md](docs/manual-testing.md) for the manual keyboard and
209
+ screen-reader test.
210
+
211
+ ### Styling
212
+
213
+ The default stylesheet is inserted once at the start of `<head>` (so your own
214
+ rules of equal specificity win) and uses BEM-style classes such as
215
+ `.stepr-checklist`, `.stepr-checklist__step` and `.stepr-checklist__action`;
216
+ completed steps have a `data-completed` attribute. Theme it with these custom
217
+ properties on `.stepr-checklist` or any ancestor:
218
+
219
+ | Property | Default | Used for |
220
+ | ------------------------------------- | --------- | ------------------------------------------------------- |
221
+ | `--stepr-checklist-accent` | `#2563eb` | Completed marker, progress bar (`accent-color`) |
222
+ | `--stepr-checklist-accent-foreground` | `#ffffff` | Check mark glyph |
223
+ | `--stepr-checklist-background` | `#ffffff` | Widget background |
224
+ | `--stepr-checklist-foreground` | `#1f2937` | Text |
225
+ | `--stepr-checklist-muted` | `#4b5563` | Progress text, completed labels, incomplete marker ring |
226
+ | `--stepr-checklist-border` | `#d1d5db` | Widget border |
227
+ | `--stepr-checklist-hover` | `#f3f4f6` | Step background on hover |
228
+ | `--stepr-checklist-focus` | `#2563eb` | Focus outline |
229
+ | `--stepr-checklist-radius` | `0.5rem` | Widget corner radius (steps use 75% of it) |
230
+ | `--stepr-checklist-padding` | `1rem` | Widget padding |
231
+ | `--stepr-checklist-gap` | `0.5rem` | Spacing between parts (steps use half of it) |
232
+ | `--stepr-checklist-font-family` | `inherit` | Font |
233
+
234
+ <!-- example: theme -->
235
+
236
+ ```css
237
+ /* <div id="onboarding" class="theme-violet"></div> */
238
+ .theme-violet {
239
+ --stepr-checklist-accent: #6d28d9;
240
+ --stepr-checklist-focus: #6d28d9;
241
+ --stepr-checklist-background: #faf5ff;
242
+ --stepr-checklist-hover: #f3e8ff;
243
+ --stepr-checklist-border: #8b5cf6;
244
+ --stepr-checklist-radius: 1rem;
245
+ }
246
+ ```
247
+
248
+ With `injectStyles: false`, include the exported `checklistCss` string (or
249
+ your own styles) yourself, for example in a `<style>` with a CSP nonce or a
250
+ shadow root.
251
+
252
+ Check contrast when you change colors. A step's state is conveyed by its
253
+ accessible name and the progress text, but visually only by the marker and the
254
+ muted label color, so the marker should keep at least the 3:1 that WCAG 2.2
255
+ SC 1.4.11 asks of non-text indicators against both `background` and `hover`:
256
+
257
+ - The incomplete marker ring uses `muted` (default `#4b5563`: 7.6:1 on the
258
+ default background, 6.9:1 on the hover color).
259
+ - The completed marker is filled with `accent` (default `#2563eb`: 5.2:1 and
260
+ 4.7:1).
261
+ - The widget border (`#d1d5db`, about 1.5:1) is decorative and doesn't convey
262
+ state.
263
+
264
+ `test/styles.test.ts` checks these default ratios.
265
+
266
+ ## Checklist controller
267
+
268
+ The core is a DOM-free state controller that the widget is built on; it can
269
+ also be used directly to build your own UI.
270
+
271
+ ```ts
272
+ import { createChecklistController } from '@stepr/checklist';
273
+
274
+ const checklist = createChecklistController({
275
+ steps: [
276
+ {
277
+ id: 'profile',
278
+ label: 'Complete your profile',
279
+ onClick: (step, checklist) => {
280
+ openProfileForm(); // completion is up to you:
281
+ // checklist.complete(step.id);
282
+ },
283
+ },
284
+ { id: 'invite', label: 'Invite a teammate' },
285
+ ],
286
+ onChange: (state) => console.log(state.progress), // { completed, total }
287
+ });
288
+
289
+ checklist.complete('invite'); // true
290
+ checklist.getProgress(); // { completed: 1, total: 2 }
291
+ const unsubscribe = checklist.subscribe((state) => render(state));
292
+ ```
293
+
294
+ | Method | Behavior |
295
+ | ----------------- | ------------------------------------------------------------------------------------------- |
296
+ | `complete(id)` | Marks a step complete. Returns `true` if state changed, `false` if it was already complete. |
297
+ | `uncomplete(id)` | Marks a step incomplete. Returns `true` if state changed, `false` if it was not complete. |
298
+ | `reset()` | Marks every step incomplete. Returns `true` if anything was complete. |
299
+ | `click(id)` | Calls the step's `onClick(step, checklist)`, if any. **Never changes completion.** |
300
+ | `isCompleted(id)` | Whether a step is complete. |
301
+ | `getProgress()` | `{ completed, total }`. |
302
+ | `getState()` | Fresh snapshot: `{ steps: [{ id, label, completed }], progress }`, in definition order. |
303
+ | `subscribe(fn)` | Calls `fn(state)` after every change. Returns an unsubscribe function. |
304
+
305
+ Behavior details:
306
+
307
+ - **Step ids** must be non-empty strings, unique within a checklist. Duplicate
308
+ or empty ids throw when the controller is created.
309
+ - **Unknown ids** passed to `complete`, `uncomplete`, `click` or `isCompleted`
310
+ throw an `Error` and leave state unchanged.
311
+ - **Repeated actions** (completing a complete step, resetting an empty
312
+ checklist, …) are no-ops: they return `false` and send no notification.
313
+ - **Empty checklists** are allowed; progress is `{ completed: 0, total: 0 }`.
314
+ - **Notifications** are sent synchronously after each actual change: first
315
+ `onChange`, then subscribers in subscription order. Listeners added during a
316
+ notification receive the next one. If listeners throw, the others are still
317
+ called, then the error is rethrown (an `AggregateError` if several threw);
318
+ the state change itself is kept.
319
+ - **Instances** are fully independent; there is no shared module state.
320
+ - Steps are copied on creation, and snapshots are fresh objects, so mutating
321
+ either does not affect the controller. All steps start incomplete unless
322
+ restored from storage (see below).
323
+
324
+ ## Persistence
325
+
326
+ Pass `storageKey` to save progress in `localStorage`. Without it, the
327
+ controller is memory-only and never touches storage.
328
+
329
+ ```ts
330
+ const checklist = createChecklistController({
331
+ steps,
332
+ storageKey: 'my-app:onboarding',
333
+ });
334
+ ```
335
+
336
+ - **Restoring:** completed step ids are read once, when the controller is
337
+ created. Ids of steps that no longer exist are ignored. Restoring does not
338
+ call `onChange` or subscribers; read the initial state with `getState()`.
339
+ - **Saving:** the completed ids are written after every change made by
340
+ `complete`, `uncomplete` or `reset`, before listeners are notified. No-op
341
+ actions and `click` do not write.
342
+ - **Format:** `{"v":1,"completed":["id", ...]}` under the exact key you pass.
343
+ Choose an app-specific key to avoid collisions with other scripts on the
344
+ same origin. An empty `storageKey` throws.
345
+ - **Failures are non-fatal:** if `localStorage` is unavailable or blocked, the
346
+ stored value is malformed or from an unknown format version, or a write fails
347
+ (e.g. quota exceeded), the checklist silently continues in memory. Malformed
348
+ data is treated as "nothing stored".
349
+ - **Scope:** storage is per origin and per browser profile. It is not synced
350
+ across devices, and controllers sharing a key in different tabs do not update
351
+ each other live (the last write wins).
352
+ - `localStorage` is only accessed when a controller with a `storageKey` is
353
+ created or changed, never on import, so the package is safe to import during
354
+ server-side rendering.
355
+
356
+ ## Examples
357
+
358
+ All examples are plain JavaScript. They also work unchanged as TypeScript,
359
+ since the package ships its own types. Placeholders such as
360
+ `openProfileForm` stand for your app's code. `pnpm test:built` runs each of
361
+ these blocks against the built package, and checks that the demo shows the
362
+ same text.
363
+
364
+ ### Completing steps from your app
365
+
366
+ <!-- example: app-events -->
367
+
368
+ ```js
369
+ import { createChecklist } from '@stepr/checklist';
370
+
371
+ const checklist = createChecklist({
372
+ container: '#onboarding',
373
+ title: 'Get started',
374
+ steps: [
375
+ {
376
+ id: 'profile',
377
+ label: 'Complete your profile',
378
+ onClick: () => openProfileForm(), // opening the form does not complete it
379
+ },
380
+ { id: 'verify', label: 'Verify your email address' }, // text only
381
+ ],
382
+ onChange: ({ progress }) => {
383
+ if (progress.completed === progress.total) showAllDoneMessage();
384
+ },
385
+ });
386
+
387
+ // Complete steps when the work is actually done, from anywhere in your app:
388
+ onProfileSaved(() => checklist.complete('profile'));
389
+ onEmailVerified(() => checklist.complete('verify'));
390
+ ```
391
+
392
+ If a step's `onClick` moves focus, for example into a form, move it back
393
+ afterwards (the demo returns it to the step that opened the form). The widget
394
+ doesn't manage focus outside itself.
395
+
396
+ ### Persistence, reset and cleanup
397
+
398
+ <!-- example: persistence -->
399
+
400
+ ```js
401
+ import { createChecklist } from '@stepr/checklist';
402
+
403
+ const checklist = createChecklist({
404
+ container: '#onboarding',
405
+ title: 'Get started',
406
+ steps: [
407
+ { id: 'profile', label: 'Complete your profile' },
408
+ { id: 'invite', label: 'Invite a teammate' },
409
+ ],
410
+ storageKey: 'my-app:onboarding', // restored on creation, saved on change
411
+ });
412
+
413
+ checklist.complete('invite'); // true, and saved
414
+ checklist.complete('invite'); // false: already complete, nothing saved
415
+ checklist.getProgress(); // { completed: 1, total: 2 }
416
+
417
+ checklist.reset(); // marks every step incomplete, and saves that
418
+ checklist.destroy(); // removes the widget; saved progress is kept
419
+ localStorage.removeItem('my-app:onboarding'); // forget saved progress
420
+ ```
421
+
422
+ ### Starting a Stepr tour from a step
423
+
424
+ [Stepr](https://github.com/ahlgren1234/stepr) is a separate tour library.
425
+ `@stepr/checklist` doesn't import it or depend on it. Install it yourself
426
+ (`npm install stepr`) if you want tours, and connect the two in your app:
427
+
428
+ <!-- example: stepr -->
429
+
430
+ ```js
431
+ import { createChecklist } from '@stepr/checklist';
432
+ import { createTour } from 'stepr';
433
+
434
+ const tour = createTour({
435
+ steps: [
436
+ { target: '#new-project', title: 'Projects', description: 'Start here.' },
437
+ { target: '#invite', title: 'Invite your team' },
438
+ ],
439
+ onComplete: () => checklist.complete('tour'), // finished: tick it off
440
+ onExit: () => {}, // closed early: the step stays incomplete
441
+ });
442
+
443
+ const checklist = createChecklist({
444
+ container: '#onboarding',
445
+ title: 'Get started',
446
+ steps: [
447
+ {
448
+ id: 'tour',
449
+ label: 'Take the product tour',
450
+ onClick: () => {
451
+ if (!tour.start()) console.warn('No tour target is visible');
452
+ },
453
+ },
454
+ ],
455
+ });
456
+ ```
457
+
458
+ - The step's `onClick` starts the tour. Only the tour's `onComplete`, which
459
+ runs when the user passes the last step, completes the checklist step.
460
+ Close or Escape calls `onExit` and leaves the step open, so the user can
461
+ retry.
462
+ - `tour.start()` returns `false` when none of the tour's targets is rendered.
463
+ Handle that case, for example by completing the step anyway or showing help.
464
+ - When the tour ends, Stepr returns focus to the element that was focused
465
+ before `start()`. For a step activated from the keyboard, that is the step's
466
+ button.
467
+ - Stepr has its own accessibility notes and limitations; see its README. The
468
+ pairing was exercised in the demo with Stepr 0.1.0.
469
+
470
+ ## Limitations
471
+
472
+ - **Early 0.x release.** Minor versions may contain breaking changes.
473
+ - **Steps are fixed at creation.** To add, remove or relabel steps, `destroy()`
474
+ the widget and create a new one. Labels are plain text; there are no
475
+ descriptions, icons or links inside steps.
476
+ - **No built-in reset, dismiss, collapse or "hide when done" UI.** Use the API
477
+ (as the demo does) and your own controls.
478
+ - **Default text is English.** Override it with `messages`.
479
+ - **Light default theme only.** There is no automatic dark mode; use the
480
+ custom properties. See the contrast note under [Styling](#styling).
481
+ - **Shadow DOM:** the default stylesheet goes into the document's `<head>`, so
482
+ it doesn't reach a widget inside a shadow root. Use `injectStyles: false` and
483
+ add `checklistCss` to the shadow root yourself. A string `container` is
484
+ resolved with `document.querySelector` and doesn't look inside shadow roots.
485
+ - **Element ids** are `stepr-checklist-<n>`, counted per copy of the package.
486
+ Two separately bundled copies on one page could produce duplicate ids.
487
+ - **Persistence** is `localStorage` only: per origin and browser, not synced
488
+ across devices or live across tabs. See [Persistence](#persistence).
489
+ - **Page styles can leak in.** The defaults use single-class selectors, so
490
+ your page rules with higher specificity, such as `.sidebar h2 { … }`, also
491
+ restyle the widget's heading and buttons. Scope such rules, as the demo
492
+ does with `.section > h2`.
493
+ - **Rendering needs a DOM.** Importing is safe during server-side rendering,
494
+ but there is no server-rendered markup.
495
+
496
+ ## Browser support
497
+
498
+ No browser support matrix has been tested, so no minimum versions are claimed.
499
+ The package is compiled to ES2022 and the widget uses native `<button>`,
500
+ `<progress>`, `:focus-visible`, `accent-color`, `clip-path: inset()` and
501
+ `Element.toggleAttribute`. Check these against your own support targets. The
502
+ no-bundler setup also needs [import maps][import-maps].
503
+
504
+ Evidence so far (2026-11-14, Linux/WSL2), from an ad-hoc Playwright 1.63
505
+ script that is not part of the repository. It used Playwright's bundled
506
+ **Chromium 153**, **Firefox 155** and **WebKit 26.6**, which are close to but
507
+ not the same as Chrome, Firefox and Safari. In all three, the demo:
508
+
509
+ - loaded with no console or page errors at 1280, 768, 375 and 320px wide, with
510
+ no horizontal scrolling and step buttons at least 44px tall
511
+ - moved Tab focus through the four step buttons in order and skipped the
512
+ text-only step, showing a 2px solid focus outline
513
+ - activated steps with Enter and Space, kept focus on the step after
514
+ completing it, and updated the progress text
515
+ - completed the Stepr tour step with the keyboard and returned focus to the
516
+ step afterwards. Escape closed the tour early.
517
+ - restored persisted progress after a reload and cleared it when turned off
518
+ - had no step transition with reduced motion emulated
519
+ - copied an example to the clipboard (Chromium only; the other engines weren't
520
+ checked)
521
+
522
+ Not tested: real Chrome, Edge, Safari or Firefox builds, macOS, Windows,
523
+ iOS, Android, touch input, zoom, forced colors / high contrast, and any
524
+ screen reader. See [docs/manual-testing.md](docs/manual-testing.md).
525
+
526
+ ## Assumptions
527
+
528
+ - **ESM only.** Published as native ES modules with TypeScript declarations;
529
+ no CommonJS build. CommonJS consumers can use dynamic `import()`.
530
+ - **No runtime dependencies.** Development tooling only.
531
+ - **Browser-first.** Compiled to ES2022 for modern browsers. The package
532
+ declares no Node.js `engines` requirement, since it only needs Node.js when
533
+ imported during server-side rendering or tests (verified with Node.js 24 and
534
+ 26).
535
+ - **Development** uses **Node.js 24** (see `.nvmrc`; CI uses the same) and
536
+ **pnpm** (version pinned via `packageManager`; enable with
537
+ `corepack enable`).
538
+ - **TypeScript 6.0.x**, since `typescript-eslint` does not yet support TypeScript 7.
539
+ - The build is plain `tsc`; a bundler can be introduced later if needed.
540
+
541
+ ## Development
542
+
543
+ ```sh
544
+ corepack enable
545
+ pnpm install
546
+
547
+ pnpm typecheck # type-check sources and tests
548
+ pnpm lint # ESLint (typescript-eslint, strict type-checked)
549
+ pnpm format # format with Prettier (pnpm format:check to verify)
550
+ pnpm test # run tests with Vitest + jsdom (pnpm test:watch for watch mode)
551
+ pnpm build # compile to dist/ with declarations
552
+ pnpm test:built # run the demo and README examples against dist/ (jsdom)
553
+ pnpm check:package # publint + attw + install/import the packed tarball in a clean consumer
554
+ pnpm check # all of the above, as run in CI
555
+ pnpm demo # build, then serve the demo at http://localhost:4173/demo/
556
+ pnpm build:pages # build, then assemble the GitHub Pages site in _site/
557
+ ```
558
+
559
+ `pnpm test:built` and `pnpm check:package` require a prior `pnpm build`. CI
560
+ runs every check on pull requests and pushes to `main`; it never publishes or
561
+ deploys. A separate workflow deploys the demo (see [Deployment](#deployment)).
562
+
563
+ `pnpm pack` builds `dist/` first (`prepack`). Releases are published by hand;
564
+ see [docs/releasing.md](docs/releasing.md).
565
+
566
+ ## Contributing
567
+
568
+ Work on a feature branch, run `pnpm check` before opening a pull request, and
569
+ reference the relevant issue.
570
+
571
+ ## License
572
+
573
+ [MIT](LICENSE) © Peter Anyawantana
@@ -0,0 +1,93 @@
1
+ /** A step as defined by the consumer. */
2
+ export interface ChecklistStep {
3
+ /** Stable, non-empty identifier, unique within one checklist. */
4
+ readonly id: string;
5
+ /** Human-readable label. */
6
+ readonly label: string;
7
+ /**
8
+ * Called when the step is activated (see {@link ChecklistController.click}).
9
+ * Activation never changes completion; call `checklist.complete(step.id)`
10
+ * from here if that is the desired behavior.
11
+ */
12
+ readonly onClick?: (step: ChecklistStepState, checklist: ChecklistController) => void;
13
+ }
14
+ /** Read-only view of a step at a point in time. */
15
+ export interface ChecklistStepState {
16
+ readonly id: string;
17
+ readonly label: string;
18
+ readonly completed: boolean;
19
+ }
20
+ /** Completion progress. `total` is 0 for an empty checklist. */
21
+ export interface ChecklistProgress {
22
+ readonly completed: number;
23
+ readonly total: number;
24
+ }
25
+ /** Read-only view of the whole checklist at a point in time. */
26
+ export interface ChecklistState {
27
+ /** Steps in definition order. */
28
+ readonly steps: readonly ChecklistStepState[];
29
+ readonly progress: ChecklistProgress;
30
+ }
31
+ /** Called after every state change with the new state. */
32
+ export type ChecklistListener = (state: ChecklistState) => void;
33
+ export interface ChecklistControllerOptions {
34
+ /** Steps in display order. May be empty. */
35
+ readonly steps: readonly ChecklistStep[];
36
+ /** Consumer callback, called after every state change. */
37
+ readonly onChange?: ChecklistListener;
38
+ /**
39
+ * Opts in to `localStorage` persistence under this key. Completed step ids
40
+ * are restored on creation (ids of steps that no longer exist are ignored)
41
+ * and saved after every change. Without a key, state is memory-only.
42
+ *
43
+ * Storage is per origin and per browser; it is not synced across devices.
44
+ * Storage failures are ignored and the checklist keeps working in memory.
45
+ */
46
+ readonly storageKey?: string;
47
+ }
48
+ export interface ChecklistController {
49
+ /**
50
+ * Marks a step as complete. Returns `true` if the state changed, `false` if
51
+ * the step was already complete (no notification is sent).
52
+ * @throws {Error} If `id` is not a step of this checklist.
53
+ */
54
+ complete(id: string): boolean;
55
+ /**
56
+ * Marks a step as not complete. Returns `true` if the state changed, `false`
57
+ * if the step was not complete (no notification is sent).
58
+ * @throws {Error} If `id` is not a step of this checklist.
59
+ */
60
+ uncomplete(id: string): boolean;
61
+ /**
62
+ * Marks every step as not complete. Returns `true` if the state changed,
63
+ * `false` if nothing was complete (no notification is sent).
64
+ */
65
+ reset(): boolean;
66
+ /**
67
+ * Invokes the step's `onClick` callback, if any. Never changes completion.
68
+ * @throws {Error} If `id` is not a step of this checklist.
69
+ */
70
+ click(id: string): void;
71
+ /**
72
+ * Whether a step is complete.
73
+ * @throws {Error} If `id` is not a step of this checklist.
74
+ */
75
+ isCompleted(id: string): boolean;
76
+ getProgress(): ChecklistProgress;
77
+ /** Returns a fresh snapshot; mutating it does not affect the checklist. */
78
+ getState(): ChecklistState;
79
+ /**
80
+ * Registers a listener called after every state change, after `onChange`.
81
+ * Returns a function that removes the listener.
82
+ */
83
+ subscribe(listener: ChecklistListener): () => void;
84
+ }
85
+ /**
86
+ * Creates an independent, DOM-free checklist state controller.
87
+ *
88
+ * Steps start incomplete, unless restored from `storageKey`. Restoring does
89
+ * not trigger `onChange`; read the initial state with `getState()`.
90
+ * @throws {Error} If a step id is empty or duplicated, or `storageKey` is an
91
+ * empty string.
92
+ */
93
+ export declare function createChecklistController(options: ChecklistControllerOptions): ChecklistController;
@@ -0,0 +1,122 @@
1
+ import { loadCompleted, saveCompleted } from './storage.js';
2
+ /**
3
+ * Creates an independent, DOM-free checklist state controller.
4
+ *
5
+ * Steps start incomplete, unless restored from `storageKey`. Restoring does
6
+ * not trigger `onChange`; read the initial state with `getState()`.
7
+ * @throws {Error} If a step id is empty or duplicated, or `storageKey` is an
8
+ * empty string.
9
+ */
10
+ export function createChecklistController(options) {
11
+ const steps = new Map();
12
+ for (const step of options.steps) {
13
+ if (typeof step.id !== 'string' || step.id === '') {
14
+ throw new Error('Checklist step id must be a non-empty string');
15
+ }
16
+ if (steps.has(step.id)) {
17
+ throw new Error(`Duplicate checklist step id: "${step.id}"`);
18
+ }
19
+ steps.set(step.id, { ...step });
20
+ }
21
+ const { onChange, storageKey } = options;
22
+ if (storageKey === '') {
23
+ throw new Error('Checklist storageKey must be a non-empty string');
24
+ }
25
+ const completed = new Set();
26
+ if (storageKey !== undefined) {
27
+ for (const id of loadCompleted(storageKey)) {
28
+ if (steps.has(id))
29
+ completed.add(id);
30
+ }
31
+ }
32
+ const listeners = new Set();
33
+ const getStep = (id) => {
34
+ const step = steps.get(id);
35
+ if (!step)
36
+ throw new Error(`Unknown checklist step id: "${id}"`);
37
+ return step;
38
+ };
39
+ const toStepState = ({ id, label }) => ({
40
+ id,
41
+ label,
42
+ completed: completed.has(id),
43
+ });
44
+ const getProgress = () => ({
45
+ completed: completed.size,
46
+ total: steps.size,
47
+ });
48
+ const getState = () => ({
49
+ steps: Array.from(steps.values(), toStepState),
50
+ progress: getProgress(),
51
+ });
52
+ // Called after every change. State is saved before listeners run, so a
53
+ // throwing listener cannot prevent persistence. Listeners registered when
54
+ // the change happened are called in order, even if an earlier one throws;
55
+ // errors are rethrown afterwards so they are not silently swallowed.
56
+ const commit = () => {
57
+ if (storageKey !== undefined)
58
+ saveCompleted(storageKey, completed);
59
+ const state = getState();
60
+ const targets = onChange ? [onChange, ...listeners] : [...listeners];
61
+ const errors = [];
62
+ for (const listener of targets) {
63
+ try {
64
+ listener(state);
65
+ }
66
+ catch (error) {
67
+ errors.push(error);
68
+ }
69
+ }
70
+ if (errors.length === 1)
71
+ throw errors[0];
72
+ if (errors.length > 1) {
73
+ throw new AggregateError(errors, 'Checklist listeners threw errors');
74
+ }
75
+ };
76
+ const controller = {
77
+ complete(id) {
78
+ getStep(id);
79
+ if (completed.has(id))
80
+ return false;
81
+ completed.add(id);
82
+ commit();
83
+ return true;
84
+ },
85
+ uncomplete(id) {
86
+ getStep(id);
87
+ if (!completed.delete(id))
88
+ return false;
89
+ commit();
90
+ return true;
91
+ },
92
+ reset() {
93
+ if (completed.size === 0)
94
+ return false;
95
+ completed.clear();
96
+ commit();
97
+ return true;
98
+ },
99
+ click(id) {
100
+ const step = getStep(id);
101
+ step.onClick?.(toStepState(step), controller);
102
+ },
103
+ isCompleted(id) {
104
+ getStep(id);
105
+ return completed.has(id);
106
+ },
107
+ getProgress,
108
+ getState,
109
+ subscribe(listener) {
110
+ // Wrap so the same function can be subscribed more than once and each
111
+ // unsubscribe removes only its own registration.
112
+ const entry = (state) => {
113
+ listener(state);
114
+ };
115
+ listeners.add(entry);
116
+ return () => {
117
+ listeners.delete(entry);
118
+ };
119
+ },
120
+ };
121
+ return controller;
122
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Public entry point for `@stepr/checklist`.
3
+ *
4
+ * Versions are 0.x: a minor release may contain breaking changes.
5
+ */
6
+ export { createChecklist } from './widget.js';
7
+ export type { Checklist, ChecklistMessages, ChecklistOptions, } from './widget.js';
8
+ export { checklistCss } from './styles.js';
9
+ export { createChecklistController } from './controller.js';
10
+ export type { ChecklistController, ChecklistControllerOptions, ChecklistListener, ChecklistProgress, ChecklistState, ChecklistStep, ChecklistStepState, } from './controller.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Public entry point for `@stepr/checklist`.
3
+ *
4
+ * Versions are 0.x: a minor release may contain breaking changes.
5
+ */
6
+ export { createChecklist } from './widget.js';
7
+ export { checklistCss } from './styles.js';
8
+ export { createChecklistController } from './controller.js';
@@ -0,0 +1,4 @@
1
+ /** Returns the stored completed ids, or an empty list if none are usable. */
2
+ export declare function loadCompleted(key: string): string[];
3
+ /** Stores the completed ids; failures are ignored. */
4
+ export declare function saveCompleted(key: string, completed: Iterable<string>): void;
@@ -0,0 +1,49 @@
1
+ // localStorage persistence for completed step ids.
2
+ //
3
+ // Stored format: {"v":1,"completed":["id", ...]}. Every failure (storage
4
+ // unavailable or blocked, malformed or unknown-version data, quota errors) is
5
+ // non-fatal: reads fall back to "nothing stored" and writes are dropped, so
6
+ // the checklist keeps working in memory.
7
+ const VERSION = 1;
8
+ // Resolved lazily on every call: never touched at module import, and
9
+ // accessing `localStorage` itself can throw (e.g. sandboxed iframes, blocked
10
+ // cookies).
11
+ const getStorage = () => {
12
+ try {
13
+ return typeof localStorage === 'undefined' ? undefined : localStorage;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ };
19
+ /** Returns the stored completed ids, or an empty list if none are usable. */
20
+ export function loadCompleted(key) {
21
+ try {
22
+ const raw = getStorage()?.getItem(key);
23
+ if (raw == null)
24
+ return [];
25
+ const data = JSON.parse(raw);
26
+ if (typeof data !== 'object' ||
27
+ data === null ||
28
+ !('v' in data) ||
29
+ data.v !== VERSION ||
30
+ !('completed' in data) ||
31
+ !Array.isArray(data.completed)) {
32
+ return [];
33
+ }
34
+ return data.completed.filter((id) => typeof id === 'string');
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ }
40
+ /** Stores the completed ids; failures are ignored. */
41
+ export function saveCompleted(key, completed) {
42
+ try {
43
+ const data = { v: VERSION, completed: [...completed] };
44
+ getStorage()?.setItem(key, JSON.stringify(data));
45
+ }
46
+ catch {
47
+ // Quota exceeded, storage disabled, etc.: keep working in memory.
48
+ }
49
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Default widget styles. Selectors use one or two classes, and the injected
3
+ * `<style>` is inserted at the start of `<head>`, so consumer rules of equal
4
+ * specificity win. Theme through the `--stepr-checklist-*` custom properties
5
+ * on `.stepr-checklist` (or any ancestor).
6
+ */
7
+ export declare const checklistCss = "\n.stepr-checklist {\n --_accent: var(--stepr-checklist-accent, #2563eb);\n --_accent-fg: var(--stepr-checklist-accent-foreground, #ffffff);\n --_bg: var(--stepr-checklist-background, #ffffff);\n --_fg: var(--stepr-checklist-foreground, #1f2937);\n --_muted: var(--stepr-checklist-muted, #4b5563);\n --_border: var(--stepr-checklist-border, #d1d5db);\n --_hover: var(--stepr-checklist-hover, #f3f4f6);\n --_focus: var(--stepr-checklist-focus, #2563eb);\n --_radius: var(--stepr-checklist-radius, 0.5rem);\n --_padding: var(--stepr-checklist-padding, 1rem);\n --_gap: var(--stepr-checklist-gap, 0.5rem);\n position: relative;\n box-sizing: border-box;\n max-width: 100%;\n padding: var(--_padding);\n border: 1px solid var(--_border);\n border-radius: var(--_radius);\n background: var(--_bg);\n color: var(--_fg);\n font-family: var(--stepr-checklist-font-family, inherit);\n line-height: 1.4;\n overflow-wrap: anywhere;\n}\n.stepr-checklist *,\n.stepr-checklist *::before,\n.stepr-checklist *::after {\n box-sizing: inherit;\n}\n.stepr-checklist__title {\n margin: 0 0 var(--_gap);\n font-size: 1.125rem;\n line-height: 1.3;\n}\n.stepr-checklist__progress-text {\n margin: 0 0 var(--_gap);\n color: var(--_muted);\n font-size: 0.875rem;\n}\n.stepr-checklist__progress {\n display: block;\n width: 100%;\n height: 0.5rem;\n margin: 0 0 var(--_gap);\n accent-color: var(--_accent);\n}\n.stepr-checklist__steps {\n display: grid;\n gap: calc(var(--_gap) / 2);\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.stepr-checklist__step {\n margin: 0;\n}\n.stepr-checklist__action, .stepr-checklist__static {\n display: flex;\n align-items: center;\n gap: var(--_gap);\n width: 100%;\n min-height: 2.75rem;\n padding: 0.5rem 0.75rem;\n border: 1px solid transparent;\n border-radius: calc(var(--_radius) * 0.75);\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: start;\n}\n.stepr-checklist__action {\n cursor: pointer;\n transition: background-color 150ms ease;\n}\n.stepr-checklist__action:hover {\n background: var(--_hover);\n}\n.stepr-checklist__action:focus-visible {\n outline: 2px solid var(--_focus);\n outline-offset: 2px;\n}\n.stepr-checklist__marker {\n display: inline-flex;\n flex: none;\n align-items: center;\n justify-content: center;\n width: 1.25rem;\n height: 1.25rem;\n border: 2px solid var(--_muted);\n border-radius: 50%;\n font-size: 0.75rem;\n font-weight: 700;\n line-height: 1;\n}\n.stepr-checklist__step[data-completed] .stepr-checklist__marker {\n border-color: var(--_accent);\n background: var(--_accent);\n color: var(--_accent-fg);\n}\n.stepr-checklist__step[data-completed] .stepr-checklist__marker::after {\n content: '\\2713';\n}\n.stepr-checklist__step[data-completed] .stepr-checklist__label {\n color: var(--_muted);\n}\n.stepr-checklist__visually-hidden {\n position: absolute;\n width: 1px;\n height: 1px;\n margin: -1px;\n padding: 0;\n overflow: hidden;\n clip-path: inset(50%);\n white-space: nowrap;\n border: 0;\n}\n@media (prefers-reduced-motion: reduce) {\n .stepr-checklist *,\n .stepr-checklist *::before,\n .stepr-checklist *::after {\n transition: none;\n animation: none;\n }\n}\n";
package/dist/styles.js ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Default widget styles. Selectors use one or two classes, and the injected
3
+ * `<style>` is inserted at the start of `<head>`, so consumer rules of equal
4
+ * specificity win. Theme through the `--stepr-checklist-*` custom properties
5
+ * on `.stepr-checklist` (or any ancestor).
6
+ */
7
+ export const checklistCss = `
8
+ .stepr-checklist {
9
+ --_accent: var(--stepr-checklist-accent, #2563eb);
10
+ --_accent-fg: var(--stepr-checklist-accent-foreground, #ffffff);
11
+ --_bg: var(--stepr-checklist-background, #ffffff);
12
+ --_fg: var(--stepr-checklist-foreground, #1f2937);
13
+ --_muted: var(--stepr-checklist-muted, #4b5563);
14
+ --_border: var(--stepr-checklist-border, #d1d5db);
15
+ --_hover: var(--stepr-checklist-hover, #f3f4f6);
16
+ --_focus: var(--stepr-checklist-focus, #2563eb);
17
+ --_radius: var(--stepr-checklist-radius, 0.5rem);
18
+ --_padding: var(--stepr-checklist-padding, 1rem);
19
+ --_gap: var(--stepr-checklist-gap, 0.5rem);
20
+ position: relative;
21
+ box-sizing: border-box;
22
+ max-width: 100%;
23
+ padding: var(--_padding);
24
+ border: 1px solid var(--_border);
25
+ border-radius: var(--_radius);
26
+ background: var(--_bg);
27
+ color: var(--_fg);
28
+ font-family: var(--stepr-checklist-font-family, inherit);
29
+ line-height: 1.4;
30
+ overflow-wrap: anywhere;
31
+ }
32
+ .stepr-checklist *,
33
+ .stepr-checklist *::before,
34
+ .stepr-checklist *::after {
35
+ box-sizing: inherit;
36
+ }
37
+ .stepr-checklist__title {
38
+ margin: 0 0 var(--_gap);
39
+ font-size: 1.125rem;
40
+ line-height: 1.3;
41
+ }
42
+ .stepr-checklist__progress-text {
43
+ margin: 0 0 var(--_gap);
44
+ color: var(--_muted);
45
+ font-size: 0.875rem;
46
+ }
47
+ .stepr-checklist__progress {
48
+ display: block;
49
+ width: 100%;
50
+ height: 0.5rem;
51
+ margin: 0 0 var(--_gap);
52
+ accent-color: var(--_accent);
53
+ }
54
+ .stepr-checklist__steps {
55
+ display: grid;
56
+ gap: calc(var(--_gap) / 2);
57
+ margin: 0;
58
+ padding: 0;
59
+ list-style: none;
60
+ }
61
+ .stepr-checklist__step {
62
+ margin: 0;
63
+ }
64
+ .stepr-checklist__action, .stepr-checklist__static {
65
+ display: flex;
66
+ align-items: center;
67
+ gap: var(--_gap);
68
+ width: 100%;
69
+ min-height: 2.75rem;
70
+ padding: 0.5rem 0.75rem;
71
+ border: 1px solid transparent;
72
+ border-radius: calc(var(--_radius) * 0.75);
73
+ background: transparent;
74
+ color: inherit;
75
+ font: inherit;
76
+ text-align: start;
77
+ }
78
+ .stepr-checklist__action {
79
+ cursor: pointer;
80
+ transition: background-color 150ms ease;
81
+ }
82
+ .stepr-checklist__action:hover {
83
+ background: var(--_hover);
84
+ }
85
+ .stepr-checklist__action:focus-visible {
86
+ outline: 2px solid var(--_focus);
87
+ outline-offset: 2px;
88
+ }
89
+ .stepr-checklist__marker {
90
+ display: inline-flex;
91
+ flex: none;
92
+ align-items: center;
93
+ justify-content: center;
94
+ width: 1.25rem;
95
+ height: 1.25rem;
96
+ border: 2px solid var(--_muted);
97
+ border-radius: 50%;
98
+ font-size: 0.75rem;
99
+ font-weight: 700;
100
+ line-height: 1;
101
+ }
102
+ .stepr-checklist__step[data-completed] .stepr-checklist__marker {
103
+ border-color: var(--_accent);
104
+ background: var(--_accent);
105
+ color: var(--_accent-fg);
106
+ }
107
+ .stepr-checklist__step[data-completed] .stepr-checklist__marker::after {
108
+ content: '\\2713';
109
+ }
110
+ .stepr-checklist__step[data-completed] .stepr-checklist__label {
111
+ color: var(--_muted);
112
+ }
113
+ .stepr-checklist__visually-hidden {
114
+ position: absolute;
115
+ width: 1px;
116
+ height: 1px;
117
+ margin: -1px;
118
+ padding: 0;
119
+ overflow: hidden;
120
+ clip-path: inset(50%);
121
+ white-space: nowrap;
122
+ border: 0;
123
+ }
124
+ @media (prefers-reduced-motion: reduce) {
125
+ .stepr-checklist *,
126
+ .stepr-checklist *::before,
127
+ .stepr-checklist *::after {
128
+ transition: none;
129
+ animation: none;
130
+ }
131
+ }
132
+ `;
@@ -0,0 +1,51 @@
1
+ import { type ChecklistController, type ChecklistControllerOptions, type ChecklistProgress } from './controller.js';
2
+ /** Text used by the widget; override for localization. */
3
+ export interface ChecklistMessages {
4
+ /** Visible progress text, also announced politely when progress changes. */
5
+ readonly progress?: (progress: ChecklistProgress) => string;
6
+ /** Screen-reader-only status appended to a completed step's name. */
7
+ readonly completed?: string;
8
+ /** Screen-reader-only status appended to an incomplete step's name. */
9
+ readonly notCompleted?: string;
10
+ }
11
+ export interface ChecklistOptions extends ChecklistControllerOptions {
12
+ /**
13
+ * Element to render into, or a CSS selector resolved with
14
+ * `document.querySelector`. The widget is appended; existing content is kept.
15
+ */
16
+ readonly container: HTMLElement | string;
17
+ /** Heading text; also the accessible name of the widget's region. */
18
+ readonly title: string;
19
+ /** Heading level for the title. Default: 2. */
20
+ readonly headingLevel?: 1 | 2 | 3 | 4 | 5 | 6;
21
+ /** Text overrides, e.g. for localization. */
22
+ readonly messages?: ChecklistMessages;
23
+ /**
24
+ * Whether to insert the default stylesheet into the document. Default: true.
25
+ * Set to `false` to supply styles yourself (e.g. under a strict CSP), for
26
+ * example from the exported `checklistCss`.
27
+ */
28
+ readonly injectStyles?: boolean;
29
+ }
30
+ /** A rendered checklist widget: the controller API plus DOM lifecycle. */
31
+ export interface Checklist extends ChecklistController {
32
+ /** The widget's root element (owned by the widget). */
33
+ readonly element: HTMLElement;
34
+ /**
35
+ * Removes the widget's element, stops re-rendering and releases the default
36
+ * stylesheet when no other widget uses it. Other container content is left
37
+ * untouched. Idempotent. State methods keep working afterwards.
38
+ */
39
+ destroy(): void;
40
+ }
41
+ /**
42
+ * Renders an accessible checklist into `container`.
43
+ *
44
+ * Steps with an `onClick` render as native buttons; activating one (click,
45
+ * Enter or Space) calls `onClick` and never changes completion. Steps without
46
+ * `onClick` render as plain text. The widget re-renders in place on every
47
+ * state change, so focus is preserved.
48
+ * @throws {Error} If the container is missing or invalid, `title` is empty,
49
+ * or the controller options are invalid (see `createChecklistController`).
50
+ */
51
+ export declare function createChecklist(options: ChecklistOptions): Checklist;
package/dist/widget.js ADDED
@@ -0,0 +1,159 @@
1
+ import { createChecklistController, } from './controller.js';
2
+ import { checklistCss } from './styles.js';
3
+ const defaultProgress = ({ completed, total }) => total === 0
4
+ ? 'No steps'
5
+ : `${String(completed)} of ${String(total)} ${total === 1 ? 'step' : 'steps'} complete`;
6
+ const STYLE_ATTR = 'data-stepr-checklist';
7
+ const styleUsers = new WeakMap();
8
+ const acquireStyles = (doc) => {
9
+ let entry = styleUsers.get(doc);
10
+ if (!entry) {
11
+ const el = doc.createElement('style');
12
+ el.setAttribute(STYLE_ATTR, '');
13
+ el.textContent = checklistCss;
14
+ doc.head.prepend(el);
15
+ entry = { el, count: 0 };
16
+ styleUsers.set(doc, entry);
17
+ }
18
+ entry.count += 1;
19
+ const owned = entry;
20
+ return () => {
21
+ owned.count -= 1;
22
+ if (owned.count === 0) {
23
+ owned.el.remove();
24
+ styleUsers.delete(doc);
25
+ }
26
+ };
27
+ };
28
+ const resolveContainer = (container) => {
29
+ if (typeof container !== 'string') {
30
+ // Duck-typed so elements from other realms (iframes) are accepted.
31
+ if (typeof container === 'object' &&
32
+ container?.nodeType === 1) {
33
+ return container;
34
+ }
35
+ throw new Error('Checklist container must be an HTMLElement or a selector');
36
+ }
37
+ let found;
38
+ try {
39
+ found = document.querySelector(container);
40
+ }
41
+ catch {
42
+ throw new Error(`Invalid checklist container selector: "${container}"`);
43
+ }
44
+ if (!(found instanceof HTMLElement)) {
45
+ throw new Error(`Checklist container not found: "${container}"`);
46
+ }
47
+ return found;
48
+ };
49
+ let instanceCount = 0;
50
+ /**
51
+ * Renders an accessible checklist into `container`.
52
+ *
53
+ * Steps with an `onClick` render as native buttons; activating one (click,
54
+ * Enter or Space) calls `onClick` and never changes completion. Steps without
55
+ * `onClick` render as plain text. The widget re-renders in place on every
56
+ * state change, so focus is preserved.
57
+ * @throws {Error} If the container is missing or invalid, `title` is empty,
58
+ * or the controller options are invalid (see `createChecklistController`).
59
+ */
60
+ export function createChecklist(options) {
61
+ const { container, title, headingLevel = 2, messages = {} } = options;
62
+ const host = resolveContainer(container);
63
+ if (typeof title !== 'string' || title.trim() === '') {
64
+ throw new Error('Checklist title must be a non-empty string');
65
+ }
66
+ if (![1, 2, 3, 4, 5, 6].includes(headingLevel)) {
67
+ throw new Error('Checklist headingLevel must be an integer from 1 to 6');
68
+ }
69
+ const controllerOptions = {
70
+ steps: options.steps,
71
+ ...(options.onChange && { onChange: options.onChange }),
72
+ ...(options.storageKey !== undefined && { storageKey: options.storageKey }),
73
+ };
74
+ const controller = createChecklistController(controllerOptions);
75
+ const formatProgress = messages.progress ?? defaultProgress;
76
+ const completedText = messages.completed ?? 'completed';
77
+ const notCompletedText = messages.notCompleted ?? 'not completed';
78
+ const doc = host.ownerDocument;
79
+ const el = (tag, className) => {
80
+ const node = doc.createElement(tag);
81
+ if (className)
82
+ node.className = `stepr-checklist__${className}`;
83
+ return node;
84
+ };
85
+ instanceCount += 1;
86
+ const id = `stepr-checklist-${String(instanceCount)}`;
87
+ const root = el('section');
88
+ root.className = 'stepr-checklist';
89
+ root.setAttribute('aria-labelledby', `${id}-title`);
90
+ const heading = el(`h${String(headingLevel)}`, 'title');
91
+ heading.id = `${id}-title`;
92
+ heading.textContent = title;
93
+ // Visible progress text doubles as a polite live region.
94
+ const progressText = el('p', 'progress-text');
95
+ progressText.id = `${id}-progress`;
96
+ progressText.setAttribute('role', 'status');
97
+ const progressBar = el('progress', 'progress');
98
+ progressBar.setAttribute('aria-labelledby', progressText.id);
99
+ root.append(heading, progressText, progressBar);
100
+ const items = new Map();
101
+ const { steps } = controller.getState();
102
+ if (steps.length > 0) {
103
+ const list = el('ol', 'steps');
104
+ const definitions = new Map(options.steps.map((step) => [step.id, step]));
105
+ for (const step of steps) {
106
+ const item = el('li', 'step');
107
+ item.dataset['stepId'] = step.id;
108
+ const actionable = definitions.get(step.id)?.onClick !== undefined;
109
+ const body = actionable ? el('button', 'action') : el('span', 'static');
110
+ if (body instanceof HTMLButtonElement) {
111
+ body.type = 'button';
112
+ body.addEventListener('click', () => {
113
+ controller.click(step.id);
114
+ });
115
+ }
116
+ const marker = el('span', 'marker');
117
+ marker.setAttribute('aria-hidden', 'true');
118
+ const label = el('span', 'label');
119
+ label.textContent = step.label;
120
+ const status = el('span', 'visually-hidden');
121
+ body.append(marker, label, status);
122
+ item.append(body);
123
+ list.append(item);
124
+ items.set(step.id, { item, status });
125
+ }
126
+ root.append(list);
127
+ }
128
+ // Updates existing nodes in place; never recreates them, so focus is kept.
129
+ const render = (state) => {
130
+ const { completed, total } = state.progress;
131
+ progressText.textContent = formatProgress(state.progress);
132
+ progressBar.max = Math.max(total, 1);
133
+ progressBar.value = completed;
134
+ for (const step of state.steps) {
135
+ const nodes = items.get(step.id);
136
+ if (!nodes)
137
+ continue;
138
+ nodes.item.toggleAttribute('data-completed', step.completed);
139
+ nodes.status.textContent = `, ${step.completed ? completedText : notCompletedText}`;
140
+ }
141
+ };
142
+ render(controller.getState());
143
+ const unsubscribe = controller.subscribe(render);
144
+ const releaseStyles = options.injectStyles === false ? undefined : acquireStyles(doc);
145
+ host.append(root);
146
+ let destroyed = false;
147
+ return {
148
+ ...controller,
149
+ element: root,
150
+ destroy() {
151
+ if (destroyed)
152
+ return;
153
+ destroyed = true;
154
+ unsubscribe();
155
+ root.remove();
156
+ releaseStyles?.();
157
+ },
158
+ };
159
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@stepr/checklist",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Lightweight, framework-agnostic onboarding checklist widget for the web.",
5
+ "keywords": [
6
+ "onboarding",
7
+ "checklist",
8
+ "onboarding-checklist",
9
+ "progress",
10
+ "widget",
11
+ "accessibility",
12
+ "typescript",
13
+ "framework-agnostic",
14
+ "vanilla-js"
15
+ ],
16
+ "homepage": "https://ahlgren1234.github.io/stepr-checklist/",
17
+ "bugs": "https://github.com/ahlgren1234/stepr-checklist/issues",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/ahlgren1234/stepr-checklist.git"
21
+ },
22
+ "license": "MIT",
23
+ "author": "Peter Anyawantana",
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "devDependencies": {
40
+ "@arethetypeswrong/cli": "^0.18.5",
41
+ "@eslint/js": "^10.0.1",
42
+ "eslint": "~10.14.0",
43
+ "globals": "^17.14.0",
44
+ "jsdom": "^31.0.1",
45
+ "prettier": "^3.10.1",
46
+ "publint": "^0.3.25",
47
+ "stepr": "0.1.0",
48
+ "typescript": "~6.0.3",
49
+ "typescript-eslint": "^8.72.2",
50
+ "vitest": "^5.1.0"
51
+ },
52
+ "scripts": {
53
+ "build": "node -e \"fs.rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
54
+ "typecheck": "tsc --noEmit",
55
+ "lint": "eslint .",
56
+ "format": "prettier --write .",
57
+ "format:check": "prettier --check .",
58
+ "test": "vitest run",
59
+ "test:watch": "vitest",
60
+ "test:built": "vitest run --config vitest.built.config.ts",
61
+ "demo": "pnpm build && node scripts/serve-demo.mjs",
62
+ "build:pages": "pnpm build && node scripts/build-pages.mjs",
63
+ "check:package": "publint --strict && attw --pack . --profile esm-only && node scripts/smoke-import.mjs",
64
+ "check": "pnpm typecheck && pnpm lint && pnpm format:check && pnpm test && pnpm build && pnpm test:built && pnpm check:package"
65
+ }
6
66
  }