clock.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package widget
  2. import (
  3. "errors"
  4. "fmt"
  5. "html/template"
  6. "time"
  7. "github.com/glanceapp/glance/internal/assets"
  8. )
  9. type Clock struct {
  10. widgetBase `yaml:",inline"`
  11. cachedHTML template.HTML `yaml:"-"`
  12. HourFormat string `yaml:"hour-format"`
  13. Timezones []struct {
  14. Timezone string `yaml:"timezone"`
  15. Label string `yaml:"label"`
  16. } `yaml:"timezones"`
  17. }
  18. func (widget *Clock) Initialize() error {
  19. widget.withTitle("Clock").withError(nil)
  20. if widget.HourFormat == "" {
  21. widget.HourFormat = "24h"
  22. } else if widget.HourFormat != "12h" && widget.HourFormat != "24h" {
  23. return errors.New("invalid hour format for clock widget, must be either 12h or 24h")
  24. }
  25. for t := range widget.Timezones {
  26. if widget.Timezones[t].Timezone == "" {
  27. return errors.New("missing timezone value for clock widget")
  28. }
  29. _, err := time.LoadLocation(widget.Timezones[t].Timezone)
  30. if err != nil {
  31. return fmt.Errorf("invalid timezone '%s' for clock widget: %v", widget.Timezones[t].Timezone, err)
  32. }
  33. }
  34. widget.cachedHTML = widget.render(widget, assets.ClockTemplate)
  35. return nil
  36. }
  37. func (widget *Clock) Render() template.HTML {
  38. return widget.cachedHTML
  39. }