@cossackframework/renderer 0.9.0 → 0.9.2

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  # Cossack Renderer Package
2
2
 
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
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
- Boolean attributes are removed if `false/null/undefined`.
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
- To render raw HTML strings (careful!):
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 may be nested. They are flattened in declaration order, and the
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 and emits one managed style
226
- element per component instance. Conditional at-rules and functional selectors
227
- are scoped recursively; keyframe names and matching animation declarations are
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
- Use the `component` helper function to include child components in your templates.
328
+ Write a child component as a component tag: bind the class in tag position.
240
329
 
241
330
  ```typescript
242
- import { component } from '@cossackframework/renderer';
331
+ import { html } from '@cossackframework/renderer';
243
332
  import { ChildComponent } from './ChildComponent';
244
333
 
245
334
  html`
246
335
  <div class="parent">
247
- ${component(ChildComponent, { someProp: 'value' })}
336
+ <${ChildComponent} someProp="value" count=${3} @select=${(event: Event) => console.log(event.type)} />
248
337
  </div>
249
338
  `
250
339
  ```
251
340
 
252
- You can also pass children to components:
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
- ${component(ChildComponent, { someProp: 'value' }, html`
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
- Efficiently renders lists by key.
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
- Check against the live DOM value (useful for inputs).
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. Useful for re-triggering
337
- CSS animations or remounting a child.
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
- pass `{ novalidate: false }` to keep native validation.
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`; render every other value
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, preserving component state, scroll
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 (e.g. a divider element).
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`${component(Child)}`;
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
- **Parent:**
670
+ Parent:
529
671
  ```typescript
530
672
  html`
531
- ${component(Card, {}, html`
673
+ <${Card}>
532
674
  <h1>Title</h1>
533
675
  <p>Content</p>
534
- `)}
676
+ </${Card}>
535
677
  `
536
678
  ```
537
679
 
538
- **Child (Card):**
680
+ Child (Card):
539
681
  ```typescript
540
682
  class Card extends CossackElement {
541
683
  render() {
package/agent-docs.json CHANGED
@@ -83,6 +83,39 @@
83
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
84
  }
85
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
+ ]
86
119
  }
87
120
  ]
88
121
  }