knit-and-stitches 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 +21 -0
- package/README.md +286 -2
- package/dist/format.d.ts +5 -0
- package/dist/index.d.ts +11 -0
- package/dist/knit.d.ts +144 -0
- package/dist/knit.iife.js +8117 -0
- package/dist/knit.js +8114 -0
- package/dist/types.d.ts +65 -0
- package/dist/vite/sections-plugin.d.ts +24 -0
- package/dist/vite/sections-plugin.js +130 -0
- package/package.json +66 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Knit and Stitches contributors
|
|
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,287 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/logo-wordmark.svg" alt="Knit and Stitches" width="420" />
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<p align="center"><strong>Stitch landing pages together from plain HTML pieces.</strong></p>
|
|
6
|
+
|
|
7
|
+
# Knit and Stitches
|
|
8
|
+
|
|
9
|
+
Knit and Stitches has two parts:
|
|
10
|
+
|
|
11
|
+
- **The library** (`src/`, TypeScript): a small typed vocabulary over Alpine and htmx. `threadball`, `thread`, `tighten`, `loosen`, `block`, `knit` and `stitch` cover shared state, component state, persistence and data loading. `yarn build` bundles it, with its types, into `dist/`.
|
|
12
|
+
- **The example page** (`example/`): a full landing page built with the library. You knit small **components** (inputs, buttons, modals) into **sections**, and stitch sections into one page. A small Vite plugin (`vite/`) does the stitching at build time, so the output is plain, unminified HTML a backend developer can take over. Copy it as the starting point for a new microsite.
|
|
13
|
+
|
|
14
|
+
**Docs:** [How it is built](docs/ARCHITECTURE.md) · [Contributing](CONTRIBUTING.md) · [Code of conduct](CODE_OF_CONDUCT.md) · [License](LICENSE)
|
|
15
|
+
|
|
16
|
+
## The problem this solves
|
|
17
|
+
|
|
18
|
+
**Primary problem:** use Node libraries (Tailwind, Alpine (+ focus and persist), htmx, GSAP, Iconify) on plain, vanilla HTML without the overhead of a framework. No React/Vue/Astro, no templating engine, no runtime dependency beyond the libraries themselves. Vite only bundles; the output is ordinary HTML, CSS and JS that a backend developer can read and take over.
|
|
19
|
+
|
|
20
|
+
**What it gives you**
|
|
21
|
+
|
|
22
|
+
- **A small vocabulary instead of plumbing, typed.** Thread names and value types are checked at compile time: `tighten('nope', 1)` or `tighten('cartTotal', 3)` (a getter) do not compile, and `stitch<Post[]>()` types the loaded data.
|
|
23
|
+
- **One page, many variants.** Sections live in their own files and are switched on, off and reordered from `example/site.config.ts`. A new microsite is a copy of the example plus a config edit, not a rewrite.
|
|
24
|
+
- **HTML components without a framework.** `<x-input>`, `<x-button>`, `<x-modal>` and friends are plain HTML files expanded at build time, so the built page holds ordinary markup.
|
|
25
|
+
- **Only what is enabled ships.** Disabled sections are absent from the built HTML, and their scripts are never loaded. Stitching and component expansion are one small local Vite plugin with tests, no extra dependency.
|
|
26
|
+
- **Data loading in one spread.** `stitch()` fetches JSON through htmx with loading, error and teardown handled. Requests are limited to an allowlist of hosts.
|
|
27
|
+
- **Animations by attribute.** `data-anim` scroll-in presets (GSAP) and `hover-lift` / `press` transitions, skipped for visitors who prefer reduced motion.
|
|
28
|
+
- **Fail loudly, not silently.** A misspelled section or component, an unclosed tag or a missing marker stops the build with a message naming the problem. One broken section script does not take down the rest of the page.
|
|
29
|
+
- **Safer defaults.** The title and description are escaped, section names cannot reach outside the sections folder, and uploaded filenames are never inserted as HTML.
|
|
30
|
+
- **Form that works as a handoff.** Required fields and the image upload are enforced, a dropped image is actually submitted, and the `action` is a clear placeholder for the backend.
|
|
31
|
+
|
|
32
|
+
## Start a site
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
npm create knit-and-stitches@latest my-site
|
|
36
|
+
# or: npx create-knit-and-stitches my-site
|
|
37
|
+
# or: yarn create knit-and-stitches my-site
|
|
38
|
+
# or: pnpm create knit-and-stitches my-site
|
|
39
|
+
|
|
40
|
+
cd my-site
|
|
41
|
+
npm run dev
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
This gives you a small Vite project that runs the example landing page. Edit `site.config.ts`, `src/sections/` and `src/components/` to make it yours.
|
|
45
|
+
|
|
46
|
+
## How to use
|
|
47
|
+
|
|
48
|
+
1. Copy this repo for the new microsite and run `yarn install`.
|
|
49
|
+
2. Run `yarn dev` and open the URL it prints. It serves the example page.
|
|
50
|
+
3. Edit `example/site.config.ts`: title, description, favicon (a file in `example/public/`), theme and which sections to show.
|
|
51
|
+
4. Replace the placeholder content in `example/src/sections/*.html` with the real copy and images. Put images in `example/public/`.
|
|
52
|
+
5. Set the form's `action` in `example/src/sections/form.html` to the backend endpoint (it posts `multipart/form-data`, including the uploaded `image`).
|
|
53
|
+
6. Run `yarn build:example` and hand over the `example/dist/` folder. It is unminified so it stays readable.
|
|
54
|
+
|
|
55
|
+
Run `yarn typecheck` after changing TypeScript, and `yarn test` after changing the section and component plugin.
|
|
56
|
+
|
|
57
|
+
## Pick sections
|
|
58
|
+
|
|
59
|
+
Edit `example/site.config.ts`:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
export default {
|
|
63
|
+
title: 'Landing Page',
|
|
64
|
+
description: 'A landing page built with Knit and Stitches', // <meta name="description">
|
|
65
|
+
favicon: '/favicon.svg', // file in example/public/
|
|
66
|
+
theme: 'theme-b', // class on <html> and the CSS prefix
|
|
67
|
+
stitches: ['hero', 'content', 'shop', 'form', 'footer'], // sections on the page, in order
|
|
68
|
+
} satisfies SiteConfig;
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`title`, `theme` and `stitches` are required (the `SiteConfig` type checks this). `description` and `favicon` are optional: leave a key out and the matching tag in `example/index.html` is left as it is (an empty description, `/favicon.svg`).
|
|
72
|
+
|
|
73
|
+
Each name maps to `example/src/sections/<name>.html`. An unknown name fails the build and names the missing file. Names may use letters, digits, `-` and `_`. Restart `yarn dev` after editing the config (it restarts itself).
|
|
74
|
+
|
|
75
|
+
## Animations
|
|
76
|
+
|
|
77
|
+
Add `data-anim="<preset>"` to any element to animate it in once when it scrolls into view. Presets: `fade`, `fade-up`, `fade-down`, `fade-left`, `fade-right`, `zoom-in`, `zoom-out`. Optional, all in ms:
|
|
78
|
+
|
|
79
|
+
- `data-anim-duration="600"`
|
|
80
|
+
- `data-anim-delay="200"`
|
|
81
|
+
- `data-anim-stagger="100"`: animate the element's children one after another (for lists and grids) instead of the element itself
|
|
82
|
+
|
|
83
|
+
It runs on GSAP with ScrollTrigger and is skipped for visitors who prefer reduced motion. To add a preset, add a line to `presets` in `example/src/main.ts`.
|
|
84
|
+
|
|
85
|
+
Hover/press transitions are Tailwind utilities defined in `example/src/style.css`:
|
|
86
|
+
|
|
87
|
+
- `hover-lift`: card rises with a shadow on hover
|
|
88
|
+
- `press`: button brightens on hover and shrinks slightly when clicked
|
|
89
|
+
|
|
90
|
+
They take Tailwind variants, e.g. `lg:hover-lift`.
|
|
91
|
+
|
|
92
|
+
## Components
|
|
93
|
+
|
|
94
|
+
Small reusable pieces are HTML files in `example/src/components/`. Use one in a section as an `<x-name>` tag; the build replaces it with the file's markup, so the output is still plain HTML.
|
|
95
|
+
|
|
96
|
+
```html
|
|
97
|
+
<x-input label="Email" type="email" name="email" placeholder="Type your email" required />
|
|
98
|
+
<x-button type="submit" class="btn-primary w-full">Submit</x-button>
|
|
99
|
+
<x-modal name="details" labelledby="detailsTitle">
|
|
100
|
+
<x-modal-header id="detailsTitle" title="Details" />
|
|
101
|
+
<x-modal-body>…</x-modal-body>
|
|
102
|
+
</x-modal>
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
- Attributes become `{{name}}` in the component file. Values may use double quotes, single quotes or none. A bare attribute such as `required` fills in its own name; an attribute you leave out is empty.
|
|
106
|
+
- `{{attrs}}` receives every attribute the component file does not use by name, so `@click`, `x-on:*`, `data-*` and `aria-*` pass straight through (e.g. `<x-button @click="open = true">`).
|
|
107
|
+
- What goes between the tags fills `{{slot}}`. Components can be nested, including inside another of the same name.
|
|
108
|
+
- If a component uses `{{id}}` and you leave `id` out, it gets a unique one (`x-input-1`, `x-input-2`, …), so labels and inputs stay linked however many times the tag is used. Pass `id` when other markup needs to point at it.
|
|
109
|
+
- End a tag with `/>` or a matching `</x-name>`. An unknown or unclosed component fails the build and names the problem.
|
|
110
|
+
- Comments in a component file are usage notes and are dropped from the output. Each file starts with one listing its attributes, state and threads.
|
|
111
|
+
- A component with its own state puts `x-data="<name>"` on its root and ships `example/src/components/<name>.ts` calling `knit('<name>', ...)` (see [the knitting vocabulary](#the-knitting-vocabulary)).
|
|
112
|
+
|
|
113
|
+
| Component | Attributes |
|
|
114
|
+
|-----------|------------|
|
|
115
|
+
| `x-input` | `label`, `label-class`, `type`, `name`, `id` (optional), `placeholder`, `autocomplete`, `class`, `required` |
|
|
116
|
+
| `x-checkbox` | `name`, `id` (optional), `required`; slot = label text |
|
|
117
|
+
| `x-dropzone` | `label`, `name`, `id` (optional), `accept`, `required` (any number per page; state in `dropzone.ts`) |
|
|
118
|
+
| `x-button` | `type`, `class` (`btn-primary` or `btn-link`); slot = text |
|
|
119
|
+
| `x-modal` | `name` (open it with `tighten('modal', '<name>')`, close with `loosen('modal')`), `labelledby`; slot = header and body |
|
|
120
|
+
| `x-modal-header` | `id`, `title` |
|
|
121
|
+
| `x-modal-body` | slot = content |
|
|
122
|
+
| `x-posts` | `limit`, `class`; latest posts from JSONPlaceholder via htmx, click one to open the `post` modal |
|
|
123
|
+
| `x-spinner` | `label` (read by screen readers), `class` (size it, e.g. `size-10`) |
|
|
124
|
+
| `x-countdown` | `to` (date, e.g. `2077-12-31T00:00:00`; add `Z` or `+07:00` to fix the time zone), `label`, `class`; slot = message once the date has passed |
|
|
125
|
+
| `x-item-card` | `sku` (unique per item; keys the saved cart), `name`, `price` (a number), `class`; slot = description. Keeps its own quantity; "Add to cart" lifts it into the `cart` thread |
|
|
126
|
+
| `x-cart` | `title`, `class`; lists the `cart` thread with remove, total (`currency` thread) and clear |
|
|
127
|
+
|
|
128
|
+
To add one, create `example/src/components/<name>.html` and use `<x-name>`. Put `{{attrs}}` on the element that should receive extra attributes.
|
|
129
|
+
|
|
130
|
+
`x-input`, `x-checkbox`, `x-dropzone` and `x-button` pass extra attributes to their `<input>` or `<button>`.
|
|
131
|
+
|
|
132
|
+
The styles behind them are classes in `example/src/components.css` (`card`, `heading`, `subheading`, `text-muted`, `label`, `input`, `checkbox-field`, `dropzone`, `btn`, `btn-primary`, `btn-link`, `modal-*`). Change a style there and every use updates. Tailwind classes in the markup still override them.
|
|
133
|
+
|
|
134
|
+
## The knitting vocabulary
|
|
135
|
+
|
|
136
|
+
State and data loading use a few words from the library (`src/knit.ts`), so a page never touches Alpine's or htmx's plumbing directly. Import them from the package:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { threadball, thread, tighten, loosen, block, knit, stitch, allowHosts } from 'knit-and-stitches';
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
| Word | What it does |
|
|
143
|
+
|------|--------------|
|
|
144
|
+
| `threadball({ ... })` | Declares the shared state for the whole page (`example/src/threadball.ts`). Each key is a **thread**. |
|
|
145
|
+
| `thread('name')` | Reads a thread. In markup you can also just write its name. |
|
|
146
|
+
| `tighten('name', value)` | Sets a thread. Every component that reads it updates. |
|
|
147
|
+
| `loosen('name')` | Puts a thread back to its starting value. |
|
|
148
|
+
| `block(value)` | In `threadball()`: the thread keeps its value across reloads (saved in `localStorage`). |
|
|
149
|
+
| `knit('name', () => ({ ... }))` | Gives a component its own state, used in markup as `x-data="name"`. |
|
|
150
|
+
| `stitch({ get, params })` | Spread into a knit to load JSON: adds `status`, `data`, `error` and `pull()`. |
|
|
151
|
+
| `allowHosts('api.example.com')` | Lets `stitch` reach that host, besides the page's own (called in `example/src/main.ts`). |
|
|
152
|
+
| `stitches: [...]` | In `example/site.config.ts`: the sections on the page, in order. |
|
|
153
|
+
|
|
154
|
+
**Shared state** lives in one place. Register its type once, so every thread name and value is checked:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
// example/src/threadball.ts
|
|
158
|
+
const threads = {
|
|
159
|
+
modal: null as string | null, // which <x-modal> is open
|
|
160
|
+
selectedPost: null as Post | null,
|
|
161
|
+
cart: block<CartLine[]>([]),
|
|
162
|
+
get cartTotal(): number { return this.cart.reduce((sum, line) => sum + line.qty * line.price, 0); },
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
type ExampleThreads = typeof threads;
|
|
166
|
+
declare module 'knit-and-stitches' {
|
|
167
|
+
interface Threads extends ExampleThreads {}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
threadball(threads);
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
```html
|
|
174
|
+
<button @click="tighten('modal', 'details')">Open details</button>
|
|
175
|
+
<p x-text="selectedPost?.title"></p>
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Now `thread('cart')` is a `CartLine[]`, and `tighten('nope', 1)`, `tighten('modal', 42)` and `tighten('cartTotal', 3)` (a getter) are compile errors. Without the `Threads` step (plain JavaScript, the script-tag build) names are plain strings and values `unknown`.
|
|
179
|
+
|
|
180
|
+
**Keeping a thread across reloads:** wrap its starting value in `block()`. Blocking is what knitters do to set a finished piece so it keeps its shape.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
cart: block<CartLine[]>([]), // saved as "threadball:cart" in localStorage
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Every `tighten` and `loosen` is saved, so `loosen('cart')` empties the saved cart too. A saved value that cannot be read is dropped and the thread starts fresh. Only block plain data (arrays, objects, strings, numbers); it is stored as JSON.
|
|
187
|
+
|
|
188
|
+
**A component** gets its own state with `knit`, and talks to others only through threads. Inside its methods `this` is typed as the state plus Alpine's magics (`$el`, `$refs`, …):
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// example/src/components/counter.ts -> <div x-data="counter">
|
|
192
|
+
import { knit, tighten } from 'knit-and-stitches';
|
|
193
|
+
|
|
194
|
+
knit('counter', () => ({
|
|
195
|
+
count: 0,
|
|
196
|
+
add() { this.count++; },
|
|
197
|
+
showDetails() { tighten('modal', 'details'); },
|
|
198
|
+
}));
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
**Lifting state up.** Keep a value in the component while only it cares, and move it into a thread once another component needs it. `x-item-card` and `x-cart` in the `shop` section show this: each card keeps its own quantity, and "Add to cart" calls `tighten('cart', …)`. The cart and every card's "N in cart" line read that same thread, so none of them knows about the others. The `cart` thread is blocked, so the cart survives a reload.
|
|
202
|
+
|
|
203
|
+
Every file in `example/src/components/*.ts` is loaded automatically. Never write `x-data="{ … }"` in markup; make a `knit` instead.
|
|
204
|
+
|
|
205
|
+
**Loading data** is one spread. `stitch` makes the request through htmx, tracks loading, success and errors, and cancels the request if the component is removed. Its type arguments say what the URL returns and what `params()` reads from the knit:
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
// example/src/components/posts.ts
|
|
209
|
+
knit('posts', () => ({
|
|
210
|
+
...stitch<Post[], { limit: number }>({
|
|
211
|
+
get: 'https://jsonplaceholder.typicode.com/posts',
|
|
212
|
+
params() { return { _limit: this.limit }; },
|
|
213
|
+
}),
|
|
214
|
+
limit: 5,
|
|
215
|
+
more() { this.limit += 5; this.pull(); },
|
|
216
|
+
}));
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
```html
|
|
220
|
+
<p x-show="status === 'loading'">Loading…</p>
|
|
221
|
+
<p x-show="status === 'error'" x-text="error"></p>
|
|
222
|
+
<template x-for="post in data" :key="post.id">…</template>
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
It loads on start. If the knit has its own `init()`, call `this.pull()` there. Requests may only go to the page's own host and the hosts passed to `allowHosts()`; anything else ends in `status = 'error'` with a message naming the host to allow.
|
|
226
|
+
|
|
227
|
+
Mistakes fail loudly: besides the compile errors, `tighten('nope', 1)` in markup or plain JavaScript throws `Unknown settable thread "nope"`, and a missing `stitches` list stops the build.
|
|
228
|
+
|
|
229
|
+
## The library
|
|
230
|
+
|
|
231
|
+
`yarn build` bundles the library into `dist/`, with Alpine, htmx and `@alpinejs/persist` included, so a page needs nothing else:
|
|
232
|
+
|
|
233
|
+
- `dist/knit.js`: ES module, with type declarations (`dist/index.d.ts`)
|
|
234
|
+
- `dist/knit.iife.js`: for a plain `<script>` tag, exposes `window.Knit`
|
|
235
|
+
|
|
236
|
+
Both export the vocabulary, `money`, `Alpine` (call `Alpine.start()` once, after the threadball and every knit) and `htmx`. The types are exported too: `Threads`, `ThreadName`, `ThreadValue`, `SettableThreadName`, `KnitFactory`, `Stitch`, `StitchOptions`, `StitchParams`, `StitchStatus`.
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
import { threadball, block, knit, tighten, thread, Alpine } from 'knit-and-stitches';
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
```html
|
|
243
|
+
<body x-data="threadball">
|
|
244
|
+
<button x-data="liker" @click="like()">Like <span x-text="likes"></span></button>
|
|
245
|
+
|
|
246
|
+
<script src="knit.iife.js"></script>
|
|
247
|
+
<script>
|
|
248
|
+
const { threadball, block, knit, tighten, thread, Alpine } = Knit;
|
|
249
|
+
threadball({ likes: block(0) });
|
|
250
|
+
knit('liker', () => ({ like() { tighten('likes', thread('likes') + 1); } }));
|
|
251
|
+
Alpine.start(); // once, after the threadball and every knit
|
|
252
|
+
</script>
|
|
253
|
+
</body>
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Only the runtime is in the bundle: components, sections, styles, the sections plugin and the focus plugin (used by `x-modal`) belong to the example page.
|
|
257
|
+
|
|
258
|
+
## Add a section
|
|
259
|
+
|
|
260
|
+
1. Create `example/src/sections/<name>.html`. The root element needs `data-section="<name>"`.
|
|
261
|
+
2. Optional state: create `example/src/sections/<name>.ts` and call `knit('<name>', ...)` in it (use `x-data="<name>"` in the HTML). It is only loaded when the section is on the page. For DOM work outside Alpine, it may also export `init(root, Alpine)`, which runs once per matching element before Alpine starts.
|
|
262
|
+
3. Add `<name>` to `stitches` in `example/site.config.ts`.
|
|
263
|
+
|
|
264
|
+
A section can be listed more than once. Write `{{uid}}` where an id or name must differ per copy: it becomes `<name>-1`, `<name>-2`, … (the `form` section uses it for its agreement modal: `tighten('modal', 'agreement-{{uid}}')`).
|
|
265
|
+
|
|
266
|
+
## Commands
|
|
267
|
+
|
|
268
|
+
```bash
|
|
269
|
+
yarn dev # the example page, reloads when section or component files change
|
|
270
|
+
yarn build # the library: dist/knit.js, dist/knit.iife.js and .d.ts types
|
|
271
|
+
yarn build:example # the example page: example/dist/
|
|
272
|
+
yarn preview # serve example/dist/
|
|
273
|
+
yarn typecheck # type-check the library, example, plugin and configs
|
|
274
|
+
yarn test # tests for the section and component plugin
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
## Hosting under a subpath
|
|
278
|
+
|
|
279
|
+
Built asset URLs are absolute (`/assets/...`, `/favicon.svg`), so the page works at the domain root. For a subpath, set `base: '/sub/'` in `example/vite.config.ts` and prefix `favicon` in `example/site.config.ts` the same way (the favicon path is not rewritten by `base`).
|
|
280
|
+
|
|
281
|
+
## Contributing
|
|
282
|
+
|
|
283
|
+
Issues and pull requests are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) for setup and conventions, and follow the [code of conduct](CODE_OF_CONDUCT.md).
|
|
284
|
+
|
|
285
|
+
## License
|
|
286
|
+
|
|
287
|
+
[MIT](LICENSE)
|
package/dist/format.d.ts
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import Alpine from 'alpinejs';
|
|
2
|
+
import htmx from 'htmx.org';
|
|
3
|
+
declare global {
|
|
4
|
+
interface Window {
|
|
5
|
+
Alpine: typeof Alpine;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export { allowHosts, block, knit, loosen, stitch, thread, threadball, tighten } from './knit.js';
|
|
9
|
+
export { money } from './format.js';
|
|
10
|
+
export type { KnitFactory, SettableThreadName, Stitch, StitchOptions, StitchParams, StitchStatus, ThreadName, Threads, ThreadValue, } from './types.js';
|
|
11
|
+
export { Alpine, htmx };
|
package/dist/knit.d.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { KnitFactory, SettableThreadName, Stitch, StitchOptions, ThreadName, ThreadValue } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Let stitch() (and any htmx request) reach these hosts, besides the page's own.
|
|
4
|
+
* Call it before Alpine starts, e.g. at the top of the page's main script:
|
|
5
|
+
*
|
|
6
|
+
* allowHosts('jsonplaceholder.typicode.com', 'api.example.com:8443');
|
|
7
|
+
*
|
|
8
|
+
* A request to any other host is cancelled before it is sent, and stitch() reports
|
|
9
|
+
* "Host not allowed: …" naming the host to add.
|
|
10
|
+
*
|
|
11
|
+
* @param names hosts as in URL.host: host[:port], no protocol or path
|
|
12
|
+
*/
|
|
13
|
+
export declare function allowHosts(...names: string[]): void;
|
|
14
|
+
/**
|
|
15
|
+
* Keep a thread's value across page reloads. Use it only inside threadball():
|
|
16
|
+
*
|
|
17
|
+
* threadball({ cart: block<CartLine[]>([]) });
|
|
18
|
+
*
|
|
19
|
+
* Blocking is what knitters do to set a finished piece so it keeps its shape.
|
|
20
|
+
* block() only marks the starting value; threadball() unwraps it, then saves the thread to
|
|
21
|
+
* localStorage under "threadball:<name>" on every change and reads it back on the next visit.
|
|
22
|
+
* The value is stored as JSON, so block plain data only (arrays, objects, strings, numbers,
|
|
23
|
+
* booleans, null): Dates come back as strings, and functions or Maps are lost.
|
|
24
|
+
*
|
|
25
|
+
* Typed as returning `T` (not the marker it really returns) so getters in the same threadball
|
|
26
|
+
* can use the thread as its real type: by the time they run, threadball() has unwrapped it.
|
|
27
|
+
*
|
|
28
|
+
* @param value the starting value, used on a visitor's first visit and by loosen()
|
|
29
|
+
*/
|
|
30
|
+
export declare function block<T>(value: T): T;
|
|
31
|
+
/**
|
|
32
|
+
* Declare the page's shared state, once (example/src/threadball.ts). Each key is a thread:
|
|
33
|
+
*
|
|
34
|
+
* threadball({
|
|
35
|
+
* modal: null as string | null, // settable thread
|
|
36
|
+
* cart: block<CartLine[]>([]), // settable, and saved across reloads
|
|
37
|
+
* get cartCount() { return this.cart.length; }, // getter: read-only, recomputed when cart changes
|
|
38
|
+
* });
|
|
39
|
+
*
|
|
40
|
+
* What it does, in order:
|
|
41
|
+
* 1. Unwraps block() values and remembers which threads to save.
|
|
42
|
+
* 2. Copies every settable thread's starting value (structuredClone), so loosen() can restore it
|
|
43
|
+
* even after the live value was changed in place. Getters and functions are not settable.
|
|
44
|
+
* 3. Makes the object reactive (Alpine.reactive): reading a thread inside a component or getter
|
|
45
|
+
* subscribes to it, and changing it re-renders exactly those readers.
|
|
46
|
+
* 4. Restores and starts saving each blocked thread (Alpine.persist). A saved value that is not
|
|
47
|
+
* valid JSON is removed and the thread starts from its starting value instead.
|
|
48
|
+
* 5. Adds thread, tighten and loosen to the object and registers it as Alpine.data('threadball'),
|
|
49
|
+
* which the page mounts on <body x-data="threadball">. Every component is inside <body>, so
|
|
50
|
+
* markup can use thread names and these three functions directly.
|
|
51
|
+
*
|
|
52
|
+
* For typed thread names and values, also fill in the Threads interface (see types.ts).
|
|
53
|
+
*
|
|
54
|
+
* @param threads every shared value the page needs, by name
|
|
55
|
+
* @throws when called a second time (two threadballs would split the shared state)
|
|
56
|
+
*/
|
|
57
|
+
export declare function threadball(threads: object): void;
|
|
58
|
+
/**
|
|
59
|
+
* Read a thread. Getters work too (thread('cartTotal')).
|
|
60
|
+
*
|
|
61
|
+
* const lines = thread('cart'); // CartLine[], once Threads is filled in
|
|
62
|
+
*
|
|
63
|
+
* Called inside a component's getter, method or markup, it subscribes that spot to the thread,
|
|
64
|
+
* so it re-renders when the thread changes. In markup the bare name does the same: x-text="cartTotal".
|
|
65
|
+
*
|
|
66
|
+
* It returns the live value, not a copy: changing an object or array you got here changes the
|
|
67
|
+
* thread (and everyone reading it). Prefer building a new value and passing it to tighten(),
|
|
68
|
+
* so every change goes through one name-checked call that is easy to search for.
|
|
69
|
+
*
|
|
70
|
+
* @param name a thread declared in threadball()
|
|
71
|
+
* @returns the thread's current value
|
|
72
|
+
* @throws when the name is not declared in threadball(), or no threadball exists yet
|
|
73
|
+
*/
|
|
74
|
+
export declare function thread<K extends ThreadName>(name: K): ThreadValue<K>;
|
|
75
|
+
/**
|
|
76
|
+
* Set a thread. Every component reading it updates, and a blocked thread is saved.
|
|
77
|
+
*
|
|
78
|
+
* tighten('modal', 'details'); // open the "details" modal
|
|
79
|
+
* tighten('cart', [...thread('cart'), line]); // add a line to the cart
|
|
80
|
+
*
|
|
81
|
+
* Tightening is how one component "broadcasts" to others: it does not need to know who reads
|
|
82
|
+
* the thread. Works in markup too: @click="tighten('modal', 'details')".
|
|
83
|
+
*
|
|
84
|
+
* @param name a settable thread declared in threadball() (not a getter or function)
|
|
85
|
+
* @param value the new value; stored as given, not copied
|
|
86
|
+
* @throws when the name is undeclared, a getter or a function
|
|
87
|
+
*/
|
|
88
|
+
export declare function tighten<K extends SettableThreadName>(name: K, value: ThreadValue<K>): void;
|
|
89
|
+
/**
|
|
90
|
+
* Put a thread back to the starting value declared in threadball(). A blocked thread saves
|
|
91
|
+
* the reset too, so loosen('cart') also empties the saved cart.
|
|
92
|
+
*
|
|
93
|
+
* loosen('modal'); // close whichever modal is open (modal starts as null)
|
|
94
|
+
*
|
|
95
|
+
* Each call gives a fresh deep copy of the starting value, so changing the result in place can
|
|
96
|
+
* never alter what the next loosen() restores.
|
|
97
|
+
*
|
|
98
|
+
* @param name a settable thread declared in threadball()
|
|
99
|
+
* @throws when the name is undeclared, a getter or a function
|
|
100
|
+
*/
|
|
101
|
+
export declare function loosen(name: SettableThreadName): void;
|
|
102
|
+
/**
|
|
103
|
+
* Give a component its own state, used in markup as x-data="<name>". A thin name for
|
|
104
|
+
* Alpine.data, so components read the same as the rest of the vocabulary.
|
|
105
|
+
*
|
|
106
|
+
* knit('counter', () => ({ count: 0, add() { this.count++; } }));
|
|
107
|
+
* // <div x-data="counter"><button @click="add()" x-text="count"></button></div>
|
|
108
|
+
*
|
|
109
|
+
* The factory runs once per element, so two counters on a page have separate counts. Inside its
|
|
110
|
+
* methods `this` is typed as the state plus Alpine's magics ($el, $refs…). Values the markup
|
|
111
|
+
* passes in come through data-* attributes, read in init() (see example/src/components/item-card.ts).
|
|
112
|
+
* Optional hooks: init() runs when the element starts, destroy() when it is removed.
|
|
113
|
+
* State two or more components need belongs in a thread instead.
|
|
114
|
+
*
|
|
115
|
+
* @param name the x-data name; unique across the page
|
|
116
|
+
* @param state returns a fresh state object; receives the arguments of x-data="name(arg)"
|
|
117
|
+
* (see example/src/components/modal.ts)
|
|
118
|
+
*/
|
|
119
|
+
export declare function knit<State extends object, Args extends unknown[] = []>(name: string, state: KnitFactory<State, Args>): void;
|
|
120
|
+
/**
|
|
121
|
+
* Load JSON into a knit through htmx. Spread it into the state object:
|
|
122
|
+
*
|
|
123
|
+
* knit('items', () => ({
|
|
124
|
+
* ...stitch<Item[]>({ get: 'https://api.example.com/items', params(this: { page: number }) { return { page: this.page }; } }),
|
|
125
|
+
* page: 1,
|
|
126
|
+
* }));
|
|
127
|
+
*
|
|
128
|
+
* It adds (see the Stitch type):
|
|
129
|
+
* status 'idle' -> 'loading' -> 'success' or 'error'
|
|
130
|
+
* data the parsed JSON after a success, typed as `Data` (kept while the next request loads)
|
|
131
|
+
* error a readable message after a failure: "Request failed (404)", "Network error",
|
|
132
|
+
* "Request timed out", "Unexpected response" (not JSON) or "Host not allowed: …"
|
|
133
|
+
* pull() load again, e.g. after changing what params() returns
|
|
134
|
+
* init() calls pull(), so it loads on start. If the knit defines its own init(), that one
|
|
135
|
+
* wins (it comes later in the object): call this.pull() in it yourself.
|
|
136
|
+
* destroy() cancels a request still running when the element is removed.
|
|
137
|
+
*
|
|
138
|
+
* The request is a GET with params() as the query string; params() runs on every pull()
|
|
139
|
+
* with `this` as the knit. A host other than the page's own must be allowed with allowHosts().
|
|
140
|
+
* `Data` is not checked at runtime: it is what you promise the URL returns.
|
|
141
|
+
*
|
|
142
|
+
* @param options the URL and the query string builder
|
|
143
|
+
*/
|
|
144
|
+
export declare function stitch<Data = unknown, Self = unknown>({ get, params }: StitchOptions<Self>): Stitch<Data>;
|