File: DECISIONS.md

package info (click to toggle)
htmx 4.0.0-alpha8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 191,048 kB
  • sloc: javascript: 29,775; sh: 44; makefile: 7
file content (340 lines) | stat: -rw-r--r-- 9,872 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# htmx 4.0 Architectural Decisions

This file captures decisions made during architecture discussions. Written immediately to avoid loss during conversation compaction.

---

## IMPORTANT: Source Code Reference

**DO NOT use the local `src/htmx.js` file for reference.**

It contains a frankenstein of outdated rearchitecture attempts and old htmx 4.0 code. The authoritative htmx 4.0 source is at:
https://raw.githubusercontent.com/bigskysoftware/htmx/refs/heads/four/src/htmx.js

When mapping features, always reference the remote `four` branch, not local files.

---

## Core Philosophy

**Clean DOM, Lazy Evaluation.**

1. Stop storing library state on DOM nodes (`_htmx`)
2. Stop calculating logic before it's needed (no snapshot `ctx`)
3. Rely on live DOM as single source of truth

---

## Technical Pillars

### Pillar A: WeakMap for Internal State

Replace `element._htmx` with a global `WeakMap` keyed by element.

**What lives in WeakMap:**
- `AbortController` (for request queues)
- Event listeners (for cleanup)
- UI counters (indicator request counts)

**Benefits:**
- Zero memory leaks — element removal auto-GCs the WeakMap entry
- Clean DOM — no `_htmx` properties confusing users or breaking `JSON.stringify`

**Access pattern:** `element.state` on wrapped elements (TBD: exact API)

### Pillar B: JIT (Just-In-Time) Evaluation

Do NOT calculate `target`, `swap`, `select` at trigger time. Calculate at response time.

**Flow:**
1. **Trigger:** Create `Request`, attach `sourceElement`, fetch
2. **Response:** Fetch completes
3. **Resolution:** NOW ask the DOM for `hx-target`, `hx-swap`, etc.

**Benefits:**
- Resilience: If DOM changes during flight, we respect current state, not stale snapshot
- Simplicity: No massive state object passed through async gap

---

## Event Model

**7 events total** (simplified from current before:/after: pairs):

| Event | When | Detail |
|-------|------|--------|
| `htmx:init` | Once on startup | `{}` |
| `htmx:activate` | Element processed | `{ source: { element } }` |
| `htmx:deactivate` | Element cleanup | `{ source: { element } }` |
| `htmx:request` | Before fetch | `{ source, request, swap }` |
| `htmx:response` | After fetch | `{ source, request, response, swap }` |
| `htmx:swap` | DOM mutation | `{ source, request, response, swap }` |
| `htmx:done` | Cleanup (finally) | `{ source, request, response, swap, error }` |

**Note:** `source: { element, event }` groups the triggering element and DOM event together.

---

## Event Detail Structure

> **SUPERSEDED** - See SESSION PROGRESS below. We now use `source: { element, event }` at top level.

For request lifecycle events (`htmx:request`, `htmx:response`, `htmx:swap`, `htmx:done`):

```javascript
{
    source: {
        element: WrappedElement,  // the triggering element (wrapped)
        event: Event,             // the DOM event that triggered this
    },
    request: {
        method: 'GET',
        url: '/api/endpoint',
        headers: { ... },
        body: FormData,
        signal: AbortSignal,
        credentials: 'same-origin',
        mode: 'same-origin',
    },
    response: {
        status: 200,
        url: 'https://...',
        headers: { ... },         // lowercase keys
        text: '<div>...</div>',
    },
    swap: {
        method: 'innerHTML',
        target: '#selector',      // resolved JIT at swap time
        modifiers: { ... },
    }
}
```

**Key decision:** `source.element` and `source.event` — grouped together, not inside `request`.

---

## Kernel vs Features

**Kernel owns:**
- Activation/deactivation lifecycle
- Trigger binding (`hx-trigger` parsing)
- Verb extraction (`hx-get`, `hx-post`, etc.)
- Request execution (fetch)
- Swap mechanism and defaults
- Event dispatching

**Features are middleware** — they hook into events and modify `request`/`response`/`swap`.

---

## Config Structure

> **SUPERSEDED** - See SESSION PROGRESS below for latest config structure.

**Kernel config** (`htmx.config`):

```javascript
htmx.config = {
    swap: {
        method: 'innerHTML',
        target: 'this',
        modifiers: {
            swapDelay: 0,
            settleDelay: 20,
            transition: false,
            ignoreTitle: false,
            scroll: null,
            show: null,
            focus: null
        }
    },

    trigger: {
        // NOTE: Still considering better naming
        fallback: 'click',
        elements: {
            'form': 'submit',
            'input:not([type=button])': 'change',
            'select': 'change',
            'textarea': 'change'
        }
    },

    request: {
        timeout: 60000,
        credentials: 'same-origin',
        mode: 'same-origin',
        encoding: null,
        headers: { ... }
    },

    syntax: {
        prefix: 'hx-',
        delimiter: ':',
        format: RelaxedJSON
    },

    inheritance: {
        enable: true,
        mode: 'explicit',       // 'explicit' = require marker, 'implicit' = always inherit
        marker: 'inherited'     // hx-target:inherited opts into inheritance
    },

    security: {
        allowEval: true,
        nonce: null,
        allowOrigins: null,
        trustedTypes: null
    },

    debug: false
}
```

**Removed from kernel config:**
- `morph` → separate feature with its own config
- `classes` → `injectStyles` feature owns these

---

## Single File Constraint

**Non-negotiable:** All code remains in one file: `htmx.js`

No separate directories, no module splitting.

---

## Wrapped Elements

Elements passed to features are wrapped with a Proxy providing:
- `element.attr(name, opts)` — attribute with inheritance
- `element.find(selector)` — extended selector support
- `element.findAll(selector)`
- `element.trigger(event, detail)`
- `element.is(other)` — identity comparison
- `element.native` — access underlying DOM element
- `element.state` — access WeakMap-backed state (TBD)

Wrapping is idempotent — safe to wrap multiple times.

---

## Naming Decisions

> **SUPERSEDED** - See SESSION PROGRESS below.

- ~~Use `sourceElement` not `source` (too ambiguous)~~ → Now use `source: { element, event }`
- ~~Use `request.element` not top-level `element`~~ → Now use `source.element`
- Use `swap.modifiers` namespace to separate "what" from "how" ✓

---

## Utilities Needed

- `htmx.inspect(element)` — debug utility to view WeakMap state (since `_htmx` is gone)

---

---

## SESSION PROGRESS (2026-01-26)

> **Note:** This section contains the latest decisions and supersedes some earlier sections above.
> See ARCHITECTURE_FULL.md for the actual code being developed.

Worked on ARCHITECTURE_FULL.md - rewriting as actual htmx.js code.

### COMPLETED

**Section 1: Core Data Structures**

1. **WeakMap State** - Namespaced structure:
   ```javascript
   state.get(element) = {
       trigger: { listeners, observers, intervals, timeouts },
       request: { queue, controller },
       cache: { etag },
   }
   ```

2. **Config Structure**:
   - `config.request` - credentials, mode, static headers (dynamic headers added by feature)
   - `config.swap` - method, target, modifiers (empty - features define defaults)
   - `config.trigger.events` - uses `*` wildcard for default:
     ```javascript
     events: {
         '*': 'click',
         'form': 'submit',
         'input:not([type=button]), select, textarea': 'change',
     }
     ```
   - `config.trigger.modifiers` - delay, throttle defaults
   - `config.syntax.format` - pluggable parser (RelaxedJSON default)

3. **Parse API**:
   ```javascript
   parse('innerHTML swap:100ms transition:true', 'method')
   // → { method: 'innerHTML', swap: '100ms', transition: 'true' }
   ```

4. **Event Detail** - `source: { element, event }` grouping:
   ```javascript
   {
       source: { element, event },  // Wrapped element + DOM event
       request,
       response,
       swap,
   }
   ```

5. **7 Events** - No before/after pairs:
   - htmx:init, htmx:activate, htmx:deactivate
   - htmx:request, htmx:response, htmx:swap, htmx:done

6. **Request Lifecycle** - Complete `issueRequest()` function with inline examples

### DECIDED BUT NOT YET IMPLEMENTED

1. **element.state proxy** - Wrapped elements should expose `.state`:
   ```javascript
   source.element.state.cache.etag = '...'
   // instead of
   state.get(source.element.native).cache.etag = '...'
   ```

2. **CSS classes out of kernel** - Move to `injectStyles` feature

3. **swap.modifiers empty** - Features define their own defaults, config just allows global overrides

4. **state.get() accepts wrapped or native** - Unwrap automatically if needed

### STILL DISCUSSING

1. **State attribute pattern** - Single `data-htmx="loading requesting"` attribute vs multiple classes. Leaning toward making this a feature, not kernel.

2. **replaceTitle timing** - htmx:swap vs htmx:response for extracting `<title>`

### TODO NEXT SESSION

1. Update Section 1 with `element.state` proxy
2. Remove `classes` from kernel config  
3. Make `swap.modifiers` empty with explanatory comment
4. Update features section to use new event names (htmx:request not htmx:before:request)
5. Design `stateAttribute` feature (if we go that route)
6. Update example features from user's local htmx.js to new patterns

### REFERENCE: User's Feature Examples

See ARCHITECTURE_FULL.md discussion - user shared local features:
- replaceTitle, executeScripts, injectStyles, etag, history
- Good patterns: `enable: true`, state attribute CSS, async history handling

---

## Open Questions

1. ~~Exact API for `element.state` WeakMap access~~ → DECIDED: `source.element.state.cache.etag`
2. ~~Better naming for `trigger.fallback` / `trigger.elements`~~ → DECIDED: `trigger.events` with `*` wildcard
3. ~~Should `htmx:swap` fire before AND after, or split into two events?~~ → DECIDED: Single event, features run in order