context.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. package app
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/url"
  6. "strings"
  7. "time"
  8. "github.com/google/uuid"
  9. "github.com/maxence-charriere/go-app/v9/pkg/errors"
  10. )
  11. // Context is the interface that describes a context tied to a UI element.
  12. //
  13. // A context provides mechanisms to deal with the browser, the current page,
  14. // navigation, concurrency, and component communication.
  15. //
  16. // It is canceled when its associated UI element is dismounted.
  17. type Context interface {
  18. context.Context
  19. // Returns the UI element tied to the context.
  20. Src() UI
  21. // Returns the associated JavaScript value. The is an helper method for:
  22. // ctx.Src.JSValue()
  23. JSSrc() Value
  24. // Reports whether the app has been updated in background. Use app.Reload()
  25. // to load the updated version.
  26. AppUpdateAvailable() bool
  27. // Reports whether the app is installable.
  28. IsAppInstallable() bool
  29. // Shows the app install prompt if the app is installable.
  30. ShowAppInstallPrompt()
  31. // Returns the current page.
  32. Page() Page
  33. // Executes the given function on the UI goroutine and notifies the
  34. // context's nearest component to update its state.
  35. Dispatch(fn func(Context))
  36. // Executes the given function on the UI goroutine after notifying the
  37. // context's nearest component to update its state.
  38. Defer(fn func(Context))
  39. // Registers the handler for the given action name. When an action occurs,
  40. // the handler is executed on the UI goroutine.
  41. Handle(actionName string, h ActionHandler)
  42. // Creates an action with optional tags, to be handled with Context.Handle.
  43. // Eg:
  44. // ctx.NewAction("myAction")
  45. // ctx.NewAction("myAction", app.T("purpose", "test"))
  46. // ctx.NewAction("myAction", app.Tags{
  47. // "foo": "bar",
  48. // "hello": "world",
  49. // })
  50. NewAction(name string, tags ...Tagger)
  51. // Creates an action with a value and optional tags, to be handled with
  52. // Context.Handle. Eg:
  53. // ctx.NewActionWithValue("processValue", 42)
  54. // ctx.NewActionWithValue("processValue", 42, app.T("type", "number"))
  55. // ctx.NewActionWithValue("myAction", 42, app.Tags{
  56. // "foo": "bar",
  57. // "hello": "world",
  58. // })
  59. NewActionWithValue(name string, v any, tags ...Tagger)
  60. // Executes the given function on a new goroutine.
  61. //
  62. // The difference versus just launching a goroutine is that it ensures that
  63. // the asynchronous function is called before a page is fully pre-rendered
  64. // and served over HTTP.
  65. Async(fn func())
  66. // Asynchronously waits for the given duration and dispatches the given
  67. // function.
  68. After(d time.Duration, fn func(Context))
  69. // Executes the given function and notifies the parent components to update
  70. // their state. It should be used to launch component custom event handlers.
  71. Emit(fn func())
  72. // Reloads the WebAssembly app to the current page. It is like refreshing
  73. // the browser page.
  74. Reload()
  75. // Navigates to the given URL. This is a helper method that converts url to
  76. // an *url.URL and then calls ctx.NavigateTo under the hood.
  77. Navigate(url string)
  78. // Navigates to the given URL.
  79. NavigateTo(u *url.URL)
  80. // Resolves the given path to make it point to the right location whether
  81. // static resources are located on a local directory or a remote bucket.
  82. ResolveStaticResource(string) string
  83. // Returns a storage that uses the browser local storage associated to the
  84. // document origin. Data stored has no expiration time.
  85. LocalStorage() BrowserStorage
  86. // Returns a storage that uses the browser session storage associated to the
  87. // document origin. Data stored expire when the page session ends.
  88. SessionStorage() BrowserStorage
  89. // Scrolls to the HTML element with the given id.
  90. ScrollTo(id string)
  91. // Returns a UUID that identifies the app on the current device.
  92. DeviceID() string
  93. // Encrypts the given value using AES encryption.
  94. Encrypt(v any) ([]byte, error)
  95. // Decrypts the given encrypted bytes and stores them in the given value.
  96. Decrypt(crypted []byte, v any) error
  97. // Sets the state with the given value.
  98. // Example:
  99. // ctx.SetState("/globalNumber", 42, Persistent)
  100. //
  101. // Options can be added to persist a state into the local storage, encrypt,
  102. // expire, or broadcast the state across browser tabs and windows.
  103. // Example:
  104. // ctx.SetState("/globalNumber", 42, Persistent, Broadcast)
  105. SetState(state string, v any, opts ...StateOption)
  106. // Stores the specified state value into the given receiver. Panics when the
  107. // receiver is not a pointer or nil.
  108. GetState(state string, recv any)
  109. // Deletes the given state. All value observations are stopped.
  110. DelState(state string)
  111. // Creates an observer that observes changes for the given state.
  112. // Example:
  113. // type myComponent struct {
  114. // app.Compo
  115. //
  116. // number int
  117. // }
  118. //
  119. // func (c *myComponent) OnMount(ctx app.Context) {
  120. // ctx.ObserveState("/globalNumber").Value(&c.number)
  121. // }
  122. ObserveState(state string) Observer
  123. // Returns the app dispatcher.
  124. Dispatcher() Dispatcher
  125. // Returns the service to setup and display notifications.
  126. Notifications() NotificationService
  127. // Prevents the component that contains the context source to be updated.
  128. PreventUpdate()
  129. }
  130. type uiContext struct {
  131. context.Context
  132. src UI
  133. jsSrc Value
  134. appUpdateAvailable bool
  135. page Page
  136. disp Dispatcher
  137. }
  138. func (ctx uiContext) Src() UI {
  139. return ctx.src
  140. }
  141. func (ctx uiContext) JSSrc() Value {
  142. return ctx.jsSrc
  143. }
  144. func (ctx uiContext) AppUpdateAvailable() bool {
  145. return ctx.appUpdateAvailable
  146. }
  147. func (ctx uiContext) IsAppInstallable() bool {
  148. if Window().Get("goappIsAppInstallable").Truthy() {
  149. return Window().Call("goappIsAppInstallable").Bool()
  150. }
  151. return false
  152. }
  153. func (ctx uiContext) IsAppInstalled() bool {
  154. if Window().Get("goappIsAppInstalled").Truthy() {
  155. return Window().Call("goappIsAppInstalled").Bool()
  156. }
  157. return false
  158. }
  159. func (ctx uiContext) ShowAppInstallPrompt() {
  160. if ctx.IsAppInstallable() {
  161. Window().Call("goappShowInstallPrompt")
  162. }
  163. }
  164. func (ctx uiContext) Page() Page {
  165. return ctx.page
  166. }
  167. func (ctx uiContext) Dispatch(fn func(Context)) {
  168. ctx.Dispatcher().Dispatch(Dispatch{
  169. Mode: Update,
  170. Source: ctx.Src(),
  171. Function: fn,
  172. })
  173. }
  174. func (ctx uiContext) Defer(fn func(Context)) {
  175. ctx.Dispatcher().Dispatch(Dispatch{
  176. Mode: Defer,
  177. Source: ctx.Src(),
  178. Function: fn,
  179. })
  180. }
  181. func (ctx uiContext) Handle(actionName string, h ActionHandler) {
  182. ctx.Dispatcher().Handle(actionName, ctx.Src(), h)
  183. }
  184. func (ctx uiContext) NewAction(name string, tags ...Tagger) {
  185. ctx.NewActionWithValue(name, nil, tags...)
  186. }
  187. func (ctx uiContext) NewActionWithValue(name string, v any, tags ...Tagger) {
  188. var tagMap Tags
  189. for _, t := range tags {
  190. if tagMap == nil {
  191. tagMap = t.Tags()
  192. continue
  193. }
  194. for k, v := range t.Tags() {
  195. tagMap[k] = v
  196. }
  197. }
  198. ctx.Dispatcher().Post(Action{
  199. Name: name,
  200. Value: v,
  201. Tags: tagMap,
  202. })
  203. }
  204. func (ctx uiContext) Async(fn func()) {
  205. ctx.Dispatcher().Async(fn)
  206. }
  207. func (ctx uiContext) After(d time.Duration, fn func(Context)) {
  208. ctx.Async(func() {
  209. time.Sleep(d)
  210. ctx.Dispatch(fn)
  211. })
  212. }
  213. func (ctx uiContext) Emit(fn func()) {
  214. ctx.Dispatcher().Emit(ctx.Src(), fn)
  215. }
  216. func (ctx uiContext) Reload() {
  217. if IsServer {
  218. return
  219. }
  220. ctx.Defer(func(ctx Context) {
  221. Window().Get("location").Call("reload")
  222. })
  223. }
  224. func (ctx uiContext) Navigate(rawURL string) {
  225. ctx.Defer(func(ctx Context) {
  226. navigate(ctx.Dispatcher(), rawURL)
  227. })
  228. }
  229. func (ctx uiContext) NavigateTo(u *url.URL) {
  230. ctx.Defer(func(ctx Context) {
  231. navigateTo(ctx.Dispatcher(), u, true)
  232. })
  233. }
  234. func (ctx uiContext) ResolveStaticResource(path string) string {
  235. return ctx.Dispatcher().resolveStaticResource(path)
  236. }
  237. func (ctx uiContext) LocalStorage() BrowserStorage {
  238. return ctx.Dispatcher().getLocalStorage()
  239. }
  240. func (ctx uiContext) SessionStorage() BrowserStorage {
  241. return ctx.Dispatcher().getSessionStorage()
  242. }
  243. func (ctx uiContext) ScrollTo(id string) {
  244. ctx.Defer(func(ctx Context) {
  245. Window().ScrollToID(id)
  246. })
  247. }
  248. func (ctx uiContext) DeviceID() string {
  249. var id string
  250. if err := ctx.LocalStorage().Get("/go-app/deviceID", &id); err != nil {
  251. panic(errors.New("retrieving device id failed").Wrap(err))
  252. }
  253. if id != "" {
  254. return id
  255. }
  256. id = uuid.NewString()
  257. if err := ctx.LocalStorage().Set("/go-app/deviceID", id); err != nil {
  258. panic(errors.New("creating device id failed").Wrap(err))
  259. }
  260. return id
  261. }
  262. func (ctx uiContext) Encrypt(v any) ([]byte, error) {
  263. b, err := json.Marshal(v)
  264. if err != nil {
  265. return nil, errors.New("encoding value failed").Wrap(err)
  266. }
  267. b, err = encrypt(ctx.cryptoKey(), b)
  268. if err != nil {
  269. return nil, errors.New("encrypting value failed").Wrap(err)
  270. }
  271. return b, nil
  272. }
  273. func (ctx uiContext) Decrypt(crypted []byte, v any) error {
  274. b, err := decrypt(ctx.cryptoKey(), crypted)
  275. if err != nil {
  276. return errors.New("decrypting value failed").Wrap(err)
  277. }
  278. if err := json.Unmarshal(b, v); err != nil {
  279. return errors.New("decoding value failed").Wrap(err)
  280. }
  281. return nil
  282. }
  283. func (ctx uiContext) SetState(state string, v any, opts ...StateOption) {
  284. ctx.Dispatcher().SetState(state, v, opts...)
  285. }
  286. func (ctx uiContext) GetState(state string, recv any) {
  287. ctx.Dispatcher().GetState(state, recv)
  288. }
  289. func (ctx uiContext) DelState(state string) {
  290. ctx.Dispatcher().DelState(state)
  291. }
  292. func (ctx uiContext) ObserveState(state string) Observer {
  293. return ctx.Dispatcher().ObserveState(state, ctx.src)
  294. }
  295. func (ctx uiContext) Dispatcher() Dispatcher {
  296. return ctx.disp
  297. }
  298. func (ctx uiContext) Notifications() NotificationService {
  299. return NotificationService{dispatcher: ctx.Dispatcher()}
  300. }
  301. func (ctx uiContext) PreventUpdate() {
  302. ctx.Dispatcher().preventComponentUpdate(getComponent(ctx.src))
  303. }
  304. func (ctx uiContext) cryptoKey() string {
  305. return strings.ReplaceAll(ctx.DeviceID(), "-", "")
  306. }
  307. func makeContext(src UI) Context {
  308. return uiContext{
  309. Context: src.getContext(),
  310. src: src,
  311. jsSrc: src.JSValue(),
  312. appUpdateAvailable: appUpdateAvailable,
  313. page: src.getDispatcher().getCurrentPage(),
  314. disp: src.getDispatcher(),
  315. }
  316. }