@stepr/checklist 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/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,546 @@
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.0, the first public 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
+ The [`demo/`](demo/) folder has an interactive page with no framework. It
25
+ shows a made-up app whose onboarding steps are completed by app events,
26
+ programmatic completion, `reset()`, `destroy()`, opt-in persistence, themes, a
27
+ [Stepr](https://github.com/ahlgren1234/stepr) tour started from a step, and
28
+ the README examples with copy buttons.
29
+
30
+ ```sh
31
+ pnpm install
32
+ pnpm demo # builds dist/, then serves http://localhost:4173/demo/
33
+ ```
34
+
35
+ The demo imports the **built package** (`dist/`) through an import map, using
36
+ the same `import … from '@stepr/checklist'` as the examples. Stepr is a
37
+ `devDependency` used only by the demo. It is not a dependency of the package.
38
+ `pnpm test:built` runs the demo and the README examples against `dist/` in
39
+ jsdom. The demo isn't deployed anywhere. The local server
40
+ ([`scripts/serve-demo.mjs`](scripts/serve-demo.mjs)) listens on `127.0.0.1`
41
+ only, and serves just the `.html`, `.css` and `.js` files in `demo/`, `dist/`
42
+ and `node_modules/stepr/dist/`. It refuses every other path, including
43
+ `.git`, `.env` and config files.
44
+
45
+ ## Quick start
46
+
47
+ ```sh
48
+ npm install @stepr/checklist
49
+ ```
50
+
51
+ With a bundler, `import` it as usual. Without one, map the package name in an
52
+ [import map][import-maps] and serve the page over HTTP, because ES modules
53
+ don't load from `file://`:
54
+
55
+ <!-- example: quickstart -->
56
+
57
+ ```html
58
+ <!doctype html>
59
+ <html lang="en">
60
+ <head>
61
+ <meta charset="utf-8" />
62
+ <title>Checklist</title>
63
+ <script type="importmap">
64
+ {
65
+ "imports": {
66
+ "@stepr/checklist": "/node_modules/@stepr/checklist/dist/index.js"
67
+ }
68
+ }
69
+ </script>
70
+ </head>
71
+ <body>
72
+ <div id="onboarding"></div>
73
+ <script type="module">
74
+ import { createChecklist } from '@stepr/checklist';
75
+
76
+ createChecklist({
77
+ container: '#onboarding',
78
+ title: 'Get started',
79
+ steps: [
80
+ {
81
+ id: 'profile',
82
+ label: 'Complete your profile',
83
+ onClick: (step, checklist) => checklist.complete(step.id),
84
+ },
85
+ { id: 'docs', label: 'Read the docs' },
86
+ ],
87
+ });
88
+ </script>
89
+ </body>
90
+ </html>
91
+ ```
92
+
93
+ [import-maps]: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type/importmap
94
+
95
+ ## Checklist widget
96
+
97
+ `createChecklist` renders an accessible checklist into an existing element and
98
+ returns the [controller API](#checklist-controller) plus `element` and
99
+ `destroy()`.
100
+
101
+ ```ts
102
+ import { createChecklist } from '@stepr/checklist';
103
+
104
+ const checklist = createChecklist({
105
+ container: '#onboarding', // or an HTMLElement
106
+ title: 'Get started',
107
+ steps: [
108
+ {
109
+ id: 'profile',
110
+ label: 'Complete your profile',
111
+ onClick: (step, checklist) => {
112
+ openProfileForm(); // activation never completes a step by itself
113
+ },
114
+ },
115
+ { id: 'invite', label: 'Invite a teammate', onClick: openInviteDialog },
116
+ { id: 'docs', label: 'Read the docs' }, // no onClick: rendered as text
117
+ ],
118
+ storageKey: 'my-app:onboarding', // optional, see Persistence
119
+ });
120
+
121
+ // Later, e.g. when the profile form is saved:
122
+ checklist.complete('profile');
123
+
124
+ checklist.destroy(); // removes the widget only
125
+ ```
126
+
127
+ | Option | Default | Description |
128
+ | -------------- | ------- | ------------------------------------------------------------------------------------- |
129
+ | `container` | — | `HTMLElement` or CSS selector (`document.querySelector`). The widget is **appended**. |
130
+ | `title` | — | Heading text and the accessible name of the widget's region. Must be non-empty. |
131
+ | `steps` | — | As for the controller. May be empty. |
132
+ | `headingLevel` | `2` | `1`–`6`; pick the level that fits your page outline. |
133
+ | `storageKey` | — | Opt-in `localStorage` persistence (see [Persistence](#persistence)). |
134
+ | `onChange` | — | Called after every state change. |
135
+ | `messages` | English | `{ progress(progress), completed, notCompleted }` text overrides for localization. |
136
+ | `injectStyles` | `true` | Insert the default stylesheet. Set `false` to style it yourself (e.g. strict CSP). |
137
+
138
+ Behavior:
139
+
140
+ - **Rendering:** a `<section>` labelled by its heading, a progress text
141
+ (`"1 of 3 steps complete"`), a native `<progress>` bar and an `<ol>` of
142
+ steps. Steps with `onClick` are native `<button type="button">`s, so mouse,
143
+ touch, Enter and Space all work; steps without `onClick` are plain text.
144
+ Titles and labels are rendered as text, never HTML.
145
+ - **Activation** calls the step's `onClick(step, checklist)` and **never**
146
+ changes completion. Call `checklist.complete(id)` when the task is actually
147
+ done (from `onClick` or anywhere else). Completed steps stay activatable.
148
+ - **Updates:** the widget updates its existing nodes in place on every state
149
+ change, so keyboard focus is not lost.
150
+ - **Errors:** `createChecklist` throws an `Error` — before touching the DOM — if
151
+ the container is not an element, the selector is invalid or matches nothing,
152
+ the title is empty, `headingLevel` is out of range, or the controller options
153
+ are invalid.
154
+ - **Empty steps:** renders the heading, `"No steps"` and an empty progress bar,
155
+ without a list.
156
+ - **Instances** are independent; element ids are unique per instance.
157
+ - **`destroy()`** removes the widget's own element and state subscription, and
158
+ removes the shared stylesheet when no other widget uses it. Other container
159
+ content is untouched. It is idempotent; the controller methods keep working
160
+ afterwards but nothing is rendered.
161
+ - `createChecklist` needs a DOM; importing the package does not.
162
+
163
+ ### Accessibility
164
+
165
+ - Each step's accessible name includes its state, e.g. "Complete your profile,
166
+ completed" (visually hidden text, customizable via `messages`). The visual
167
+ check mark is hidden from assistive technology.
168
+ - The progress text is a polite live region (`role="status"`), so changes are
169
+ announced without moving focus. The `<progress>` bar is labelled by it.
170
+ - Focus is shown with a visible `:focus-visible` outline; targets are at least
171
+ 44px tall; transitions are disabled under `prefers-reduced-motion`.
172
+ - With the default colors, the incomplete and completed step markers have at
173
+ least 3:1 contrast against the widget and hover backgrounds (see
174
+ [Styling](#styling)).
175
+ - No dialog, ARIA widget roles or custom key handling: only native elements.
176
+
177
+ What has been verified: the structure above (roles, names, live region,
178
+ focus retention) is covered by jsdom tests, and keyboard operation and focus
179
+ retention were checked in Playwright's bundled browsers (see
180
+ [Browser support](#browser-support)). It has **not** been tested with a screen
181
+ reader, and the widget hasn't been audited against WCAG. See
182
+ [docs/manual-testing.md](docs/manual-testing.md) for the manual keyboard and
183
+ screen-reader test.
184
+
185
+ ### Styling
186
+
187
+ The default stylesheet is inserted once at the start of `<head>` (so your own
188
+ rules of equal specificity win) and uses BEM-style classes such as
189
+ `.stepr-checklist`, `.stepr-checklist__step` and `.stepr-checklist__action`;
190
+ completed steps have a `data-completed` attribute. Theme it with these custom
191
+ properties on `.stepr-checklist` or any ancestor:
192
+
193
+ | Property | Default | Used for |
194
+ | ------------------------------------- | --------- | ------------------------------------------------------- |
195
+ | `--stepr-checklist-accent` | `#2563eb` | Completed marker, progress bar (`accent-color`) |
196
+ | `--stepr-checklist-accent-foreground` | `#ffffff` | Check mark glyph |
197
+ | `--stepr-checklist-background` | `#ffffff` | Widget background |
198
+ | `--stepr-checklist-foreground` | `#1f2937` | Text |
199
+ | `--stepr-checklist-muted` | `#4b5563` | Progress text, completed labels, incomplete marker ring |
200
+ | `--stepr-checklist-border` | `#d1d5db` | Widget border |
201
+ | `--stepr-checklist-hover` | `#f3f4f6` | Step background on hover |
202
+ | `--stepr-checklist-focus` | `#2563eb` | Focus outline |
203
+ | `--stepr-checklist-radius` | `0.5rem` | Widget corner radius (steps use 75% of it) |
204
+ | `--stepr-checklist-padding` | `1rem` | Widget padding |
205
+ | `--stepr-checklist-gap` | `0.5rem` | Spacing between parts (steps use half of it) |
206
+ | `--stepr-checklist-font-family` | `inherit` | Font |
207
+
208
+ <!-- example: theme -->
209
+
210
+ ```css
211
+ /* <div id="onboarding" class="theme-violet"></div> */
212
+ .theme-violet {
213
+ --stepr-checklist-accent: #6d28d9;
214
+ --stepr-checklist-focus: #6d28d9;
215
+ --stepr-checklist-background: #faf5ff;
216
+ --stepr-checklist-hover: #f3e8ff;
217
+ --stepr-checklist-border: #8b5cf6;
218
+ --stepr-checklist-radius: 1rem;
219
+ }
220
+ ```
221
+
222
+ With `injectStyles: false`, include the exported `checklistCss` string (or
223
+ your own styles) yourself, for example in a `<style>` with a CSP nonce or a
224
+ shadow root.
225
+
226
+ Check contrast when you change colors. A step's state is conveyed by its
227
+ accessible name and the progress text, but visually only by the marker and the
228
+ muted label color, so the marker should keep at least the 3:1 that WCAG 2.2
229
+ SC 1.4.11 asks of non-text indicators against both `background` and `hover`:
230
+
231
+ - The incomplete marker ring uses `muted` (default `#4b5563`: 7.6:1 on the
232
+ default background, 6.9:1 on the hover color).
233
+ - The completed marker is filled with `accent` (default `#2563eb`: 5.2:1 and
234
+ 4.7:1).
235
+ - The widget border (`#d1d5db`, about 1.5:1) is decorative and doesn't convey
236
+ state.
237
+
238
+ `test/styles.test.ts` checks these default ratios.
239
+
240
+ ## Checklist controller
241
+
242
+ The core is a DOM-free state controller that the widget is built on; it can
243
+ also be used directly to build your own UI.
244
+
245
+ ```ts
246
+ import { createChecklistController } from '@stepr/checklist';
247
+
248
+ const checklist = createChecklistController({
249
+ steps: [
250
+ {
251
+ id: 'profile',
252
+ label: 'Complete your profile',
253
+ onClick: (step, checklist) => {
254
+ openProfileForm(); // completion is up to you:
255
+ // checklist.complete(step.id);
256
+ },
257
+ },
258
+ { id: 'invite', label: 'Invite a teammate' },
259
+ ],
260
+ onChange: (state) => console.log(state.progress), // { completed, total }
261
+ });
262
+
263
+ checklist.complete('invite'); // true
264
+ checklist.getProgress(); // { completed: 1, total: 2 }
265
+ const unsubscribe = checklist.subscribe((state) => render(state));
266
+ ```
267
+
268
+ | Method | Behavior |
269
+ | ----------------- | ------------------------------------------------------------------------------------------- |
270
+ | `complete(id)` | Marks a step complete. Returns `true` if state changed, `false` if it was already complete. |
271
+ | `uncomplete(id)` | Marks a step incomplete. Returns `true` if state changed, `false` if it was not complete. |
272
+ | `reset()` | Marks every step incomplete. Returns `true` if anything was complete. |
273
+ | `click(id)` | Calls the step's `onClick(step, checklist)`, if any. **Never changes completion.** |
274
+ | `isCompleted(id)` | Whether a step is complete. |
275
+ | `getProgress()` | `{ completed, total }`. |
276
+ | `getState()` | Fresh snapshot: `{ steps: [{ id, label, completed }], progress }`, in definition order. |
277
+ | `subscribe(fn)` | Calls `fn(state)` after every change. Returns an unsubscribe function. |
278
+
279
+ Behavior details:
280
+
281
+ - **Step ids** must be non-empty strings, unique within a checklist. Duplicate
282
+ or empty ids throw when the controller is created.
283
+ - **Unknown ids** passed to `complete`, `uncomplete`, `click` or `isCompleted`
284
+ throw an `Error` and leave state unchanged.
285
+ - **Repeated actions** (completing a complete step, resetting an empty
286
+ checklist, …) are no-ops: they return `false` and send no notification.
287
+ - **Empty checklists** are allowed; progress is `{ completed: 0, total: 0 }`.
288
+ - **Notifications** are sent synchronously after each actual change: first
289
+ `onChange`, then subscribers in subscription order. Listeners added during a
290
+ notification receive the next one. If listeners throw, the others are still
291
+ called, then the error is rethrown (an `AggregateError` if several threw);
292
+ the state change itself is kept.
293
+ - **Instances** are fully independent; there is no shared module state.
294
+ - Steps are copied on creation, and snapshots are fresh objects, so mutating
295
+ either does not affect the controller. All steps start incomplete unless
296
+ restored from storage (see below).
297
+
298
+ ## Persistence
299
+
300
+ Pass `storageKey` to save progress in `localStorage`. Without it, the
301
+ controller is memory-only and never touches storage.
302
+
303
+ ```ts
304
+ const checklist = createChecklistController({
305
+ steps,
306
+ storageKey: 'my-app:onboarding',
307
+ });
308
+ ```
309
+
310
+ - **Restoring:** completed step ids are read once, when the controller is
311
+ created. Ids of steps that no longer exist are ignored. Restoring does not
312
+ call `onChange` or subscribers; read the initial state with `getState()`.
313
+ - **Saving:** the completed ids are written after every change made by
314
+ `complete`, `uncomplete` or `reset`, before listeners are notified. No-op
315
+ actions and `click` do not write.
316
+ - **Format:** `{"v":1,"completed":["id", ...]}` under the exact key you pass.
317
+ Choose an app-specific key to avoid collisions with other scripts on the
318
+ same origin. An empty `storageKey` throws.
319
+ - **Failures are non-fatal:** if `localStorage` is unavailable or blocked, the
320
+ stored value is malformed or from an unknown format version, or a write fails
321
+ (e.g. quota exceeded), the checklist silently continues in memory. Malformed
322
+ data is treated as "nothing stored".
323
+ - **Scope:** storage is per origin and per browser profile. It is not synced
324
+ across devices, and controllers sharing a key in different tabs do not update
325
+ each other live (the last write wins).
326
+ - `localStorage` is only accessed when a controller with a `storageKey` is
327
+ created or changed, never on import, so the package is safe to import during
328
+ server-side rendering.
329
+
330
+ ## Examples
331
+
332
+ All examples are plain JavaScript. They also work unchanged as TypeScript,
333
+ since the package ships its own types. Placeholders such as
334
+ `openProfileForm` stand for your app's code. `pnpm test:built` runs each of
335
+ these blocks against the built package, and checks that the demo shows the
336
+ same text.
337
+
338
+ ### Completing steps from your app
339
+
340
+ <!-- example: app-events -->
341
+
342
+ ```js
343
+ import { createChecklist } from '@stepr/checklist';
344
+
345
+ const checklist = createChecklist({
346
+ container: '#onboarding',
347
+ title: 'Get started',
348
+ steps: [
349
+ {
350
+ id: 'profile',
351
+ label: 'Complete your profile',
352
+ onClick: () => openProfileForm(), // opening the form does not complete it
353
+ },
354
+ { id: 'verify', label: 'Verify your email address' }, // text only
355
+ ],
356
+ onChange: ({ progress }) => {
357
+ if (progress.completed === progress.total) showAllDoneMessage();
358
+ },
359
+ });
360
+
361
+ // Complete steps when the work is actually done, from anywhere in your app:
362
+ onProfileSaved(() => checklist.complete('profile'));
363
+ onEmailVerified(() => checklist.complete('verify'));
364
+ ```
365
+
366
+ If a step's `onClick` moves focus, for example into a form, move it back
367
+ afterwards (the demo returns it to the step that opened the form). The widget
368
+ doesn't manage focus outside itself.
369
+
370
+ ### Persistence, reset and cleanup
371
+
372
+ <!-- example: persistence -->
373
+
374
+ ```js
375
+ import { createChecklist } from '@stepr/checklist';
376
+
377
+ const checklist = createChecklist({
378
+ container: '#onboarding',
379
+ title: 'Get started',
380
+ steps: [
381
+ { id: 'profile', label: 'Complete your profile' },
382
+ { id: 'invite', label: 'Invite a teammate' },
383
+ ],
384
+ storageKey: 'my-app:onboarding', // restored on creation, saved on change
385
+ });
386
+
387
+ checklist.complete('invite'); // true, and saved
388
+ checklist.complete('invite'); // false: already complete, nothing saved
389
+ checklist.getProgress(); // { completed: 1, total: 2 }
390
+
391
+ checklist.reset(); // marks every step incomplete, and saves that
392
+ checklist.destroy(); // removes the widget; saved progress is kept
393
+ localStorage.removeItem('my-app:onboarding'); // forget saved progress
394
+ ```
395
+
396
+ ### Starting a Stepr tour from a step
397
+
398
+ [Stepr](https://github.com/ahlgren1234/stepr) is a separate tour library.
399
+ `@stepr/checklist` doesn't import it or depend on it. Install it yourself
400
+ (`npm install stepr`) if you want tours, and connect the two in your app:
401
+
402
+ <!-- example: stepr -->
403
+
404
+ ```js
405
+ import { createChecklist } from '@stepr/checklist';
406
+ import { createTour } from 'stepr';
407
+
408
+ const tour = createTour({
409
+ steps: [
410
+ { target: '#new-project', title: 'Projects', description: 'Start here.' },
411
+ { target: '#invite', title: 'Invite your team' },
412
+ ],
413
+ onComplete: () => checklist.complete('tour'), // finished: tick it off
414
+ onExit: () => {}, // closed early: the step stays incomplete
415
+ });
416
+
417
+ const checklist = createChecklist({
418
+ container: '#onboarding',
419
+ title: 'Get started',
420
+ steps: [
421
+ {
422
+ id: 'tour',
423
+ label: 'Take the product tour',
424
+ onClick: () => {
425
+ if (!tour.start()) console.warn('No tour target is visible');
426
+ },
427
+ },
428
+ ],
429
+ });
430
+ ```
431
+
432
+ - The step's `onClick` starts the tour. Only the tour's `onComplete`, which
433
+ runs when the user passes the last step, completes the checklist step.
434
+ Close or Escape calls `onExit` and leaves the step open, so the user can
435
+ retry.
436
+ - `tour.start()` returns `false` when none of the tour's targets is rendered.
437
+ Handle that case, for example by completing the step anyway or showing help.
438
+ - When the tour ends, Stepr returns focus to the element that was focused
439
+ before `start()`. For a step activated from the keyboard, that is the step's
440
+ button.
441
+ - Stepr has its own accessibility notes and limitations; see its README. The
442
+ pairing was exercised in the demo with Stepr 0.1.0.
443
+
444
+ ## Limitations
445
+
446
+ - **Early 0.x release.** Minor versions may contain breaking changes.
447
+ - **Steps are fixed at creation.** To add, remove or relabel steps, `destroy()`
448
+ the widget and create a new one. Labels are plain text; there are no
449
+ descriptions, icons or links inside steps.
450
+ - **No built-in reset, dismiss, collapse or "hide when done" UI.** Use the API
451
+ (as the demo does) and your own controls.
452
+ - **Default text is English.** Override it with `messages`.
453
+ - **Light default theme only.** There is no automatic dark mode; use the
454
+ custom properties. See the contrast note under [Styling](#styling).
455
+ - **Shadow DOM:** the default stylesheet goes into the document's `<head>`, so
456
+ it doesn't reach a widget inside a shadow root. Use `injectStyles: false` and
457
+ add `checklistCss` to the shadow root yourself. A string `container` is
458
+ resolved with `document.querySelector` and doesn't look inside shadow roots.
459
+ - **Element ids** are `stepr-checklist-<n>`, counted per copy of the package.
460
+ Two separately bundled copies on one page could produce duplicate ids.
461
+ - **Persistence** is `localStorage` only: per origin and browser, not synced
462
+ across devices or live across tabs. See [Persistence](#persistence).
463
+ - **Page styles can leak in.** The defaults use single-class selectors, so
464
+ your page rules with higher specificity, such as `.sidebar h2 { … }`, also
465
+ restyle the widget's heading and buttons. Scope such rules, as the demo
466
+ does with `.section > h2`.
467
+ - **Rendering needs a DOM.** Importing is safe during server-side rendering,
468
+ but there is no server-rendered markup.
469
+
470
+ ## Browser support
471
+
472
+ No browser support matrix has been tested, so no minimum versions are claimed.
473
+ The package is compiled to ES2022 and the widget uses native `<button>`,
474
+ `<progress>`, `:focus-visible`, `accent-color`, `clip-path: inset()` and
475
+ `Element.toggleAttribute`. Check these against your own support targets. The
476
+ no-bundler setup also needs [import maps][import-maps].
477
+
478
+ Evidence so far (2026-11-14, Linux/WSL2), from an ad-hoc Playwright 1.63
479
+ script that is not part of the repository. It used Playwright's bundled
480
+ **Chromium 153**, **Firefox 155** and **WebKit 26.6**, which are close to but
481
+ not the same as Chrome, Firefox and Safari. In all three, the demo:
482
+
483
+ - loaded with no console or page errors at 1280, 768, 375 and 320px wide, with
484
+ no horizontal scrolling and step buttons at least 44px tall
485
+ - moved Tab focus through the four step buttons in order and skipped the
486
+ text-only step, showing a 2px solid focus outline
487
+ - activated steps with Enter and Space, kept focus on the step after
488
+ completing it, and updated the progress text
489
+ - completed the Stepr tour step with the keyboard and returned focus to the
490
+ step afterwards. Escape closed the tour early.
491
+ - restored persisted progress after a reload and cleared it when turned off
492
+ - had no step transition with reduced motion emulated
493
+ - copied an example to the clipboard (Chromium only; the other engines weren't
494
+ checked)
495
+
496
+ Not tested: real Chrome, Edge, Safari or Firefox builds, macOS, Windows,
497
+ iOS, Android, touch input, zoom, forced colors / high contrast, and any
498
+ screen reader. See [docs/manual-testing.md](docs/manual-testing.md).
499
+
500
+ ## Assumptions
501
+
502
+ - **ESM only.** Published as native ES modules with TypeScript declarations;
503
+ no CommonJS build. CommonJS consumers can use dynamic `import()`.
504
+ - **No runtime dependencies.** Development tooling only.
505
+ - **Browser-first.** Compiled to ES2022 for modern browsers. The package
506
+ declares no Node.js `engines` requirement, since it only needs Node.js when
507
+ imported during server-side rendering or tests (verified with Node.js 24 and
508
+ 26).
509
+ - **Development** uses **Node.js 24** (see `.nvmrc`; CI uses the same) and
510
+ **pnpm** (version pinned via `packageManager`; enable with
511
+ `corepack enable`).
512
+ - **TypeScript 6.0.x**, since `typescript-eslint` does not yet support TypeScript 7.
513
+ - The build is plain `tsc`; a bundler can be introduced later if needed.
514
+
515
+ ## Development
516
+
517
+ ```sh
518
+ corepack enable
519
+ pnpm install
520
+
521
+ pnpm typecheck # type-check sources and tests
522
+ pnpm lint # ESLint (typescript-eslint, strict type-checked)
523
+ pnpm format # format with Prettier (pnpm format:check to verify)
524
+ pnpm test # run tests with Vitest + jsdom (pnpm test:watch for watch mode)
525
+ pnpm build # compile to dist/ with declarations
526
+ pnpm test:built # run the demo and README examples against dist/ (jsdom)
527
+ pnpm check:package # publint + attw + install/import the packed tarball in a clean consumer
528
+ pnpm check # all of the above, as run in CI
529
+ pnpm demo # build, then serve the demo at http://localhost:4173/demo/
530
+ ```
531
+
532
+ `pnpm test:built` and `pnpm check:package` require a prior `pnpm build`. CI
533
+ runs every check on pull requests and pushes to `main`; it never publishes or
534
+ deploys.
535
+
536
+ `pnpm pack` builds `dist/` first (`prepack`). Releases are published by hand;
537
+ see [docs/releasing.md](docs/releasing.md).
538
+
539
+ ## Contributing
540
+
541
+ Work on a feature branch, run `pnpm check` before opening a pull request, and
542
+ reference the relevant issue.
543
+
544
+ ## License
545
+
546
+ [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,65 @@
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.0",
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://github.com/ahlgren1234/stepr-checklist#readme",
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
+ "check:package": "publint --strict && attw --pack . --profile esm-only && node scripts/smoke-import.mjs",
63
+ "check": "pnpm typecheck && pnpm lint && pnpm format:check && pnpm test && pnpm build && pnpm test:built && pnpm check:package"
64
+ }
6
65
  }