-
-
Notifications
You must be signed in to change notification settings - Fork 356
/
context.go
289 lines (247 loc) · 7.5 KB
/
context.go
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
package app
import (
"context"
"encoding/json"
"net/url"
"strings"
"time"
"github.com/google/uuid"
"github.com/maxence-charriere/go-app/v9/pkg/errors"
)
// Context represents a UI element-associated environment enabling interactions
// with the browser, page navigation, concurrency, and component communication.
type Context struct {
context.Context
page func() Page
appUpdatable bool
resolveURL func(string) string
navigate func(*url.URL, bool)
localStorage BrowserStorage
sessionStorage BrowserStorage
dispatch func(func())
defere func(func())
async func(func())
addComponentUpdate func(Composer)
removeComponentUpdate func(Composer)
handleAction func(string, UI, bool, ActionHandler)
postAction func(Context, Action)
observeState func(Context, string, any) ObserverX
getState func(Context, string, any)
setState func(Context, string, any) StateX
delState func(Context, string)
sourceElement UI
foreachUpdatableComponent func(UI, func(Composer))
notifyComponentEvent func(Context, UI, any)
}
// Src retrieves the linked UI element of the context.
func (ctx Context) Src() UI {
return ctx.sourceElement
}
// JSSrc fetches the JavaScript representation of the associated UI element.
func (ctx Context) JSSrc() Value {
return ctx.sourceElement.JSValue()
}
// AppUpdateAvailable checks if there's a pending app update.
func (ctx Context) AppUpdateAvailable() bool {
return ctx.appUpdatable
}
// IsAppInstallable verifies if the app is eligible for installation.
func (ctx Context) IsAppInstallable() bool {
if Window().Get("goappIsAppInstallable").Truthy() {
return Window().Call("goappIsAppInstallable").Bool()
}
return false
}
// ShowAppInstallPrompt initiates the app installation process.
func (ctx Context) ShowAppInstallPrompt() {
if ctx.IsAppInstallable() {
Window().Call("goappShowInstallPrompt")
}
}
// DeviceID fetches a distinct identifier for the app on the present device.
func (ctx Context) DeviceID() string {
var id string
if err := ctx.localStorage.Get("/go-app/deviceID", &id); err != nil {
panic(errors.New("retrieving device id failed").Wrap(err))
}
if id != "" {
return id
}
id = uuid.NewString()
if err := ctx.localStorage.Set("/go-app/deviceID", id); err != nil {
panic(errors.New("creating device id failed").Wrap(err))
}
return id
}
// Page retrieves the current active page.
func (ctx Context) Page() Page {
return ctx.page()
}
// Reload refreshes the present page.
func (ctx Context) Reload() {
if IsServer {
return
}
Window().Get("location").Call("reload")
}
// Navigate transitions to the given URL string.
func (ctx Context) Navigate(rawURL string) {
u, err := url.Parse(rawURL)
if err != nil {
Log(errors.New("navigating to URL failed").
WithTag("url", rawURL).
Wrap(err))
return
}
ctx.NavigateTo(u)
}
// NavigateTo transitions to the provided URL.
func (ctx Context) NavigateTo(u *url.URL) {
ctx.navigate(u, true)
}
// ResolveStaticResource adjusts a given path to point to the correct static
// resource location.
func (ctx Context) ResolveStaticResource(v string) string {
return ctx.resolveURL(v)
}
// ScrollTo adjusts the scrollbar to target an HTML element by its ID.
func (ctx Context) ScrollTo(id string) {
ctx.Defer(func(ctx Context) {
Window().ScrollToID(id)
})
}
// LocalStorage accesses the browser's local storage tied to the document
// origin.
func (ctx Context) LocalStorage() BrowserStorage {
return ctx.localStorage
}
// SessionStorage accesses the browser's session storage tied to the
// document origin.
func (ctx Context) SessionStorage() BrowserStorage {
return ctx.sessionStorage
}
// Encrypt enciphers a value using AES encryption.
func (ctx Context) Encrypt(v any) ([]byte, error) {
b, err := json.Marshal(v)
if err != nil {
return nil, errors.New("encoding value failed").Wrap(err)
}
b, err = encrypt(ctx.cryptoKey(), b)
if err != nil {
return nil, errors.New("encrypting value failed").Wrap(err)
}
return b, nil
}
// Decrypt deciphers encrypted data into a given reference value.
func (ctx Context) Decrypt(crypted []byte, v any) error {
b, err := decrypt(ctx.cryptoKey(), crypted)
if err != nil {
return errors.New("decrypting value failed").Wrap(err)
}
if err := json.Unmarshal(b, v); err != nil {
return errors.New("decoding value failed").Wrap(err)
}
return nil
}
func (ctx Context) cryptoKey() string {
return strings.ReplaceAll(ctx.DeviceID(), "-", "")
}
// Notifications accesses the notifications service.
func (ctx Context) Notifications() NotificationService {
return NotificationService{}
}
// Dispatch prompts the execution of a function on the UI goroutine,
// flagging the enclosing component for an update, respecting any
// implemented UpdateNotifier behavior.
func (ctx Context) Dispatch(v func(Context)) {
ctx.dispatch(func() {
if !ctx.sourceElement.Mounted() {
return
}
ctx.foreachUpdatableComponent(ctx.sourceElement, ctx.addComponentUpdate)
if v == nil {
return
}
v(ctx)
})
}
// Defer postpones the function execution on the UI goroutine until the
// current update cycle completes.
func (ctx Context) Defer(v func(Context)) {
ctx.defere(func() {
if !ctx.sourceElement.Mounted() {
return
}
if v == nil {
return
}
v(ctx)
})
}
// Async initiates a function asynchronously. It enables go-app to monitor
// goroutines, ensuring they conclude when rendering server-side.
func (ctx Context) Async(v func()) {
ctx.async(v)
}
// After pauses for a determined span, then triggers a specified function.
func (ctx Context) After(d time.Duration, f func(Context)) {
ctx.async(func() {
time.Sleep(d)
ctx.Dispatch(f)
})
}
// PreventUpdate halts updates for the enclosing component, respecting any
// implemented UpdateNotifier behavior.
func (ctx Context) PreventUpdate() {
ctx.foreachUpdatableComponent(ctx.sourceElement, ctx.removeComponentUpdate)
}
// Handle designates a handler for a particular action, set to run on the UI
// goroutine.
func (ctx Context) Handle(action string, h ActionHandler) {
ctx.handleAction(action, ctx.sourceElement, false, h)
}
// NewAction generates a new action for handling.
func (ctx Context) NewAction(action string, tags ...Tagger) {
ctx.NewActionWithValue(action, nil, tags...)
}
// NewActionWithValue crafts an action with a given value for processing.
func (ctx Context) NewActionWithValue(action string, v any, tags ...Tagger) {
var tagMap Tags
for _, tag := range tags {
if tagMap == nil {
tagMap = make(Tags)
}
for k, v := range tag.Tags() {
tagMap[k] = v
}
}
ctx.postAction(ctx, Action{
Name: action,
Value: v,
Tags: tagMap,
})
}
// ObserveState establishes an observer for a state, tracking its changes.
func (ctx Context) ObserveState(state string, recv any) ObserverX {
return ctx.observeState(ctx, state, recv)
}
// GetState fetches the value of a particular state.
func (ctx Context) GetState(state string, recv any) {
ctx.getState(ctx, state, recv)
}
// SetState modifies a state with the provided value.
func (ctx Context) SetState(state string, v any) StateX {
return ctx.setState(ctx, state, v)
}
// DelState erases a state, halting all associated observations.
func (ctx Context) DelState(state string) {
ctx.delState(ctx, state)
}
// TODO: see whether to deprecate
func (ctx Context) ResizeContent() {
ctx.Defer(func(ctx Context) {
ctx.Dispatch(func(ctx Context) {
ctx.notifyComponentEvent(ctx, ctx.Src(), resize{})
})
})
}