github.com/soypat/vectytemplater@v0.0.0-20220501050640-d40b24e35168/_templates/default/main.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "syscall/js" 6 7 "vecty-templater-project/store" 8 "vecty-templater-project/store/actions" 9 "vecty-templater-project/store/dispatcher" 10 "vecty-templater-project/views" 11 12 "github.com/hexops/vecty" 13 ) 14 15 func main() { 16 // OnAction must be registered before any storage manipulation. 17 dispatcher.Register(store.OnAction) 18 19 attachItemsStorage() 20 21 body := &views.Body{ 22 Ctx: store.Ctx, 23 } 24 store.Listeners.Add(body, func(interface{}) { 25 body.Ctx = store.Ctx 26 vecty.Rerender(body) 27 }) 28 vecty.RenderBody(body) 29 } 30 31 // attachItemsStorage provides persistent local storage saved on edits so 32 // no data is lost due to bad connection or refreshed page. 33 func attachItemsStorage() { 34 const key = "vecty_items" 35 store.Listeners.Add(nil, func(action interface{}) { 36 if _, ok := action.(*actions.NewItem); !ok { 37 // Only save state upon adding an item 38 return 39 } 40 // After item addition save state. 41 b, err := json.Marshal(&store.Items) 42 if err != nil { 43 panic(err) 44 } 45 js.Global().Get("localStorage").Set(key, string(b)) 46 }) 47 48 if data := js.Global().Get("localStorage").Get(key); !data.IsUndefined() { 49 // Old session data found, initialize store data. 50 err := json.Unmarshal([]byte(data.String()), &store.Items) 51 if err != nil { 52 panic(err) 53 } 54 } 55 }