@cossackframework/renderer 0.8.3 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -29
- package/agent-docs.json +121 -0
- package/dist/attributes.d.ts +824 -0
- package/dist/attributes.js +1 -0
- package/dist/browser-ssr.d.ts +5 -0
- package/dist/browser-ssr.js +7 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +11 -0
- package/dist/component-tags.d.ts +69 -0
- package/dist/component-tags.js +106 -0
- package/dist/cossack-element.d.ts +36 -2
- package/dist/cossack-element.js +26 -28
- package/dist/cossack-html.d.ts +23 -5
- package/dist/cossack-html.js +1059 -551
- package/dist/css-result.d.ts +9 -0
- package/dist/css-result.js +14 -0
- package/dist/css-scoping.d.ts +4 -0
- package/dist/css-scoping.js +95 -0
- package/dist/css.d.ts +3 -16
- package/dist/css.js +13 -111
- package/dist/diagnostics.d.ts +85 -0
- package/dist/diagnostics.js +465 -0
- package/dist/directives.d.ts +13 -7
- package/dist/directives.js +7 -7
- package/dist/index.d.ts +2 -0
- package/dist/index.js +9 -7
- package/dist/minify-html.d.ts +22 -0
- package/dist/minify-html.js +123 -18
- package/dist/server.d.ts +3 -1
- package/dist/server.js +6 -4
- package/dist/ssr-form-values.d.ts +2 -0
- package/dist/ssr-form-values.js +72 -0
- package/dist/style-registry.d.ts +42 -0
- package/dist/style-registry.js +73 -0
- package/dist/style-runtime.d.ts +47 -0
- package/dist/style-runtime.js +43 -0
- package/dist/template-analysis.d.ts +224 -0
- package/dist/template-analysis.js +321 -0
- package/dist/template-parse.d.ts +157 -0
- package/dist/template-parse.js +526 -0
- package/dist/template.d.ts +2 -0
- package/dist/template.js +3 -0
- package/package.json +26 -6
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Cossack Renderer Package
|
|
2
2
|
|
|
3
|
-
Cossack Renderer is a Lit-compatible rendering engine for
|
|
4
|
-
|
|
3
|
+
Cossack Renderer is a Lit-compatible rendering engine for Light DOM and
|
|
4
|
+
SSR. It returns HTML strings for SSR and updates the DOM without Shadow DOM
|
|
5
5
|
isolation.
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
@@ -80,6 +80,17 @@ const htmlString = renderToString(app.render());
|
|
|
80
80
|
console.log(htmlString);
|
|
81
81
|
```
|
|
82
82
|
|
|
83
|
+
Component styles are not part of that string. To serve a page with styled
|
|
84
|
+
components, collect the styles the render used and put them in `<head>`
|
|
85
|
+
(the Cossack framework does this for every SSR and SSG page):
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
import { collectComponentStyles, renderComponentStyles, renderToString } from '@cossackframework/renderer/server';
|
|
89
|
+
|
|
90
|
+
const { result: body, styles } = collectComponentStyles(() => renderToString(page, { hydrate: true }));
|
|
91
|
+
const head = renderComponentStyles(styles); // one <style data-cossack-style="…"> per scope
|
|
92
|
+
```
|
|
93
|
+
|
|
83
94
|
## Template Syntax
|
|
84
95
|
|
|
85
96
|
Cossack uses tagged template literals via `html`.
|
|
@@ -92,7 +103,30 @@ html`<h1>Hello ${name}</h1>`
|
|
|
92
103
|
|
|
93
104
|
### Attributes
|
|
94
105
|
|
|
95
|
-
|
|
106
|
+
A binding that is an attribute's whole value (`title=${x}` or
|
|
107
|
+
`title="${x}"`) removes the attribute when the value is `null`, `undefined`
|
|
108
|
+
or `nothing`. HTML boolean attributes such as `hidden` are present for `true`
|
|
109
|
+
and removed for `false`; other attributes get the text `"true"` or `"false"`.
|
|
110
|
+
|
|
111
|
+
An attribute value that mixes bindings with static text, or has several
|
|
112
|
+
bindings, is text:
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
html`<svg viewBox="0 0 ${size} ${size}"></svg>`
|
|
116
|
+
html`<button class="btn btn-${variant}">Save</button>`
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- Each binding adds its value as text. `null`, `undefined`, functions and
|
|
120
|
+
`ifDefined(undefined)` add nothing. Booleans and numbers add `String(value)`.
|
|
121
|
+
- `nothing` in any of the bindings removes the whole attribute.
|
|
122
|
+
- The client writes the attribute once per render, after all of its bindings
|
|
123
|
+
have their new values, and only when the assembled text changed. The
|
|
124
|
+
browser never sees a value with only some bindings filled in.
|
|
125
|
+
|
|
126
|
+
SSR, hydration and client updates follow the same rules.
|
|
127
|
+
|
|
128
|
+
A `?name` binding sets a boolean attribute: present when the value is
|
|
129
|
+
truthy, removed otherwise.
|
|
96
130
|
|
|
97
131
|
```typescript
|
|
98
132
|
html`<button ?disabled="${isDisabled}">Click</button>`
|
|
@@ -108,7 +142,7 @@ html`<button @click="${(e) => this.handleClick(e)}">Click Me</button>`
|
|
|
108
142
|
|
|
109
143
|
### Property Binding
|
|
110
144
|
|
|
111
|
-
For `<input>` elements, use `.` prefix to bind properties directly.
|
|
145
|
+
For `<input>` elements, use the `.` prefix to bind properties directly.
|
|
112
146
|
|
|
113
147
|
```typescript
|
|
114
148
|
html`<input type="text" .value="${this.inputValue}" @input="${this.handleInput}" />`
|
|
@@ -123,9 +157,34 @@ const props = { id: 'btn', class: 'primary', 'data-type': 'action' };
|
|
|
123
157
|
html`<button ...=${props}>Click</button>`
|
|
124
158
|
```
|
|
125
159
|
|
|
160
|
+
Keys can be attributes (`id`), boolean attributes (`?disabled`), properties
|
|
161
|
+
(`.value`) and events (`@click`). An element can have several spreads. SSR,
|
|
162
|
+
hydration and client updates apply them with the same rules:
|
|
163
|
+
|
|
164
|
+
- **A later spread wins.** When two spreads set the same attribute, boolean
|
|
165
|
+
attribute or property, the value of the later spread is used. If the later
|
|
166
|
+
spread drops the key, the earlier spread's value applies again.
|
|
167
|
+
- **A spread overrides the template.** A spread key replaces an attribute
|
|
168
|
+
with the same name written in the template, whichever side of the spread it
|
|
169
|
+
is on. When the key is dropped, the template's value comes back. A value of
|
|
170
|
+
`null`, `undefined`, `nothing`, `false` (for a boolean attribute) or a
|
|
171
|
+
function removes the attribute.
|
|
172
|
+
- **Classes merge.** `class` and `className` keys add their tokens to the
|
|
173
|
+
element's own class, in spread order. They do not replace it.
|
|
174
|
+
- **Every event handler runs.** Each spread adds its own listener for its
|
|
175
|
+
event keys. If two spreads set `@click`, both handlers run.
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
// Renders <button class="cs-button primary" id="save" type="button">.
|
|
179
|
+
html`<button class="cs-button" ...=${{ id: 'save', type: 'submit', class: 'primary' }} ...=${{ type: 'button' }}>Save</button>`
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Do not combine a spread key with a bound attribute of the same name, such as
|
|
183
|
+
`id=${id}` next to a spread that sets `id`. That result is not defined.
|
|
184
|
+
|
|
126
185
|
### Unsafe HTML
|
|
127
186
|
|
|
128
|
-
|
|
187
|
+
Render a raw HTML string with `unsafeHTML`. Do not pass untrusted input to it:
|
|
129
188
|
|
|
130
189
|
```typescript
|
|
131
190
|
import { unsafeHTML } from '@cossackframework/renderer';
|
|
@@ -211,7 +270,7 @@ class Notice extends CossackElement {
|
|
|
211
270
|
}
|
|
212
271
|
```
|
|
213
272
|
|
|
214
|
-
Style arrays
|
|
273
|
+
Style arrays can be nested. They are flattened in declaration order, and the
|
|
215
274
|
last occurrence of the same `CSSResult` wins. A subclass can extend inherited
|
|
216
275
|
styles explicitly:
|
|
217
276
|
|
|
@@ -222,12 +281,42 @@ class EmphasizedNotice extends Notice {
|
|
|
222
281
|
```
|
|
223
282
|
|
|
224
283
|
Cossack scopes selectors by adding deterministic `data-cossack-scope`
|
|
225
|
-
attributes to elements created by that component
|
|
226
|
-
|
|
227
|
-
|
|
284
|
+
attributes to elements created by that component. Each style scope has one
|
|
285
|
+
managed `<style data-cossack-style="<scope id>">` element per page, however
|
|
286
|
+
many instances render. Scope ids hash the CSS, so classes with identical
|
|
287
|
+
styles share one. Conditional at-rules and functional selectors are scoped
|
|
288
|
+
recursively. Keyframe names and matching animation declarations are
|
|
228
289
|
rewritten. `:host`, `:host-context`, and `::slotted` are rejected because
|
|
229
290
|
Cossack uses Light DOM rather than Shadow DOM.
|
|
230
291
|
|
|
292
|
+
Where the style elements live:
|
|
293
|
+
|
|
294
|
+
- **SSR and SSG** emit them in `<head>`, after the application CSS, in the
|
|
295
|
+
order the render first used each scope (see `collectComponentStyles()`).
|
|
296
|
+
- **On the client** a registry counts the rendered instances per scope. It
|
|
297
|
+
adopts the server-rendered head styles on hydration, inserts a scope's style
|
|
298
|
+
in `<head>` when its first instance renders (before `updated()` runs and
|
|
299
|
+
before paint), and removes it a task after its last instance is gone, so a
|
|
300
|
+
client navigation keeps every style the next page also uses.
|
|
301
|
+
- **Inside a shadow root** components get their own copy at the start of that
|
|
302
|
+
shadow root, counted separately from the document.
|
|
303
|
+
|
|
304
|
+
Ordering caveat: scoped rules only match elements that carry their own scope,
|
|
305
|
+
so the order of two components' styles only matters for global at-rules
|
|
306
|
+
(`@font-face`, `@property`, `@counter-style`, `@layer` order) and for selectors
|
|
307
|
+
you scope by hand. Those follow first-use order: a scope first used later in
|
|
308
|
+
the page, or first inserted by a client render, comes later in `<head>`, and a
|
|
309
|
+
scope keeps its place while any instance remains. Keep conflicting global
|
|
310
|
+
at-rules in the application stylesheet.
|
|
311
|
+
|
|
312
|
+
Migration note: component outputs used to begin with their own `<style>`
|
|
313
|
+
element. Structural selectors now match as written, because no style element
|
|
314
|
+
sits between sibling component outputs anymore: `li + li`, `:first-child`,
|
|
315
|
+
`:last-child`, `:nth-child()`, `:empty` and Tailwind `first:`, `odd:`,
|
|
316
|
+
`even:`, `space-*` and `divide-*` see only the elements components render.
|
|
317
|
+
Review selectors that compensated for the old style siblings (for example
|
|
318
|
+
`:nth-child(2n)` used to select odd items).
|
|
319
|
+
|
|
231
320
|
Scoping follows template ownership. Nested components use their own scope, while
|
|
232
321
|
projected templates retain the scope of the component that created them. This
|
|
233
322
|
is attribute-based isolation, not a Shadow DOM security boundary: inherited CSS
|
|
@@ -236,38 +325,87 @@ are explicit escape hatches and are not guaranteed to receive scope attributes.
|
|
|
236
325
|
|
|
237
326
|
## Using Components in Templates
|
|
238
327
|
|
|
239
|
-
|
|
328
|
+
Write a child component as a component tag: bind the class in tag position.
|
|
240
329
|
|
|
241
330
|
```typescript
|
|
242
|
-
import {
|
|
331
|
+
import { html } from '@cossackframework/renderer';
|
|
243
332
|
import { ChildComponent } from './ChildComponent';
|
|
244
333
|
|
|
245
334
|
html`
|
|
246
335
|
<div class="parent">
|
|
247
|
-
|
|
336
|
+
<${ChildComponent} someProp="value" count=${3} @select=${(event: Event) => console.log(event.type)} />
|
|
248
337
|
</div>
|
|
249
338
|
`
|
|
250
339
|
```
|
|
251
340
|
|
|
252
|
-
|
|
341
|
+
Put children between the opening and closing tags. The closing tag binds the
|
|
342
|
+
same class:
|
|
253
343
|
|
|
254
344
|
```typescript
|
|
255
345
|
html`
|
|
256
346
|
<div class="parent">
|
|
257
|
-
|
|
347
|
+
<${ChildComponent} someProp="value">
|
|
258
348
|
<span>Child content</span>
|
|
259
|
-
|
|
349
|
+
</${ChildComponent}>
|
|
260
350
|
</div>
|
|
261
351
|
`
|
|
262
352
|
```
|
|
263
353
|
|
|
354
|
+
Attributes become the component's `props` the way `component()` takes them:
|
|
355
|
+
|
|
356
|
+
| Attribute | Prop |
|
|
357
|
+
| --- | --- |
|
|
358
|
+
| `name="text"` | `name: 'text'` (character references decoded) |
|
|
359
|
+
| `name` (bare) | `name: true` |
|
|
360
|
+
| `name=${value}` | `name: value`, any value |
|
|
361
|
+
| `name="a ${b}"` | `name: 'a …'`, text; `nothing` in it removes the prop |
|
|
362
|
+
| `.prop=${v}`, `?bool=${v}`, `@event=${f}` | the same key with its prefix |
|
|
363
|
+
| `...=${props}` | every key of `props`; later attributes override earlier ones |
|
|
364
|
+
|
|
365
|
+
Children become `children`: nothing for no content or whitespace, the text for
|
|
366
|
+
plain text, the value itself for one binding, and a template otherwise. Named
|
|
367
|
+
slots are props with template values: ``footer=${html`<p>…</p>`}``. Prop names
|
|
368
|
+
keep their case (`rowCount`, `getRowId`).
|
|
369
|
+
|
|
370
|
+
`html` compiles each component tag into the same result `component()` returns,
|
|
371
|
+
so rendering, SSR and hydration are identical. Keep `component(Class, props,
|
|
372
|
+
children)` for classes chosen at runtime, such as a component picked from a map.
|
|
373
|
+
Template holes are not contextually typed: annotate callback parameters, such as
|
|
374
|
+
`(value: string) => ...`, and write object props with `satisfies`, such as
|
|
375
|
+
`items=${[...] satisfies Item[]}`.
|
|
376
|
+
|
|
377
|
+
## Template Checks
|
|
378
|
+
|
|
379
|
+
`cossack check templates` and the Vite build check every `html` and `svg`
|
|
380
|
+
template with the project's TypeScript program, and report each problem with
|
|
381
|
+
its file, line and column. Errors fail the check and the build; the dev server
|
|
382
|
+
reports them as files change.
|
|
383
|
+
|
|
384
|
+
- Structure: unclosed or mismatched elements, `<div />` on HTML elements,
|
|
385
|
+
bindings that render nothing (in a comment, or `<div ${x}>`), and component
|
|
386
|
+
tags that do not close or close with another class.
|
|
387
|
+
- Binding forms: `name=`, `.property=`, `?boolean=`, `@event=` and `...=` only;
|
|
388
|
+
a prefixed binding takes one whole value.
|
|
389
|
+
- Markup in an untagged template literal, such as `` `<li>${x}</li>` `` in a
|
|
390
|
+
hole, which renders as text: tag it with `html`.
|
|
391
|
+
- Types: attribute names and values against the native attribute map
|
|
392
|
+
(`@cossackframework/renderer/attributes`), `@event` handlers against the
|
|
393
|
+
element's events, `?attr` as boolean, `.prop` against the element's property
|
|
394
|
+
type, and component tag attributes against the component's `props`. Unknown
|
|
395
|
+
elements accept global attributes, with a warning for others.
|
|
396
|
+
- Hints: `component()` with a literal class can be a component tag.
|
|
397
|
+
|
|
398
|
+
In the editor, `@cossackframework/typescript-plugin` shows the same diagnostics
|
|
399
|
+
and completes tag names, attributes, events, properties, component props and
|
|
400
|
+
enumerated values inside templates. Generated applications enable it.
|
|
401
|
+
|
|
264
402
|
## Directives
|
|
265
403
|
|
|
266
404
|
Cossack includes standard Lit directives.
|
|
267
405
|
|
|
268
406
|
### `repeat` (Keyed Lists)
|
|
269
407
|
|
|
270
|
-
|
|
408
|
+
Renders lists by key.
|
|
271
409
|
|
|
272
410
|
```typescript
|
|
273
411
|
import { repeat } from '@cossackframework/renderer';
|
|
@@ -294,6 +432,10 @@ const styles = { color: 'red', display: isVisible ? 'block' : 'none' };
|
|
|
294
432
|
html`<div class="${classMap(classes)}" style="${styleMap(styles)}">...</div>`
|
|
295
433
|
```
|
|
296
434
|
|
|
435
|
+
`styleMap` keys can be CSS property names (`'font-size'`, `'--gap'`) or
|
|
436
|
+
camelCase names (`fontSize`, `backgroundColor`), which are converted to
|
|
437
|
+
dash-case. Custom properties (`--name`) are used exactly as written.
|
|
438
|
+
|
|
297
439
|
### `ref`
|
|
298
440
|
|
|
299
441
|
Get a reference to the DOM element.
|
|
@@ -306,7 +448,7 @@ html`<input ref="${(el) => console.log(el)}" />`
|
|
|
306
448
|
|
|
307
449
|
### `live`
|
|
308
450
|
|
|
309
|
-
|
|
451
|
+
`live` compares against the live DOM value. Use it for inputs.
|
|
310
452
|
|
|
311
453
|
```typescript
|
|
312
454
|
import { live } from '@cossackframework/renderer';
|
|
@@ -333,8 +475,8 @@ any depth: `bind(this, 'address.street')`.
|
|
|
333
475
|
|
|
334
476
|
### `key`
|
|
335
477
|
|
|
336
|
-
Force a subtree to be recreated when the key changes.
|
|
337
|
-
CSS animations or
|
|
478
|
+
Force a subtree to be recreated when the key changes. Use it to re-trigger
|
|
479
|
+
CSS animations or to remount a child.
|
|
338
480
|
|
|
339
481
|
```typescript
|
|
340
482
|
import { key } from '@cossackframework/renderer';
|
|
@@ -345,8 +487,8 @@ html`<div>${key(currentIndex, html`<div class="animate-fade-in">${child}</div>`)
|
|
|
345
487
|
### `preventDefault`
|
|
346
488
|
|
|
347
489
|
Wraps an event handler so the event's default is prevented before it runs. It
|
|
348
|
-
also disables the browser's native validation on the bound `<form>` by default
|
|
349
|
-
|
|
490
|
+
also disables the browser's native validation on the bound `<form>` by default.
|
|
491
|
+
Pass `{ novalidate: false }` to keep native validation.
|
|
350
492
|
|
|
351
493
|
```typescript
|
|
352
494
|
import { preventDefault } from '@cossackframework/renderer';
|
|
@@ -382,7 +524,7 @@ html`${choose(status, [
|
|
|
382
524
|
|
|
383
525
|
### `ifDefined`
|
|
384
526
|
|
|
385
|
-
Only omit an attribute when the value is `undefined
|
|
527
|
+
Only omit an attribute when the value is `undefined`. Render every other value
|
|
386
528
|
(including `null`, `false`, `0`, `''`) as a normal attribute.
|
|
387
529
|
|
|
388
530
|
```typescript
|
|
@@ -408,7 +550,7 @@ html`${guard([query, page], () => renderResults(query, page))}`
|
|
|
408
550
|
|
|
409
551
|
Keep previously-rendered template subtrees alive instead of destroying them
|
|
410
552
|
when the rendered value switches templates. Toggling back to a cached template
|
|
411
|
-
reattaches its existing DOM and part tree
|
|
553
|
+
reattaches its existing DOM and part tree. It preserves component state, scroll
|
|
412
554
|
position, and focus.
|
|
413
555
|
|
|
414
556
|
```typescript
|
|
@@ -430,7 +572,7 @@ html`<ul>${map(items, (item) => html`<li>${item.name}</li>`)}</ul>`
|
|
|
430
572
|
### `join`
|
|
431
573
|
|
|
432
574
|
Join renderable values with a separator interleaved between each pair. The
|
|
433
|
-
separator can be a static value or a template (
|
|
575
|
+
separator can be a static value or a template (for example a divider element).
|
|
434
576
|
|
|
435
577
|
```typescript
|
|
436
578
|
import { join } from '@cossackframework/renderer';
|
|
@@ -467,7 +609,7 @@ export const ThemeContext = createContext('light'); // Default value
|
|
|
467
609
|
class App extends CossackElement {
|
|
468
610
|
render() {
|
|
469
611
|
this.provide(ThemeContext, 'dark');
|
|
470
|
-
return html
|
|
612
|
+
return html`<${Child} />`;
|
|
471
613
|
}
|
|
472
614
|
}
|
|
473
615
|
```
|
|
@@ -525,17 +667,17 @@ class ClockElement extends CossackElement {
|
|
|
525
667
|
|
|
526
668
|
Cossack supports passing children to components.
|
|
527
669
|
|
|
528
|
-
|
|
670
|
+
Parent:
|
|
529
671
|
```typescript
|
|
530
672
|
html`
|
|
531
|
-
|
|
673
|
+
<${Card}>
|
|
532
674
|
<h1>Title</h1>
|
|
533
675
|
<p>Content</p>
|
|
534
|
-
|
|
676
|
+
</${Card}>
|
|
535
677
|
`
|
|
536
678
|
```
|
|
537
679
|
|
|
538
|
-
|
|
680
|
+
Child (Card):
|
|
539
681
|
```typescript
|
|
540
682
|
class Card extends CossackElement {
|
|
541
683
|
render() {
|
package/agent-docs.json
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"guides": [
|
|
4
|
+
{
|
|
5
|
+
"id": "server-html",
|
|
6
|
+
"title": "Render escaped HTML on the server",
|
|
7
|
+
"summary": "Use the server entrypoint to turn an HTML template into a string.",
|
|
8
|
+
"imports": [
|
|
9
|
+
"@cossackframework/renderer/server"
|
|
10
|
+
],
|
|
11
|
+
"markdown": "Import html and renderToString from the public server entrypoint. Interpolate text values into html templates. The renderer escapes text rather than interpreting it as markup.\n\nDo not concatenate untrusted text into HTML source or use unsafe raw-HTML helpers for it. Escaping text does not authorize a request or validate application URLs. Server rendering produces an HTML string. It does not attach browser event handlers or hydrate an application.",
|
|
12
|
+
"examples": [
|
|
13
|
+
{
|
|
14
|
+
"id": "escaped-text",
|
|
15
|
+
"language": "typescript",
|
|
16
|
+
"source": "import { html, renderToString } from '@cossackframework/renderer/server';\n\nconst name: string = '<script>alert(1)</script>';\nconst output: string = await renderToString(html`<p>Hello ${name}</p>`);\nif (output.includes('<script>')) throw new Error('Text became executable markup');\nif (!output.includes('<script>')) throw new Error('Text was not escaped');\n"
|
|
17
|
+
}
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "conditional-templates",
|
|
22
|
+
"title": "Select template branches and optional attributes",
|
|
23
|
+
"summary": "Render conditional content without building HTML strings.",
|
|
24
|
+
"imports": [
|
|
25
|
+
"@cossackframework/renderer",
|
|
26
|
+
"@cossackframework/renderer/server"
|
|
27
|
+
],
|
|
28
|
+
"markdown": "Use `when` to select a branch and `choose` to match a value with strict equality. Their callbacks run while the template expression is evaluated. Use `nothing` for an empty child value. `ifDefined(undefined)` omits an attribute; other values, including `null`, `false`, and `0`, are serialized as values. HTML escaping does not validate URL schemes or authorize a destination.",
|
|
29
|
+
"examples": [
|
|
30
|
+
{
|
|
31
|
+
"id": "choose-safe-branches",
|
|
32
|
+
"language": "typescript",
|
|
33
|
+
"source": "import { choose, ifDefined, nothing, when } from '@cossackframework/renderer';\nimport { html, renderToString } from '@cossackframework/renderer/server';\n\nconst status: string = 'ready';\nconst output = await renderToString(html`<main><a href=\"${ifDefined(undefined)}\">Home</a>${when(status !== 'hidden', () => html`<p>${choose(status, [['ready', () => 'Ready'], ['saving', () => 'Saving']], () => nothing)}</p>`, () => nothing)}</main>`);\nif (output !== '<main><a>Home</a><p>Ready</p></main>') throw new Error(`Unexpected conditional output: ${output}`);\n"
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"id": "keyed-lists",
|
|
39
|
+
"title": "Render lists with stable item keys",
|
|
40
|
+
"summary": "Use keyed repeat for lists whose DOM items should keep their identity.",
|
|
41
|
+
"imports": [
|
|
42
|
+
"@cossackframework/renderer",
|
|
43
|
+
"@cossackframework/renderer/server"
|
|
44
|
+
],
|
|
45
|
+
"markdown": "`repeat(items, keyFn, templateFn)` gives the browser renderer a stable key for each item so it can retain matching DOM nodes when the list changes. Server rendering emits the initial ordered markup; it does not prove browser node reuse. Use `join` when you need a renderable separator between values. Plain arrays and `map` are enough when item identity does not matter.",
|
|
46
|
+
"examples": [
|
|
47
|
+
{
|
|
48
|
+
"id": "keyed-initial-markup",
|
|
49
|
+
"language": "typescript",
|
|
50
|
+
"source": "import { join, repeat } from '@cossackframework/renderer';\nimport { html, renderToString } from '@cossackframework/renderer/server';\n\nconst people = [{ id: 'ada', name: 'Ada' }, { id: 'lin', name: 'Lin' }];\nconst output = await renderToString(html`<ol>${repeat(people, person => person.id, person => html`<li data-id=\"${person.id}\">${person.name}</li>`)}</ol><p>${join(people, person => person.name, ', ')}</p>`);\nif (!output.includes('<li data-id=\"ada\">Ada</li><li data-id=\"lin\">Lin</li>')) throw new Error('Initial list order or values are wrong');\nif (!output.endsWith('<p>Ada, Lin</p>')) throw new Error('List separator is missing');\n"
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"id": "server-form-values",
|
|
56
|
+
"title": "Render current form values before hydration",
|
|
57
|
+
"summary": "Seed input, checkbox, and textarea values in server-rendered HTML.",
|
|
58
|
+
"imports": [
|
|
59
|
+
"@cossackframework/renderer",
|
|
60
|
+
"@cossackframework/renderer/server"
|
|
61
|
+
],
|
|
62
|
+
"markdown": "Use `.value=${bind(state, path)}` and `.checked=${bind(state, path)}` to render the current field values. `live(value)` supplies the current value when the renderer reconciles an existing DOM property. On the server these helpers only produce initial markup; client rendering or hydration is required for browser write-back. A binding does not validate submitted data or authorize a server action.",
|
|
63
|
+
"examples": [
|
|
64
|
+
{
|
|
65
|
+
"id": "seed-native-controls",
|
|
66
|
+
"language": "typescript",
|
|
67
|
+
"source": "import { bind, live } from '@cossackframework/renderer';\nimport { html, renderToString } from '@cossackframework/renderer/server';\n\nconst form = { email: 'agent@example.test', active: true, note: '<draft>' };\nconst output = await renderToString(html`<form><input name=\"email\" .value=${bind(form, 'email')}><input name=\"active\" type=\"checkbox\" .checked=${bind(form, 'active')}><textarea name=\"note\" .value=${live(form.note)}></textarea></form>`);\nif (!output.includes('name=\"email\" value=\"agent@example.test\"')) throw new Error('Email value was not rendered');\nif (!output.includes('type=\"checkbox\" checked')) throw new Error('Checked state was not rendered');\nif (!output.includes('<draft></textarea>')) throw new Error('Textarea text was not escaped');\n"
|
|
68
|
+
}
|
|
69
|
+
]
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"id": "safe-component-css",
|
|
73
|
+
"title": "Compose component CSS from reviewed values",
|
|
74
|
+
"summary": "Use css tagged templates for static styles and reserve unsafeCSS for trusted values.",
|
|
75
|
+
"imports": [
|
|
76
|
+
"@cossackframework/renderer"
|
|
77
|
+
],
|
|
78
|
+
"markdown": "`css` accepts numeric interpolations and other `CSSResult` values. It rejects ordinary strings, so use static styles and typed numbers for normal composition. `unsafeCSS` marks a string as trusted CSS; it does not sanitize it. Never pass user input, request data, or other untrusted values to `unsafeCSS`.",
|
|
79
|
+
"examples": [
|
|
80
|
+
{
|
|
81
|
+
"id": "safe-style-composition",
|
|
82
|
+
"language": "typescript",
|
|
83
|
+
"source": "import { css, unsafeCSS } from '@cossackframework/renderer';\n\nconst gap = 8;\nconst surface = css`background-color: #fff;`;\nconst card = css`article { padding: ${gap}px; ${surface} }`;\nif (!card.cssText.includes('padding: 8px')) throw new Error('Numeric CSS interpolation failed');\nif (!card.cssText.includes('background-color: #fff')) throw new Error('CSSResult composition failed');\nlet rejected = false;\ntry { css`color: ${'red'};`; } catch { rejected = true; }\nif (!rejected) throw new Error('A raw string was accepted by css');\nconst reviewedToken = unsafeCSS('var(--brand-color)');\nif (!css`color: ${reviewedToken};`.cssText.includes('var(--brand-color)')) throw new Error('Reviewed CSS token did not compose');\n"
|
|
84
|
+
}
|
|
85
|
+
]
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
"id": "component-tags",
|
|
89
|
+
"title": "Compose components with component tags",
|
|
90
|
+
"summary": "Write child components as <${Class}> tags; attributes become props and content becomes children.",
|
|
91
|
+
"imports": [
|
|
92
|
+
"@cossackframework/renderer",
|
|
93
|
+
"@cossackframework/renderer/server"
|
|
94
|
+
],
|
|
95
|
+
"markdown": "Write a child component as a component tag: bind its class in tag position, `<${Card} padding=\"sm\">children</${Card}>`, or self-close it, `<${Icon} entry=${ArrowIcon} />`. The closing tag binds the same class; another class is an error. Attributes become `props` the way `component()` takes them: `name=\"text\"` passes the string (character references decoded), a bare `name` passes `true`, `name=${value}` passes the value as is, `name=\"a ${b}\"` passes text, and `.prop=${v}`, `?bool=${v}` and `@event=${f}` keep their prefix in the prop key. `...=${props}` spreads an object; later attributes override earlier ones. Prop names keep their case, so `rowCount=${12}` sets `rowCount`.\n\nChildren become `children`: nothing for empty or whitespace content, the text for plain text, the value itself for one binding, and a template otherwise. Named slots are props with template values: ``footer=${html`<p>Saved</p>`}``.\n\n`html` compiles each tag into the result `component()` returns, so SSR, hydration, drafts and service scopes behave the same. Use tags for markup. Keep `component(Class, props, children)` only where the class is chosen at runtime, such as from a registry; `cossack check templates --verbose` hints at `component()` calls with a literal class.\n\nTemplate holes are not contextually typed. Annotate callback parameters, such as `onValueChange=${(value: string) => ...}`, and write object and array literals with `satisfies`, such as `state=${{ page: 1 } satisfies TableState}`, so literal types are kept. The template check reports a prop the component does not declare, a value of the wrong type, a missing required prop, and a static text value for a non-string prop (`count=\"3\"`; write `count=${3}`).",
|
|
96
|
+
"examples": [
|
|
97
|
+
{
|
|
98
|
+
"id": "badge-tags",
|
|
99
|
+
"language": "typescript",
|
|
100
|
+
"source": "import { CossackElement, component } from '@cossackframework/renderer';\nimport { html, renderToString } from '@cossackframework/renderer/server';\n\nclass Badge extends CossackElement {\n declare props: { tone?: 'info' | 'warning'; count?: number };\n render() {\n const { tone = 'info', count = 0 } = this.props;\n return html`<span class=\"badge ${tone}\" data-count=${count}>${this.children}</span>`;\n }\n}\n\nclass Alert extends Badge {}\n\nconst output = await renderToString(html`<p><${Badge} tone=\"warning\" count=${3}>Late <b>2</b></${Badge}></p>`);\nif (output !== '<p><span class=\"badge warning\" data-count=\"3\">Late <b>2</b></span></p>') throw new Error(`Unexpected tag output: ${output}`);\n\n// component() remains for a class chosen at runtime.\nconst registry: Record<string, typeof Badge> = { badge: Badge, alert: Alert };\nconst chosen = await renderToString(html`<p>${component(registry['alert'], { count: 1 }, 'New')}</p>`);\nif (chosen !== '<p><span class=\"badge info\" data-count=\"1\">New</span></p>') throw new Error(`Unexpected component() output: ${chosen}`);\n"
|
|
101
|
+
}
|
|
102
|
+
]
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"id": "binding-forms-and-template-checks",
|
|
106
|
+
"title": "Use the binding forms the template check accepts",
|
|
107
|
+
"summary": "Know what each binding form does and which template problems fail the check and the build.",
|
|
108
|
+
"imports": [
|
|
109
|
+
"@cossackframework/renderer/template"
|
|
110
|
+
],
|
|
111
|
+
"markdown": "An `html` or `svg` template has five binding forms. In child content, `${value}` renders text, a template, a list or a component. In a tag, `name=${value}` sets an attribute (`null`, `undefined` or `nothing` removes it; `ifDefined()` removes it only for undefined), `name=\"a ${b}\"` interpolates text, `.prop=${value}` sets a DOM property, `?name=${boolean}` toggles a boolean attribute, `@event=${handler}` adds a listener, and `...=${object}` spreads attributes, properties and listeners. A `.`, `?` or `@` binding takes one whole value. A component tag binds a class in tag position.\n\nRun `cossack check templates` (or rely on the Vite build) after editing templates. It reads every template with the project's TypeScript program and reports each problem with file, line and column. Errors fail the check and the build; warnings do not. Structural errors: unclosed or mismatched elements, `<div />` on an HTML element (only void and SVG elements self-close), a binding that renders nothing (inside a comment, `<div ${x}>`, or interrupting an attribute name), an unknown binding prefix such as `:value=`, a prefixed attribute without a binding (`@click=\"save()\"`), a component tag that never closes or closes with another class, and a template literal with markup but no `html` tag in child content, which renders as escaped text. Type errors: an attribute the element does not have (custom elements accept global attributes, with a warning for others), an attribute value of the wrong type (static enumerated values are checked too), an inline `onclick` attribute, an `@event` handler that does not accept the element's event, a `?attr` value that is not boolean, an unknown or read-only `.prop`, and component tag props. Attribute types come from `@cossackframework/renderer/attributes`.\n\n`parseTemplate` from `@cossackframework/renderer/template` returns the same element tree and structural problems the check uses.",
|
|
112
|
+
"examples": [
|
|
113
|
+
{
|
|
114
|
+
"id": "structural-problems",
|
|
115
|
+
"language": "typescript",
|
|
116
|
+
"source": "import { parseTemplate } from '@cossackframework/renderer/template';\n\nconst strings = (template: TemplateStringsArray, ..._values: unknown[]) => [...template];\nconst parsed = parseTemplate(strings`<ul><li .title=${'x'}>${'Ada'}</li><div ${'dropped'}></div><input :value=${'v'}><div /></ul>`);\nconst codes: string[] = parsed.problems.map(problem => problem.code);\nfor (const code of ['COSSACK_TEMPLATE_DROPPED_BINDING', 'COSSACK_TEMPLATE_UNKNOWN_BINDING_PREFIX', 'COSSACK_TEMPLATE_SELF_CLOSING_ELEMENT']) {\n if (!codes.includes(code)) throw new Error(`Missing structural problem ${code}: ${codes.join(', ')}`);\n}\nif (parsed.bindings[1].kind !== 'node' || parsed.bindings[0].kind !== 'attribute') throw new Error('Binding roles are wrong');\n"
|
|
117
|
+
}
|
|
118
|
+
]
|
|
119
|
+
}
|
|
120
|
+
]
|
|
121
|
+
}
|