-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathllms.txt
More file actions
1651 lines (1248 loc) · 46.3 KB
/
llms.txt
File metadata and controls
1651 lines (1248 loc) · 46.3 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Ripple TS Framework - AI/LLM Documentation
## Overview
Ripple is a TypeScript UI framework that combines the best parts of React, Solid, and Svelte into one elegant package. Created by Dominic Gannaway ([@trueadm](https://github.com/trueadm)), Ripple is designed to be JS/TS-first with `.tsrx` as its default component file extension while preserving `.tsrx` compatibility.
**Key Characteristics:**
- **Performance**: Fine-grain rendering, with industry-leading performance, bundle-size and memory usage
- **TypeScript-first**: Full TypeScript integration with type checking
- **JSX-like syntax**: Familiar templating with TSRX-specific enhancements
- **Reactive state**: Built-in reactivity with `track` and `&[]` lazy destructuring syntax
- **Component-based**: Clean, reusable components with props and children
## Installation & Setup
```bash
# Create new project from template
npx degit Ripple-TS/ripple/templates/basic my-app
cd my-app
pnpm install && pnpm dev
# Or install in existing project
pnpm add ripple
pnpm add -D '@ripple-ts/vite-plugin' # For Vite integration
```
## Core Syntax & Concepts
### Component Definition
Components are defined using the `component` keyword (not functions that return JSX):
```ripple
component Button(props: { text: string, onClick: () => void }) {
<button onClick={props.onClick}>
{props.text}
</button>
}
// Usage
export component App() {
<Button text="Click me" onClick={() => console.log("Clicked!")} />
}
```
### ⚠️ Critical: Text Content Must Be in Expressions
**IMPORTANT**: Unlike HTML or JSX, Ripple elements cannot contain raw text content. All text must be wrapped in JavaScript expressions using curly braces `{}`.
```ripple
// ❌ WRONG - Raw text not allowed
<div>Hello World</div>
<p>This will cause a compilation error</p>
// ✅ CORRECT - Text in expressions
<div>{"Hello World"}</div>
<p>{"This works correctly"}</p>
// ✅ CORRECT - Variables and expressions
<div>{greeting}</div>
<p>{`Dynamic content: ${value}`}</p>
```
This is because Ripple needs to distinguish between JavaScript code and literal strings within the template syntax. The parser cannot determine if `Hello` is meant to be a string literal or a JavaScript identifier without explicit expression syntax.
### ⚠️ Critical: Templates Only Inside Component Bodies
**IMPORTANT**: Ripple template syntax (JSX-like elements) can ONLY exist inside `component` function bodies. You cannot create JSX elements in regular functions, assign them to variables, or use them outside components.
```ripple
// ❌ WRONG - Templates outside component
const element = <div>{"Hello"}</div>; // Compilation error
function regularFunction() {
return <span>{"Not allowed"}</span>; // Compilation error
}
const myTemplate = (
<div>{"Cannot assign JSX"}</div> // Compilation error
);
// ✅ CORRECT - Templates only inside components
component MyComponent() {
// Template syntax is valid here
<div>{"Hello World"}</div>
// You can have JavaScript code mixed with templates
const message = "Dynamic content";
console.log("This JavaScript works");
<p>{message}</p>
}
// ✅ CORRECT - Helper functions return data, not templates
function getMessage() {
return "Hello from function"; // Return data, not JSX
}
component App() {
<div>{getMessage()}</div> // Use function result in template
}
```
This design enforces clear separation between component templates and regular JavaScript logic, making code more predictable and easier to analyze.
### Using `<>` or `<tsx>` for JSX Expression Values
**IMPORTANT**: Regular Ripple elements are statement-based and can only appear directly inside component bodies or nested template blocks. If you need to create JSX as a value in expression position, wrap it in `<>...</>` or the equivalent `<tsx>...</tsx>` form.
Use `<>...</>` or `<tsx>...</tsx>` when you need to:
- assign JSX to a variable
- return JSX from a helper function
- pass JSX directly as a prop or `children`
- build reusable render factories
```ripple
// ✅ CORRECT - JSX used as an expression value via fragment shorthand
component App() {
const title = <><span class="title">Title</span></>;
<div>{title}</div>
}
// ✅ CORRECT - returning JSX from a helper function
function createBadge(label: string) {
return <>
<span class="badge">{label}</span>
</>;
}
component App() {
{createBadge('New')}
}
// ✅ CORRECT - passing JSX directly as props
component Card(props: { title: any; children: any }) {
<section>
<h2>{props.title}</h2>
<div>{props.children}</div>
</section>
}
component App() {
<Card
title={<><span>Settings</span></>}
children={<><p>Card body</p></>}
/>
}
```
**LLM DO:**
- Use `<>...</>` as the default wrapper when JSX must exist in expression position.
- Use `<tsx>...</tsx>` when you want the explicit long form; it is equivalent.
- Treat either form as a renderable value that can be stored, returned, and passed around.
- Keep using normal Ripple syntax and semantics inside either wrapper.
**LLM DON'T:**
- Do not write `const el = <div />;` directly in Ripple code.
- Do not return bare JSX from helper functions without `<>...</>` or `<tsx>...</tsx>`.
- Do not confuse plain `<tsx>` with `<tsx:react>`.
- Do not require React compat for plain `<tsx>`.
**Key distinction:**
- `<>...</>` / `<tsx>...</tsx>`: expression-form Ripple JSX value
- `<tsx:react>`: React compatibility block with React JSX semantics and compat setup
### ⚠️ Critical: Early Returns Are Guard Exits, Not JSX Returns
**IMPORTANT**: Inside Ripple components, use early returns only as `return;` (no value). This exits the current component render path and skips statements that follow.
```ripple
// ✅ CORRECT - Guard clause with early return
component AuthGate({ is_logged_in }) {
if (!is_logged_in) {
<p>{'Please sign in.'}</p>
return;
}
<h1>{'Dashboard'}</h1>
}
// ❌ WRONG - Returning templates from components
component App() {
if (loading) {
return <p>{'Loading...'}</p>; // Compilation error
}
}
// ❌ WRONG - Returning values from components
component App() {
if (error) {
return 'failed'; // Compilation error
}
}
```
**LLM DO:**
- Use `if (...) { <Fallback /> return; }` guard clauses to short-circuit rendering.
- Place any guard/fallback template statements before `return;`.
- Keep helper functions separate for computing/returning data.
- Use early return when it improves readability over deeply nested `if/else`.
**LLM DON'T:**
- Do not generate `return <JSX />` in Ripple components.
- Do not generate `return someValue;` inside Ripple components.
- Do not generate top-level/module `return;`.
- Do not translate React-style `return (...)` component patterns directly to Ripple.
### Template Lexical Scoping
**Unique Feature**: Ripple templates act as lexical scopes, allowing you to declare variables, call functions, and execute JavaScript statements directly within JSX elements - similar to block statements in regular JavaScript.
```ripple
component TemplateScope() {
<div>
// Variable declarations inside templates
const message = "Hello from template scope";
let count = 42;
// Function calls and expressions
console.log("This runs during render");
// Conditional logic
const isEven = count % 2 === 0;
<h1>{message}</h1>
<p>{"Count is: "}{count}</p>
if (isEven) {
<span>{"Count is even"}</span>
}
// Nested scopes work too
<section>
const sectionData = "Nested scope variable";
<p>{sectionData}</p>
</section>
// You can even put debugger statements
debugger;
</div>
}
```
**Key Benefits:**
- **Inline Logic**: Execute JavaScript directly where you need it in the template
- **Local Variables**: Declare variables scoped to specific parts of your template
- **Debugging**: Place `console.log()` or `debugger` statements anywhere in templates
- **Dynamic Computation**: Calculate values inline without helper functions
**Scope Rules:**
- Variables declared in templates are scoped to that template block
- Nested elements create nested scopes
- Variables from outer scopes are accessible in inner scopes
- Template variables don't leak to the component function scope
### Reactive Variables
You use `track` to create a single tracked value. The `track` function creates a `Tracked<V>` object. Use lazy destructuring with `&[...]` to unwrap the tracked value into a reactive variable:
```ripple
import { track } from 'ripple';
export component Counter() {
let &[count] = track(0);
let &[double] = track(() => count * 2); // Derived reactive value
<div>
<p>{"Count: "}{count}</p>
<p>{"Double: "}{double}</p>
<button onClick={() => count++}>{"Increment"}</button>
</div>
}
```
**IMPORTANT:** You must use `track()` with lazy destructuring `&[...]` to create reactive variables:
```ripple
import { track } from 'ripple';
// CORRECT:
let &[count] = track(0); // Create with track() and &[] destructuring
count++; // Read/write directly
// Access the tracked ref as the second element:
let &[count, countTracked] = track(0);
```
#### Accessing Tracked Values with `.value`
As an alternative to lazy destructuring, you can read and write a tracked value directly using the `.value` property on the `Tracked<V>` object:
```ripple
import { track } from 'ripple';
const count = track(0);
// Read the current value
console.log(count.value); // 0
// Write a new value
count.value++;
console.log(count.value); // 1
```
Using `&[...]` lazy destructuring is preferred in most cases because it produces cleaner, more readable code. However, `.value` is useful when you need to keep the `Tracked<V>` object around — for example, when storing tracked values in data structures, passing them as props typed as `Tracked<T>`, or when you need both the tracked object and its value in different contexts:
```ripple
import { track } from 'ripple';
// Storing tracked values in an array — use .value to read/write
const items = [track(1), track(2), track(3)];
items[0].value++; // reactively updates
// Passing tracked objects as props — the child receives the Tracked<T> object
component Child(props: { count: Tracked<number> }) {
<div>{props.count.value}</div>
}
// Using &[value, trackedValue] gives you both:
let &[count, countTracked] = track(0);
count++; // convenient direct access via lazy destructuring
console.log(countTracked.value); // equivalent: read via .value on the tracked object
```
Objects can also contain tracked values — use lazy destructuring to access them:
```ripple
import { track } from 'ripple';
let counter = { current: track(0) };
let &[current] = counter.current;
current++; // Triggers reactivity
```
Tracked derived values are also `Tracked<V>` objects, except you pass a function to `track` rather than a value:
```ripple
import { track } from 'ripple';
let &[count] = track(0);
let &[double] = track(() => count * 2);
let &[quadruple] = track(() => double * 2);
console.log(quadruple);
```
If you want to use a tracked value inside a reactive context, such as an effect but you don't want that value to be a tracked dependency, you can use `untrack`:
```ripple
import { track, effect, untrack } from 'ripple';
let &[count] = track(0);
let &[double] = track(() => count * 2);
let &[quadruple] = track(() => double * 2);
effect(() => {
// This effect will never fire again, as we've untracked the only dependency it has
console.log(untrack(() => quadruple));
})
```
> Note: you cannot create `Tracked` objects in module/global scope, they have to be created on access from an active component context.
#### track with get / set
The optional get and set parameters of the `track` function let you customize how a tracked value is read or written, similar to property accessors but expressed as pure functions. The get function receives the current stored value and its return value is exposed when the tracked value is read via `&[]` destructuring. The set function should return the value that will actually be stored and receives two parameters: the first is the one being assigned and the second with the previous value. The get and set functions may be useful for tasks such as logging, validating, or transforming values before they are exposed or stored.
```ripple
import { track } from 'ripple';
export component App() {
let &[count] = track(0,
(current) => {
console.log(current);
return current;
},
(next, prev) => {
console.log(prev);
if (typeof next === 'string') {
next = Number(next);
}
return next;
}
);
}
```
> Note: If no value is returned from either `get` or `set`, `undefined` is either exposed (for get) or stored (for set). Also, if only supplying the `set`, the `get` parameter must be set to `undefined`.
#### Lazy Destructuring (`&{...}` / `&[...]`)
Lazy destructuring uses the `&` prefix directly before `{` or `[` in a destructuring pattern. Instead of eagerly pulling values out of the source object, lazy destructuring compiles each variable access to a deferred property/index lookup on the source. This preserves reactivity for reactive props and other tracked objects.
```ripple
// Lazy object destructuring
const &{ a, b } = props;
// Compiles to: a → props.a, b → props.b (accessed lazily)
// Lazy array destructuring
const &[first, second] = items;
// Compiles to: first → items[0], second → items[1]
// With default values
const &{ x = 10 } = props;
// Compiles to: x → _$_.fallback(props.x, 10)
// With rest patterns
const &{ a, ...rest } = props;
// Compiles to: a → props.a, rest → { ...props, a: undefined } (lazily)
```
**Component props** — use `&{...}` to lazily destructure props, preserving reactivity:
```ripple
component Child(&{ count, className, children }: Props) {
// count, className, children are lazily read from __props
<button class={className}>{children}</button>
<pre>{`Count is: ${count}`}</pre>
}
```
**Function parameters** — works in regular functions too:
```ripple
function process(&{ x, y }: Point) {
return x + y; // lazily reads from the parameter object
}
```
**Variable declarations** — lazy destructuring works with `const`, `let`, and `var`:
```ripple
const &{ a, b } = someObject; // read-only lazy access
let &{ x, y } = mutableObject; // supports assignment: x = 5 writes back to mutableObject.x
```
> **When to use lazy destructuring**: Use `&{...}` whenever you destructure reactive props or tracked objects and need the variables to remain reactive. Regular destructuring (`{ a, b } = obj`) eagerly copies values and loses reactivity.
### Transporting Reactivity
**Critical Concept**: Ripple doesn't constrain reactivity to components only. `Tracked<V>` objects can simply be passed by reference between boundaries to improve expressivity and co-location.
#### Basic Transport Pattern
```ripple
import { track, effect } from 'ripple';
function createDouble(&[count]) {
const &[double] = track(() => count * 2);
effect(() => {
console.log('Count:', count)
});
return double;
}
export component App() {
let &[count, countTracked] = track(0);
const &[double] = createDouble(countTracked);
<div>{'Double: ' + double}</div>
<button onClick={() => { count++; }}>{'Increment'}</button>
}
```
#### Dynamic Component Transport Pattern
Ripple has built-in support for dynamic components, a way to render different components based on reactive state. Instead of hardcoding which component to show, you can store a component in a `Tracked` via `track()`, and update it at runtime. When the tracked value changes, Ripple automatically unmounts the previous component and mounts the new one. Dynamic components are written with the `<@Component />` tag, where `@` is a special marker that tells the compiler the component or element is dynamic — it does not dereference or unwrap the value. The expression after `@` (e.g., `swapMe` in `<@swapMe />`) is treated as a `Tracked` value, and the runtime handles unwrapping it internally. This makes it straightforward to pass components as props or swap them directly within a component, enabling flexible, state-driven UIs with minimal boilerplate.
```ripple
import { track } from 'ripple';
export component App() {
let &[swapMe, swapMeTracked] = track(() => Child1);
<Child swapMe={swapMeTracked} />
<button onClick={() => swapMe = swapMe === Child1 ? Child2 : Child1}>{'Swap Component'}</button>
}
component Child(&{ swapMe }: {swapMe: Tracked<Component>}) {
<@swapMe />
}
component Child1(props) {
<pre>{'I am child 1'}</pre>
}
component Child2(props) {
<pre>{'I am child 2'}</pre>
}
```
**Transport Rules:**
- Reactive state must be connected to a component
- Cannot be global or created at module/global scope
- Use arrays `[ trackedVar ]` or objects `{ trackedVar }` to transport reactivity
- Functions can accept and return reactive state using these patterns
- This enables composable reactive logic outside of component boundaries
### Control Flow
#### If Statements
```ripple
component Conditional({ isVisible }) {
<div>
if (isVisible) {
<span>{"Visible content"}</span>
} else {
<span>{"Hidden state"}</span>
}
</div>
}
```
#### Switch Statements
Switch statements in Ripple provide a powerful way to conditionally render content based on the value of an expression. They are fully reactive and integrate seamlessly with Ripple's templating syntax.
**Key Features:**
- **Reactivity:** Works with both static and reactive (`Tracked`) values.
- **Control Flow:** Full support of standard JS with `break` statements and fall-through's.
- **Template Integration:** `case` blocks can contain any valid Ripple template content, including other components, elements, and logic.
**Basic Usage:**
The `switch` statement evaluates an expression and matches its value against a series of `case` clauses.
```ripple
component StatusIndicator({ status }) {
// The switch statement evaluates the 'status' prop
switch (status) {
case: 'init':
// fall-through to the next
case 'loading':
<p>{'Loading...'}</p>
break; // break is mandatory
case 'success':
<p>{'Success!'}</p>
break;
case 'error':
<p>{'Error!'}</p>
break;
default:
<p>{'Unknown status'}</p>
// No break needed for default
}
}
```
`switch` statements can also react to changes in `Tracked` variables. When the tracked variable changes, the `switch` statement will re-evaluate and render the appropriate `case`.
```ripple
import { track } from 'ripple';
component InteractiveStatus() {
let &[status] = track('loading'); // Reactive state
<button onClick={() => status = 'success'>{'Set to Success'}</button>
<button onClick={() => status = 'error'}>{'Set to Error'}</button>
// This switch block will update automatically when 'status' changes
switch (status) {
case 'init':
<p>{'Status: Init'}</p>
// fall-through to the next
case 'loading':
<p>{'Status: Loading...'}</p>
break;
case 'success':
<p>{'Status: Success!'}</p>
break;
case 'error':
<p>{'Status: Error!'}</p>
break;
default:
<p>{'Status: Unknown'}</p>
}
}
```
#### For Loops
```ripple
component List({ items }) {
<ul>
for (const item of items) {
<li>{item.text}</li>
}
</ul>
}
```
#### For Loops with index
```ripple
component ListView({ title, items }) {
<h2>{title}</h2>
<ul>
for (const item of items; index i) {
<li>{item.text}{' at index '}{i}</li>
}
</ul>
}
```
#### For Loops with key
```ripple
component ListView({ title, items }) {
<h2>{title}</h2>
<ul>
for (const item of items; index i; key item.id) {
<li>{item.text}{' at index '}{i}</li>
}
</ul>
}
```
**Key Usage Guidelines:**
- **Arrays with `RippleObject` instances**: Keys are usually unnecessary - object identity and reactivity handle updates automatically. Identity-based loops are more efficient with less bookkeeping.
- **Arrays with plain objects**: Keys are needed when object reference isn't sufficient for identification. Use stable identifiers: `key item.id`.
#### Dynamic Elements
```ripple
import { track } from 'ripple';
export component App() {
let &[tag] = track('div');
<@tag class="dynamic">{'Hello World'}</@tag>
<button onClick={() => tag = tag === 'div' ? 'span' : 'div'}>{'Toggle Element'}</button>
}
```
#### Try-Catch (Error Boundaries)
```ripple
component ErrorBoundary() {
<div>
try {
<ComponentThatMightFail />
} catch (e) {
<div>{"Error: "}{e.message}</div>
}
</div>
}
```
### Children Components
Use the `children` prop for component composition. Use the `Children` type to accept one or more children. If you need to pass additional child components such as `Header`, `Footer`, or `InlineComp`, define them in scope and pass them as explicit props on the component element. Do not declare `component Foo() {}` directly inside another component's child content.
```ripple
import type { Children, Component } from 'ripple';
component Card(props: { children: Children; Footer?: Component }) {
<div class="card">
{props.children}
if (props.Footer) {
<props.Footer />
}
</div>
}
component Footer() {
<button>{'OK'}</button>
}
// Usage
<Card Footer={Footer}>
<p>{"Card content here"}</p>
</Card>
```
### Events
#### Attribute Event Handling
Events follow React-style naming (`onClick`, `onPointerMove`, etc.):
```ripple
import { track } from 'ripple';
component EventExample() {
let &[message] = track("");
<div>
<button onClick={() => message = "Clicked!"}>{"Click me"}</button>
<input onInput={(e) => message = e.target.value} />
<p>{message}</p>
</div>
}
```
For capture phase events, add `Capture` suffix:
- `onClickCapture`
- `onPointerDownCapture`
#### Direct Event Handling
Use function `on` to attach events to window, document or any other element instead of addEventListener.
This method guarantees the proper execution order with respect to attribute-based handlers such as `onClick`, and similarly optimized through event delegation for those events that support it.
```ripple
import { on, effect } from 'ripple';
export component App() {
effect(() => {
// on component mount
const removeListener = on(window, 'resize', () => {
console.log('Window resized!');
});
// return the removeListener when the component unmounts
return removeListener;
});
}
```
### Styling
Components support scoped CSS with `<style>` elements:
```ripple
component StyledComponent() {
<div class="container">
<h1>{"Styled Content"}</h1>
</div>
<style>
.container {
background: blue;
padding: 1rem;
}
h1 {
color: white;
font-size: 2rem;
}
</style>
}
```
#### Style Scoping
Styles defined in a `<style>` block are **automatically scoped** to the component where they are defined. Ripple achieves this by adding a unique hash-based class (e.g., `ripple-abc123`) to all elements in that component and rewriting the CSS selectors to include that hash.
**Important**: Scoped styles of a parent component do NOT apply to child components. Each component's styles are isolated. This means:
```ripple
component Parent() {
<div class="wrapper">
<Child /> // .wrapper styles will NOT affect elements inside Child
</div>
<style>
.wrapper { padding: 20px; } // Only applies to THIS component's .wrapper
.child-class { color: red; } // Will NOT work - can't reach into Child
</style>
}
component Child() {
<div class="child-class">{"I won't be red"}</div>
}
```
#### Global Styles with `:global()`
To escape scoping and apply styles globally (or to reach into child components), use the `:global()` modifier:
```ripple
component Parent() {
<div class="wrapper">
<Child />
</div>
<style>
.wrapper { padding: 20px; } // Scoped to this component
:global(.child-class) { color: red; } // Applies globally - will reach Child
.wrapper :global(.nested) { // Scoped .wrapper, global .nested
font-weight: bold;
}
</style>
}
```
The `:global()` modifier can wrap:
- A single selector: `:global(.class-name)`
- Multiple selectors: `:global(.foo, .bar)`
- Part of a selector chain: `.scoped :global(.unscoped) .also-scoped`
```
#### Dynamic Classes
In Ripple, the `class` attribute can accept more than just a string — it also supports objects and arrays. Truthy values are included as class names, while falsy values are omitted. This behavior is powered by the `clsx` library.
Examples:
```ripple
import { track } from 'ripple';
let &[includeBaz] = track(true);
<div class={{ foo: true, bar: false, baz: includeBaz }}></div>
// becomes: class="foo baz"
<div class={['foo', {baz: false}, 0 && 'bar', [true && 'bat'] ]}></div>
// becomes: class="foo bat"
let &[count] = track(3);
<div class={['foo', {bar: count > 2}, count > 3 && 'bat']}></div>
// becomes: class="foo bar"
```
#### Dynamic Inline Styles
Sometimes you might need to dynamically set inline styles. For this, you can use the `style` attribute, passing either a string or an object to it:
```ripple
import { track } from 'ripple';
let &[color] = track('red');
<div style={`color: ${color}; font-weight: bold; background-color: gray`}></div>
<div style={{ color: color, fontWeight: 'bold', 'background-color': 'gray' }}></div>
const style = {
color,
fontWeight: 'bold',
'background-color': 'gray',
};
// using object spread
<div style={{...style}}></div>
// using object directly
<div style={style}></div>
```
Both examples above will render the same inline styles, however, it's recommended to use the object notation as it's typically more performance optimized.
> Note: When passing an object to the `style` attribute, you can use either camelCase or kebab-case for CSS property names.
### DOM References (Refs)
Use `{ref fn}` syntax to capture DOM element references:
```ripple
import { track } from 'ripple';
export component App() {
let &[div] = track();
const divRef = (node) => {
div = node;
console.log("mounted", node);
return () => {
div = undefined;
console.log("unmounted", node);
};
};
<div {ref divRef}>{"Hello world"}</div>
}
```
Inline refs:
```ripple
<div {ref (node) => console.log(node)}>{"Content"}</div>
```
## Built-in APIs
### Core Functions
```typescript
import {
mount, // Mount component to DOM
flushSync, // Synchronous state updates
} from 'ripple';
```
### Mount API
Use `mount()` to render a component to the DOM for client-side only applications:
```typescript
import { mount } from 'ripple';
import { App } from './App.tsrx';
const cleanup = mount(App, {
target: document.getElementById('root')!,
props: { title: 'Hello world!' }
});
// To unmount later:
cleanup();
```
### Hydrate API
Use `hydrate()` when your HTML was server-rendered and you need to make it interactive:
```typescript
import { hydrate } from 'ripple';
import { App } from './App.tsrx';
const cleanup = hydrate(App, {
target: document.getElementById('root')!,
props: { title: 'Hello world!' }
});
```
**When to use each:**
- `mount()`: Client-side only (SPA). Clears target and renders fresh DOM.
- `hydrate()`: SSR apps. Adopts existing server-rendered HTML without re-creating elements.
### Server-Side Rendering
On the server, use `render()` from `ripple/server`:
```typescript
import { render } from 'ripple/server';
import { App } from './App.tsrx';
// Render to string
const html = render(App, {
props: { title: 'Hello world!' }
});
```
### Effects
```ripple
import { track, effect } from 'ripple';
export component App() {
let &[count] = track(0);
effect(() => {
console.log("Count changed:", count);
});
<button onClick={() => count++}>{"Increment"}</button>
}
```
### After Update tick()
The `tick()` function returns a Promise that resolves after all pending reactive updates have been applied to the DOM. This is useful when you need to ensure that DOM changes are complete before executing subsequent code, similar to Vue's `nextTick()` or Svelte's `tick()`.
```ripple
import { tick, track, effect } from 'ripple';
export component App() {
let &[count] = track(0);
effect(() => {
count;
if (count === 0) {
console.log('initial run, skipping');
return;
}
tick().then(() => {
console.log('after the update');
});
});
<button onClick={() => count++}>{'Increment'}</button>
}
```
### Context
Ripple has the concept of `context` where a value or reactive object can be shared through the component tree –
like in other frameworks. This all happens from the `Context` class that is imported from `ripple`.
Creating contexts may take place anywhere. Contexts can contain anything including tracked values or objects. However, context cannot be read via `get` or written to via `set` inside an event handler or at the module level as it must happen within the context of a component. A good strategy is to assign the contents of a context to a variable via the `.get()` method during the component initialization and use this variable for reading and writing.
When Child components overwrite a context's value via `.set()`, this new value will only be seen by its descendants. Components higher up in the tree will continue to see the original value.
Example with tracked / reactive contents:
```ripple
import { Context, track } from 'ripple';
// create context with an empty object
const context = new Context({});
const context2 = new Context();
export component App() {
// get reference to the object
const obj = context.get();
// set your reactive value
let &[objCount, objCountTracked] = track(0);
obj.count = objCountTracked;
// create another tracked variable
let &[count2, count2Tracked] = track(0);
// context2 now contains a tracked variable
context2.set(count2Tracked);
<button onClick={() => { objCount++; count2++ }}>