-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontext.go
More file actions
403 lines (368 loc) · 9.76 KB
/
context.go
File metadata and controls
403 lines (368 loc) · 9.76 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
package via
import (
"bytes"
"encoding/json"
"fmt"
"log"
"maps"
"sync"
"github.com/go-via/via/h"
)
// Context is the living bridge between Go and the browser.
//
// It holds runtime state, defines actions, manages reactive signals, and defines UI through View.
type Context struct {
id string
route string
app *App
view func() h.H
routeParams map[string]string
componentRegistry map[string]*Context
parentPageCtx *Context
patchChan chan patch
actionRegistry map[string]func() error
signals *sync.Map
stateModified bool
mu sync.RWMutex
initFn func()
disposeFn func()
}
// View defines the UI rendered by this context.
// The function should return an h.H element (from via/h).
//
// Changes to signals or state can be pushed live with Sync().
func (c *Context) View(f func() h.H) {
if f == nil {
panic("nil viewfn")
}
c.view = func() h.H { return h.Div(h.ID(c.id), f()) }
}
// Component registers a subcontext that has self contained data, actions and signals.
// It returns the component's view as a DOM node fn that can be placed in the view
// of the parent. Components can be added to components.
//
// Example:
//
// counterCompFn := func(c *via.Context) {
// (...)
// }
//
// v.Page("/", func(c *via.Context) {
// counterComp := c.Component(counterCompFn)
//
// c.View(func() h.H {
// return h.Div(
// h.H1(h.Text("Counter")),
// counterComp(),
// )
// })
// })
func (c *Context) Component(initCtx func(c *Context)) func() h.H {
id := c.id + "/_component/" + genRandID()
compCtx := newContext(id, c.route, c.app)
if c.isComponent() {
compCtx.parentPageCtx = c.parentPageCtx
} else {
compCtx.parentPageCtx = c
}
initCtx(compCtx)
if compCtx.initFn != nil {
compCtx.initFn()
}
c.componentRegistry[id] = compCtx
return compCtx.view
}
func (c *Context) isComponent() bool {
return c.parentPageCtx != nil
}
// Init registers a callback to run once when the first SSE connection is established.
// This is useful for component initialization.
func (c *Context) Init(fn func()) {
c.initFn = fn
}
// Dispose registers a callback to run when the session closes.
// This is useful for component cleanup.
func (c *Context) Dispose(fn func()) {
c.disposeFn = fn
}
// Action registers an event handler and returns a trigger to that event that
// that can be added to the view fn as any other via.h element.
//
// Example:
//
// n := 0
// increment := c.Action(func(){
// n++
// c.Sync()
// })
//
// c.View(func() h.H {
// return h.Div(
// h.P(h.Textf("Value of n: %d", n)),
// h.Button(h.Text("Increment n"), increment.OnClick()),
// )
// })
func (c *Context) Action(f func() error) *actionTrigger {
id := genRandID()
if f == nil {
c.app.logErr(c, "failed to bind action '%s' to context: nil func", id)
return nil
}
if c.isComponent() {
c.parentPageCtx.actionRegistry[id] = f
} else {
c.actionRegistry[id] = f
}
return &actionTrigger{id}
}
func (c *Context) getActionFn(id string) (func() error, error) {
if f, ok := c.actionRegistry[id]; ok {
return f, nil
}
return nil, fmt.Errorf("action '%s' not found", id)
}
func (c *Context) injectSignals(sigs map[string]any) {
if sigs == nil {
c.app.logErr(c, "signal injection failed: nil signals")
return
}
c.mu.Lock()
defer c.mu.Unlock()
for sigID, val := range sigs {
// Skip via-ctx
if sigID == "via-ctx" {
continue
}
// Fast path: lookup by map key (== signal id when no tag)
if item, ok := c.signals.Load(sigID); ok {
if entry, ok := item.(signalEntry); ok {
entry.setRawValue(val)
entry.markSynced()
}
continue
}
// Slow path: find by displayID (for tagged signals)
var found signalEntry
c.signals.Range(func(_, value any) bool {
if entry, ok := value.(signalEntry); ok {
if entry.displayID() == sigID {
found = entry
return false
}
}
return true
})
if found != nil {
found.setRawValue(val)
found.markSynced()
} else {
c.signals.Store(sigID, &signalOf[any]{id: sigID, val: val})
}
}
}
func (c *Context) getPatchChan() chan patch {
// components use parent page sse stream
var patchChan chan patch
if c.isComponent() {
patchChan = c.parentPageCtx.patchChan
} else {
patchChan = c.patchChan
}
return patchChan
}
// allSignalValues returns all signal values regardless of changed state,
// for embedding into the initial HTML so the browser has them before SSE connects.
func (c *Context) allSignalValues() map[string]any {
c.mu.RLock()
defer c.mu.RUnlock()
result := make(map[string]any)
c.signals.Range(func(_, value any) bool {
if entry, ok := value.(signalEntry); ok && !entry.hasError() {
result[entry.displayID()] = entry.rawValue()
}
return true
})
return result
}
func (c *Context) prepareSignalsForPatch() map[string]any {
c.mu.RLock()
defer c.mu.RUnlock()
updatedSigs := make(map[string]any)
c.signals.Range(func(_, value any) bool {
entry, ok := value.(signalEntry)
if !ok {
return true
}
if entry.hasError() {
c.app.logWarn(c, "signal '%s' is out of sync: %v", entry.getID(), entry.getErr())
return true
}
if entry.isChanged() {
updatedSigs[entry.displayID()] = entry.rawValue()
entry.markSynced()
}
return true
})
return updatedSigs
}
// sendPatch queues a patch on this *Context sse stream. If the sse is closed or queue is full, the patch
// is dropped to prevent runtime blocks.
func (c *Context) sendPatch(p patch) {
patchChan := c.getPatchChan()
select {
case patchChan <- p:
default: // closed or buffer full - drop patch without blocking
}
}
// Sync pushes the current view state and signal changes to the browser immediately
// over the live SSE event stream.
func (c *Context) Sync() {
elemsPatch := bytes.NewBuffer(make([]byte, 0))
if err := c.view().Render(elemsPatch); err != nil {
c.app.logErr(c, "sync view failed: %v", err)
return
}
c.sendPatch(patch{patchTypeElements, elemsPatch.String()})
updatedSigs := c.prepareSignalsForPatch()
if len(updatedSigs) != 0 {
outgoingSigs, _ := json.Marshal(updatedSigs)
c.sendPatch(patch{patchTypeSignals, string(outgoingSigs)})
}
c.clearStateModified()
}
func (c *Context) clearStateModified() {
c.mu.Lock()
defer c.mu.Unlock()
c.stateModified = false
}
// autoSync is called automatically after each action. It calls Sync() so that
// view and signal state are pushed to the browser without requiring an explicit c.Sync() call.
func (c *Context) autoSync() {
if c.hasModifications() {
c.Sync()
}
}
// SyncElements pushes an immediate html patch over the live SSE stream to the
// browser that merges with the DOM
//
// For the merge to occur, each top lever element in the patch needs to have
// an ID that matches the ID of an element that already sits in the view.
//
// Example:
//
// If the view already contains the element:
//
// h.Div(
// h.ID("my-element"),
// h.P(h.Text("Hello from Via!"))
// )
//
// Then, the merge will only occur if the ID of one of the top level elements in the patch
// matches 'my-element'.
func (c *Context) SyncElements(elem ...h.H) {
b := bytes.NewBuffer(nil)
for idx, el := range elem {
if el == nil {
c.app.logWarn(c, "sync elements failed: element at idx=%d is nil", idx)
continue
}
if err := el.Render(b); err != nil {
c.app.logWarn(c, "sync elements failed: element at idx=%d has invalid html", idx)
continue
}
}
c.sendPatch(patch{patchTypeElements, b.String()})
}
// SyncSignals pushes the current signal changes to the browser immediately
// over the live SSE event stream.
func (c *Context) SyncSignals() {
updatedSigs := c.prepareSignalsForPatch()
if len(updatedSigs) != 0 {
outgoingSignals, _ := json.Marshal(updatedSigs)
c.sendPatch(patch{patchTypeSignals, string(outgoingSignals)})
}
}
func (c *Context) ExecScript(s string) {
if s == "" {
c.app.logWarn(c, "exec script failed: empty script")
return
}
c.sendPatch(patch{patchTypeScript, s})
}
func (c *Context) injectRouteParams(params map[string]string) {
if params == nil {
return
}
m := make(map[string]string)
c.mu.Lock()
defer c.mu.Unlock()
maps.Copy(m, params)
c.routeParams = m
}
// GetPathParam retrieves the value from the page request URL for the given parameter name
// or an empty string if not found.
//
// Example:
//
// v.Page("/users/{user_id}", func(c *via.Context) {
//
// userID := GetPathParam("user_id")
//
// c.View(func() h.H {
// return h.Div(
// h.H1(h.Textf("User ID: %s", userID)),
// )
// })
// })
func (c *Context) GetPathParam(param string) string {
c.mu.RLock()
defer c.mu.RUnlock()
if p, ok := c.routeParams[param]; ok {
return p
}
return ""
}
func newContext(id string, route string, a *App) *Context {
if a == nil {
log.Fatal("create context failed: app pointer is nil")
}
return &Context{
id: id,
route: route,
routeParams: make(map[string]string),
app: a,
componentRegistry: make(map[string]*Context),
actionRegistry: make(map[string]func() error),
signals: new(sync.Map),
stateModified: false,
patchChan: make(chan patch, 64),
}
}
// markStateModified records that State was modified in this action.
// Called by State.Set() when state changes.
func (c *Context) markStateModified() {
c.mu.Lock()
defer c.mu.Unlock()
c.stateModified = true
}
// hasModifications returns true if State or Signals have been modified since last sync.
func (c *Context) hasModifications() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.stateModified || c.hasChangedSignals()
}
func (c *Context) hasChangedSignals() bool {
hasChanged := false
c.signals.Range(func(_, value any) bool {
entry, ok := value.(signalEntry)
if !ok {
return true
}
if entry.isChanged() {
hasChanged = true
return false
}
return true
})
return hasChanged
}