Compare commits

..
5 Commits
Author SHA1 Message Date
Svilen Markov b37f8a8375 Merge pull request #194 from glanceapp/backport-fixes
Create release / release (push) Has been cancelled
Backport fixes from v0.6.0 to v0.5.0
2024-08-09 16:08:30 +01:00
Svilen Markov 139937f887 Fix missing RSS thumbnail images 2024-08-09 16:03:24 +01:00
Wyatt Gill b8b90451b6 Use GitHub's latest release API endpoint
The current releases widget uses the releases endpoint to pull the 10
most recent releases and filter them to find the latest release. This
causes a problem when a repository's latest release is outside of the 10
most recent (e.g. 10 prereleases):

ERROR No live release found repository=cross-seed/cross-seed url="https://api.github.com/repos/cross-seed/cross-seed/releases?per_page=10"

This is no longer a problem when using the latest release endpoint which
grabs the latest release, ignoring draft releases and prereleases.
2024-08-09 16:02:15 +01:00
Svilen Markov c9a2aff6a6 Fix search input color 2024-08-09 16:01:15 +01:00
Svilen Markov 82b6531a07 Add funding 2024-08-07 19:18:17 +01:00
33 changed files with 176 additions and 718 deletions
+1
View File
@@ -0,0 +1 @@
github: [glanceapp]
+1 -107
View File
@@ -13,7 +13,6 @@
- [Lobsters](#lobsters) - [Lobsters](#lobsters)
- [Reddit](#reddit) - [Reddit](#reddit)
- [Search](#search-widget) - [Search](#search-widget)
- [Group](#group)
- [Extension](#extension) - [Extension](#extension)
- [Weather](#weather) - [Weather](#weather)
- [Monitor](#monitor) - [Monitor](#monitor)
@@ -124,7 +123,6 @@ server:
| ---- | ---- | -------- | ------- | | ---- | ---- | -------- | ------- |
| host | string | no | | | host | string | no | |
| port | number | no | 8080 | | port | number | no | 8080 |
| base-url | string | no | |
| assets-path | string | no | | | assets-path | string | no | |
#### `host` #### `host`
@@ -133,9 +131,6 @@ The address which the server will listen on. Setting it to `localhost` means tha
#### `port` #### `port`
A number between 1 and 65,535, so long as that port isn't already used by anything else. A number between 1 and 65,535, so long as that port isn't already used by anything else.
#### `base-url`
The base URL that Glance is hosted under. No need to specify this unless you're using a reverse proxy and are hosting Glance under a directory. If that's the case then you can set this value to `/glance` or whatever the directory is called. Note that the forward slash (`/`) in the beginning is required unless you specify the full domain and path.
#### `assets-path` #### `assets-path`
The path to a directory that will be served by the server under the `/assets/` path. This is handy for widgets like the Monitor where you have to specify an icon URL and you want to self host all the icons rather than pointing to an external source. The path to a directory that will be served by the server under the `/assets/` path. This is handy for widgets like the Monitor where you have to specify an icon URL and you want to self host all the icons rather than pointing to an external source.
@@ -239,8 +234,6 @@ theme:
> .widget-type-rss a { > .widget-type-rss a {
> font-size: 1.5rem; > font-size: 1.5rem;
> } > }
>
> In addition, you can also use the `css-class` property which is available on every widget to set custom class names for individual widgets.
## Pages & Columns ## Pages & Columns
@@ -268,8 +261,6 @@ pages:
| ---- | ---- | -------- | ------- | | ---- | ---- | -------- | ------- |
| title | string | yes | | | title | string | yes | |
| slug | string | no | | | slug | string | no | |
| width | string | no | |
| hide-desktop-navigation | boolean | no | false |
| show-mobile-header | boolean | no | false | | show-mobile-header | boolean | no | false |
| columns | array | yes | | | columns | array | yes | |
@@ -279,21 +270,6 @@ The name of the page which gets shown in the navigation bar.
#### `slug` #### `slug`
The URL friendly version of the title which is used to access the page. For example if the title of the page is "RSS Feeds" you can make the page accessible via `localhost:8080/feeds` by setting the slug to `feeds`. If not defined, it will automatically be generated from the title. The URL friendly version of the title which is used to access the page. For example if the title of the page is "RSS Feeds" you can make the page accessible via `localhost:8080/feeds` by setting the slug to `feeds`. If not defined, it will automatically be generated from the title.
#### `width`
The maximum width of the page on desktop. Possible values are `slim` and `wide`.
* default: `1600px`
* slim: `1100px`
* wide: `1920px`
> [!NOTE]
>
> When using `slim`, the maximum number of columns allowed for that page is `2`.
#### `hide-desktop-navigation`
Whether to show the navigation links at the top of the page on desktop.
#### `show-mobile-header` #### `show-mobile-header`
Whether to show a header displaying the name of the page on mobile. The header purposefully has a lot of vertical whitespace in order to push the content down and make it easier to reach on tall devices. Whether to show a header displaying the name of the page on mobile. The header purposefully has a lot of vertical whitespace in order to push the content down and make it easier to reach on tall devices.
@@ -378,9 +354,7 @@ pages:
| ---- | ---- | -------- | | ---- | ---- | -------- |
| type | string | yes | | type | string | yes |
| title | string | no | | title | string | no |
| title-url | string | no |
| cache | string | no | | cache | string | no |
| css-class | string | no |
#### `type` #### `type`
Used to specify the widget. Used to specify the widget.
@@ -388,9 +362,6 @@ Used to specify the widget.
#### `title` #### `title`
The title of the widget. If left blank it will be defined by the widget. The title of the widget. If left blank it will be defined by the widget.
#### `title-url`
The URL to go to when clicking on the widget's title. If left blank it will be defined by the widget (if available).
#### `cache` #### `cache`
How long to keep the fetched data in memory. The value is a string and must be a number followed by one of s, m, h, d. Examples: How long to keep the fetched data in memory. The value is a string and must be a number followed by one of s, m, h, d. Examples:
@@ -405,9 +376,6 @@ cache: 1d # 1 day
> >
> Not all widgets can have their cache duration modified. The calendar and weather widgets update on the hour and this cannot be changed. > Not all widgets can have their cache duration modified. The calendar and weather widgets update on the hour and this cannot be changed.
#### `css-class`
Set custom CSS classes for the specific widget instance.
### RSS ### RSS
Display a list of articles from multiple RSS feeds. Display a list of articles from multiple RSS feeds.
@@ -505,7 +473,6 @@ Preview:
| limit | integer | no | 25 | | limit | integer | no | 25 |
| style | string | no | horizontal-cards | | style | string | no | horizontal-cards |
| collapse-after-rows | integer | no | 4 | | collapse-after-rows | integer | no | 4 |
| include-shorts | boolean | no | false |
| video-url-template | string | no | https://www.youtube.com/watch?v={VIDEO-ID} | | video-url-template | string | no | https://www.youtube.com/watch?v={VIDEO-ID} |
##### `channels` ##### `channels`
@@ -605,23 +572,11 @@ Preview:
#### Properties #### Properties
| Name | Type | Required | Default | | Name | Type | Required | Default |
| ---- | ---- | -------- | ------- | | ---- | ---- | -------- | ------- |
| instance-url | string | no | https://lobste.rs/ |
| custom-url | string | no | |
| limit | integer | no | 15 | | limit | integer | no | 15 |
| collapse-after | integer | no | 5 | | collapse-after | integer | no | 5 |
| sort-by | string | no | hot | | sort-by | string | no | hot |
| tags | array | no | | | tags | array | no | |
##### `instance-url`
The base URL for a lobsters instance hosted somewhere other than on lobste.rs. Example:
```yaml
instance-url: https://www.journalduhacker.net/
```
##### `custom-url`
A custom URL to retrieve lobsters posts from. If this is specified, the `instance-url`, `sort-by` and `tags` properties are ignored.
##### `limit` ##### `limit`
The maximum number of posts to show. The maximum number of posts to show.
@@ -769,16 +724,10 @@ Preview:
| <kbd>Ctrl</kbd> + <kbd>Enter</kbd> | Perform search in a new tab | Search input is focused and not empty | | <kbd>Ctrl</kbd> + <kbd>Enter</kbd> | Perform search in a new tab | Search input is focused and not empty |
| <kbd>Escape</kbd> | Leave focus | Search input is focused | | <kbd>Escape</kbd> | Leave focus | Search input is focused |
> [!TIP]
>
> You can use the property `new-tab` with a value of `true` if you want to show search results in a new tab by default. <kbd>Ctrl</kbd> + <kbd>Enter</kbd> will then show results in the same tab.
#### Properties #### Properties
| Name | Type | Required | Default | | Name | Type | Required | Default |
| ---- | ---- | -------- | ------- | | ---- | ---- | -------- | ------- |
| search-engine | string | no | duckduckgo | | search-engine | string | no | duckduckgo |
| new-tab | boolean | no | false |
| autofocus | boolean | no | false |
| bangs | array | no | | | bangs | array | no | |
##### `search-engine` ##### `search-engine`
@@ -789,12 +738,6 @@ Either a value from the table below or a URL to a custom search engine. Use `{QU
| duckduckgo | `https://duckduckgo.com/?q={QUERY}` | | duckduckgo | `https://duckduckgo.com/?q={QUERY}` |
| google | `https://www.google.com/search?q={QUERY}` | | google | `https://www.google.com/search?q={QUERY}` |
##### `new-tab`
When set to `true`, swaps the shortcuts for showing results in the same or new tab, defaulting to showing results in a new tab.
##### `new-tab`
When set to `true`, automatically focuses the search input on page load.
##### `bangs` ##### `bangs`
What now? [Bangs](https://duckduckgo.com/bangs). They're shortcuts that allow you to use the same search box for many different sites. Assuming you have it configured, if for example you start your search input with `!yt` you'd be able to perform a search on YouTube: What now? [Bangs](https://duckduckgo.com/bangs). They're shortcuts that allow you to use the same search box for many different sites. Assuming you have it configured, if for example you start your search input with `!yt` you'd be able to perform a search on YouTube:
@@ -829,50 +772,6 @@ url: https://store.steampowered.com/search/?term={QUERY}
url: https://www.amazon.com/s?k={QUERY} url: https://www.amazon.com/s?k={QUERY}
``` ```
### Group
Group multiple widgets into one using tabs. Widgets are defined using a `widgets` property exactly as you would on a page column. The only limitation is that you cannot place a group widget within a group widget.
Example:
```yaml
- type: group
widgets:
- type: reddit
subreddit: gamingnews
show-thumbnails: true
collapse-after: 6
- type: reddit
subreddit: games
- type: reddit
subreddit: pcgaming
show-thumbnails: true
```
Preview:
![](images/group-widget-preview.png)
#### Sharing properties
To avoid repetition you can use [YAML anchors](https://support.atlassian.com/bitbucket-cloud/docs/yaml-anchors/) and share properties between widgets.
Example:
```yaml
- type: group
define: &shared-properties
type: reddit
show-thumbnails: true
collapse-after: 6
widgets:
- subreddit: gamingnews
<<: *shared-properties
- subreddit: games
<<: *shared-properties
- subreddit: pcgaming
<<: *shared-properties
```
### Extension ### Extension
Display a widget provided by an external source (3rd party). If you want to learn more about developing extensions, checkout the [extensions documentation](extensions.md) (WIP). Display a widget provided by an external source (3rd party). If you want to learn more about developing extensions, checkout the [extensions documentation](extensions.md) (WIP).
@@ -1018,7 +917,6 @@ Properties for each site:
| ---- | ---- | -------- | ------- | | ---- | ---- | -------- | ------- |
| title | string | yes | | | title | string | yes | |
| url | string | yes | | | url | string | yes | |
| check-url | string | no | |
| icon | string | no | | | icon | string | no | |
| allow-insecure | boolean | no | false | | allow-insecure | boolean | no | false |
| same-tab | boolean | no | false | | same-tab | boolean | no | false |
@@ -1029,11 +927,7 @@ The title used to indicate the site.
`url` `url`
The public facing URL of a monitored service, the user will be redirected here. If `check-url` is not specified, this is used as the status check. The URL which will be requested and its response will determine the status of the site. Optionally, you can specify this using an environment variable with the syntax `${VARIABLE_NAME}`.
`check-url`
The URL which will be requested and its response will determine the status of the site. If not specified, the `url` property is used.
`icon` `icon`
Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

+4 -4
View File
@@ -1,19 +1,19 @@
module github.com/glanceapp/glance module github.com/glanceapp/glance
go 1.22.5 go 1.22.3
require ( require (
github.com/mmcdole/gofeed v1.3.0 github.com/mmcdole/gofeed v1.3.0
golang.org/x/text v0.16.0 golang.org/x/text v0.14.0
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
) )
require ( require (
github.com/PuerkitoBio/goquery v1.9.2 // indirect github.com/PuerkitoBio/goquery v1.9.1 // indirect
github.com/andybalholm/cascadia v1.3.2 // indirect github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/mmcdole/goxpp v1.1.1 // indirect github.com/mmcdole/goxpp v1.1.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
golang.org/x/net v0.27.0 // indirect golang.org/x/net v0.24.0 // indirect
) )
+6 -6
View File
@@ -1,5 +1,5 @@
github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE= github.com/PuerkitoBio/goquery v1.9.1 h1:mTL6XjbJTZdpfL+Gwl5U2h1l9yEkJjhmlTeV9VPW7UI=
github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk= github.com/PuerkitoBio/goquery v1.9.1/go.mod h1:cW1n6TmIMDoORQU5IU/P1T3tGFunOeXEpGP2WHRwkbY=
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss= github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU= github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -33,8 +33,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -54,8 +54,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
-41
View File
@@ -1,14 +1,8 @@
package assets package assets
import ( import (
"crypto/md5"
"embed" "embed"
"encoding/hex"
"io"
"io/fs" "io/fs"
"log/slog"
"strconv"
"time"
) )
//go:embed static //go:embed static
@@ -19,38 +13,3 @@ var _templateFS embed.FS
var PublicFS, _ = fs.Sub(_publicFS, "static") var PublicFS, _ = fs.Sub(_publicFS, "static")
var TemplateFS, _ = fs.Sub(_templateFS, "templates") var TemplateFS, _ = fs.Sub(_templateFS, "templates")
func getFSHash(files fs.FS) string {
hash := md5.New()
err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
file, err := files.Open(path)
if err != nil {
return err
}
if _, err := io.Copy(hash, file); err != nil {
return err
}
return nil
})
if err == nil {
return hex.EncodeToString(hash.Sum(nil))[:10]
}
slog.Warn("Could not compute assets cache", "err", err)
return strconv.FormatInt(time.Now().Unix(), 10)
}
var PublicFSHash = getFSHash(PublicFS)
+7 -87
View File
@@ -58,11 +58,6 @@
font-size: var(--font-size-h4); font-size: var(--font-size-h4);
} }
.page {
height: 100%;
padding-block: var(--widget-gap);
}
.page-content, .page.content-ready .page-loading-container { .page-content, .page.content-ready .page-loading-container {
display: none; display: none;
} }
@@ -189,57 +184,6 @@
transform: rotate(-90deg); transform: rotate(-90deg);
} }
.widget-group-header {
overflow-x: auto;
scrollbar-width: thin;
}
.widget-group-title {
background: none;
font: inherit;
border: none;
color: inherit;
text-transform: uppercase;
border-bottom: 1px solid transparent;
cursor: pointer;
flex-shrink: 0;
padding-bottom: 0.1rem;
transition: color .3s, border-color .3s;
}
.widget-group-title:hover:not(.widget-group-title-current) {
border-bottom-color: var(--color-text-subdue);
color: var(--color-text-highlight);
}
.widget-group-title-current {
border-bottom-color: var(--color-primary);
color: var(--color-text-highlight);
}
.widget-group-content {
animation: widgetGroupContentEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards;
}
.widget-group-content[data-direction="right"] {
--direction: 5px;
}
.widget-group-content[data-direction="left"] {
--direction: -5px;
}
@keyframes widgetGroupContentEntrance {
from {
opacity: 0;
transform: translateX(var(--direction));
}
}
.widget-group-content:not(.widget-group-content-current) {
display: none;
}
.widget-content:has(.expand-toggle-button:last-child) { .widget-content:has(.expand-toggle-button:last-child) {
padding-bottom: 0; padding-bottom: 0;
} }
@@ -316,14 +260,9 @@ html {
scroll-behavior: smooth; scroll-behavior: smooth;
} }
html, body {
height: 100%;
}
a { a {
text-decoration: none; text-decoration: none;
color: inherit; color: inherit;
overflow-wrap: break-word;
} }
ul { ul {
@@ -353,6 +292,7 @@ body {
.page-columns { .page-columns {
display: flex; display: flex;
gap: var(--widget-gap); gap: var(--widget-gap);
margin: var(--widget-gap) 0;
animation: pageColumnsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards; animation: pageColumnsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards;
} }
@@ -364,19 +304,13 @@ body {
} }
.page-loading-container { .page-loading-container {
height: 100%; margin: 50px auto;
display: flex; width: fit-content;
align-items: center;
justify-content: center;
animation: loadingContainerEntrance 200ms backwards; animation: loadingContainerEntrance 200ms backwards;
animation-delay: 150ms; animation-delay: 150ms;
font-size: 2rem; font-size: 2rem;
} }
.page-loading-container > .loading-icon {
translate: 0 -250%;
}
@keyframes loadingContainerEntrance { @keyframes loadingContainerEntrance {
from { from {
opacity: 0; opacity: 0;
@@ -438,19 +372,10 @@ kbd:active {
.content-bounds { .content-bounds {
max-width: 1600px; max-width: 1600px;
width: 100%;
margin-inline: auto; margin-inline: auto;
padding: 0 var(--content-bounds-padding); padding: 0 var(--content-bounds-padding);
} }
.page-width-wide .content-bounds {
max-width: 1920px;
}
.page-width-slim .content-bounds {
max-width: 1100px;
}
.dynamic-columns { .dynamic-columns {
gap: calc(var(--widget-content-vertical-padding) / 2); gap: calc(var(--widget-content-vertical-padding) / 2);
display: grid; display: grid;
@@ -669,8 +594,7 @@ kbd:active {
} }
.footer { .footer {
padding-bottom: calc(var(--widget-gap) * 1.5); margin-block: calc(var(--widget-gap) * 1.5);
padding-top: calc(var(--widget-gap) / 2);
animation: loadingContainerEntrance 200ms backwards; animation: loadingContainerEntrance 200ms backwards;
animation-delay: 150ms; animation-delay: 150ms;
} }
@@ -1243,9 +1167,8 @@ kbd:active {
} }
} }
.mobile-navigation-offset { body {
height: var(--mobile-navigation-height); padding-bottom: calc(var(--mobile-navigation-height) + var(--content-bounds-padding));
flex-shrink: 0;
} }
.mobile-navigation { .mobile-navigation {
@@ -1278,7 +1201,7 @@ kbd:active {
padding: 15px var(--content-bounds-padding); padding: 15px var(--content-bounds-padding);
display: flex; display: flex;
align-items: center; align-items: center;
overflow-x: auto; overflow-x: scroll;
gap: 2.5rem; gap: 2.5rem;
} }
@@ -1448,7 +1371,6 @@ kbd:active {
.shrink-0 { flex-shrink: 0; } .shrink-0 { flex-shrink: 0; }
.min-width-0 { min-width: 0; } .min-width-0 { min-width: 0; }
.max-width-100 { max-width: 100%; } .max-width-100 { max-width: 100%; }
.height-100 { height: 100%; }
.block { display: block; } .block { display: block; }
.inline-block { display: inline-block; } .inline-block { display: inline-block; }
.overflow-hidden { overflow: hidden; } .overflow-hidden { overflow: hidden; }
@@ -1470,7 +1392,6 @@ kbd:active {
.gap-7 { gap: 0.7rem; } .gap-7 { gap: 0.7rem; }
.gap-10 { gap: 1rem; } .gap-10 { gap: 1rem; }
.gap-15 { gap: 1.5rem; } .gap-15 { gap: 1.5rem; }
.gap-20 { gap: 2rem; }
.gap-25 { gap: 2.5rem; } .gap-25 { gap: 2.5rem; }
.gap-35 { gap: 3.5rem; } .gap-35 { gap: 3.5rem; }
.gap-45 { gap: 4.5rem; } .gap-45 { gap: 4.5rem; }
@@ -1480,7 +1401,6 @@ kbd:active {
.margin-top-7 { margin-top: 0.7rem; } .margin-top-7 { margin-top: 0.7rem; }
.margin-top-10 { margin-top: 1rem; } .margin-top-10 { margin-top: 1rem; }
.margin-top-15 { margin-top: 1.5rem; } .margin-top-15 { margin-top: 1.5rem; }
.margin-top-auto { margin-top: auto; }
.margin-block-3 { margin-block: 0.3rem; } .margin-block-3 { margin-block: 0.3rem; }
.margin-block-5 { margin-block: 0.5rem; } .margin-block-5 { margin-block: 0.5rem; }
.margin-block-7 { margin-block: 0.7rem; } .margin-block-7 { margin-block: 0.7rem; }
+15 -56
View File
@@ -21,10 +21,10 @@ function throttledDebounce(callback, maxDebounceTimes, debounceDelay) {
}; };
async function fetchPageContent(pageData) { async function fetchPageContent(pageSlug) {
// TODO: handle non 200 status codes/time outs // TODO: handle non 200 status codes/time outs
// TODO: add retries // TODO: add retries
const response = await fetch(`${pageData.baseURL}/api/pages/${pageData.slug}/content/`); const response = await fetch(`/api/pages/${pageSlug}/content/`);
const content = await response.text(); const content = await response.text();
return content; return content;
@@ -107,7 +107,7 @@ function updateRelativeTimeForElements(elements)
} }
} }
function setupSearchBoxes() { function setupSearchboxes() {
const searchWidgets = document.getElementsByClassName("search"); const searchWidgets = document.getElementsByClassName("search");
if (searchWidgets.length == 0) { if (searchWidgets.length == 0) {
@@ -117,7 +117,6 @@ function setupSearchBoxes() {
for (let i = 0; i < searchWidgets.length; i++) { for (let i = 0; i < searchWidgets.length; i++) {
const widget = searchWidgets[i]; const widget = searchWidgets[i];
const defaultSearchUrl = widget.dataset.defaultSearchUrl; const defaultSearchUrl = widget.dataset.defaultSearchUrl;
const newTab = widget.dataset.newTab === "true";
const inputElement = widget.getElementsByClassName("search-input")[0]; const inputElement = widget.getElementsByClassName("search-input")[0];
const bangElement = widget.getElementsByClassName("search-bang")[0]; const bangElement = widget.getElementsByClassName("search-bang")[0];
const bangs = widget.querySelectorAll(".search-bangs > input"); const bangs = widget.querySelectorAll(".search-bangs > input");
@@ -148,13 +147,14 @@ function setupSearchBoxes() {
query = input; query = input;
searchUrlTemplate = defaultSearchUrl; searchUrlTemplate = defaultSearchUrl;
} }
if (query.length == 0 && currentBang == null) {
if (query.length == 0) {
return; return;
} }
const url = searchUrlTemplate.replace("!QUERY!", encodeURIComponent(query)); const url = searchUrlTemplate.replace("!QUERY!", encodeURIComponent(query));
if (newTab && !event.ctrlKey || !newTab && event.ctrlKey) { if (event.ctrlKey) {
window.open(url, '_blank').focus(); window.open(url, '_blank').focus();
} else { } else {
window.location.href = url; window.location.href = url;
@@ -170,13 +170,9 @@ function setupSearchBoxes() {
} }
const handleInput = (event) => { const handleInput = (event) => {
const value = event.target.value.trim(); const value = event.target.value.trimStart();
if (value in bangsMap) {
changeCurrentBang(bangsMap[value]);
return;
}
const words = value.split(" "); const words = value.split(" ");
if (words.length >= 2 && words[0] in bangsMap) { if (words.length >= 2 && words[0] in bangsMap) {
changeCurrentBang(bangsMap[words[0]]); changeCurrentBang(bangsMap[words[0]]);
return; return;
@@ -250,46 +246,6 @@ function setupDynamicRelativeTime() {
}); });
} }
function setupGroups() {
const groups = document.getElementsByClassName("widget-type-group");
if (groups.length == 0) {
return;
}
for (let g = 0; g < groups.length; g++) {
const group = groups[g];
const titles = group.getElementsByClassName("widget-header")[0].children;
const tabs = group.getElementsByClassName("widget-group-contents")[0].children;
let current = 0;
for (let t = 0; t < titles.length; t++) {
const title = titles[t];
title.addEventListener("click", () => {
if (t == current) {
return;
}
for (let i = 0; i < titles.length; i++) {
titles[i].classList.remove("widget-group-title-current");
tabs[i].classList.remove("widget-group-content-current");
}
if (current < t) {
tabs[t].dataset.direction = "right";
} else {
tabs[t].dataset.direction = "left";
}
current = t;
title.classList.add("widget-group-title-current");
tabs[t].classList.add("widget-group-content-current");
});
}
}
}
function setupLazyImages() { function setupLazyImages() {
const images = document.querySelectorAll("img[loading=lazy]"); const images = document.querySelectorAll("img[loading=lazy]");
@@ -588,17 +544,16 @@ function setupClocks() {
async function setupPage() { async function setupPage() {
const pageElement = document.getElementById("page"); const pageElement = document.getElementById("page");
const pageContentElement = document.getElementById("page-content"); const pageContentElement = document.getElementById("page-content");
const pageContent = await fetchPageContent(pageData); const pageContent = await fetchPageContent(pageData.slug);
pageContentElement.innerHTML = pageContent; pageContentElement.innerHTML = pageContent;
try { try {
setupClocks() setupClocks()
setupCarousels(); setupCarousels();
setupSearchBoxes(); setupSearchboxes();
setupCollapsibleLists(); setupCollapsibleLists();
setupCollapsibleGrids(); setupCollapsibleGrids();
setupGroups();
setupDynamicRelativeTime(); setupDynamicRelativeTime();
setupLazyImages(); setupLazyImages();
} finally { } finally {
@@ -614,4 +569,8 @@ async function setupPage() {
} }
} }
setupPage(); if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", setupPage);
} else {
setupPage();
}
+1 -1
View File
@@ -6,7 +6,7 @@
"start_url": "/", "start_url": "/",
"icons": [ "icons": [
{ {
"src": "app-icon.png", "src": "/static/app-icon.png",
"type": "image/png", "type": "image/png",
"sizes": "512x512" "sizes": "512x512"
} }
-1
View File
@@ -37,7 +37,6 @@ var (
RepositoryTemplate = compileTemplate("repository.html", "widget-base.html") RepositoryTemplate = compileTemplate("repository.html", "widget-base.html")
SearchTemplate = compileTemplate("search.html", "widget-base.html") SearchTemplate = compileTemplate("search.html", "widget-base.html")
ExtensionTemplate = compileTemplate("extension.html", "widget-base.html") ExtensionTemplate = compileTemplate("extension.html", "widget-base.html")
GroupTemplate = compileTemplate("group.html", "widget-base.html")
) )
var globalTemplateFunctions = template.FuncMap{ var globalTemplateFunctions = template.FuncMap{
+6 -6
View File
@@ -11,12 +11,12 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Glance"> <meta name="apple-mobile-web-app-title" content="Glance">
<meta name="theme-color" content="{{ if ne nil .App.Config.Theme.BackgroundColor }}{{ .App.Config.Theme.BackgroundColor }}{{ else }}hsl(240, 8%, 9%){{ end }}"> <meta name="theme-color" content="{{ if ne nil .App.Config.Theme.BackgroundColor }}{{ .App.Config.Theme.BackgroundColor }}{{ else }}hsl(240, 8%, 9%){{ end }}">
<link rel="apple-touch-icon" sizes="512x512" href="{{ .App.AssetPath "app-icon.png" }}"> <link rel="apple-touch-icon" sizes="512x512" href="/static/app-icon.png">
<link rel="icon" type="image/png" sizes="50x50" href="{{ .App.AssetPath "favicon.png" }}"> <link rel="icon" type="image/png" sizes="50x50" href="/static/favicon.png">
<link rel="manifest" href="{{ .App.AssetPath "manifest.json" }}"> <link rel="manifest" href="/static/manifest.json">
<link rel="icon" type="image/png" href="{{ .App.AssetPath "favicon.png" }}" /> <link rel="icon" type="image/png" href="/static/favicon.png" />
<link rel="stylesheet" href="{{ .App.AssetPath "main.css" }}"> <link rel="stylesheet" href="/static/main.css?v={{ .App.Config.Server.StartedAt.Unix }}">
<script type="module" src="{{ .App.AssetPath "main.js" }}"></script> <script async src="/static/main.js?v={{ .App.Config.Server.StartedAt.Unix }}"></script>
{{ block "document-head-after" . }}{{ end }} {{ block "document-head-after" . }}{{ end }}
</head> </head>
<body> <body>
-20
View File
@@ -1,20 +0,0 @@
{{ template "widget-base.html" . }}
{{ define "widget-content-classes" }}widget-content-frameless{{ end }}
{{ define "widget-content" }}
<div class="widget-group-header">
<div class="widget-header gap-20">
{{ range $i, $widget := .Widgets }}
<button class="widget-group-title{{ if eq $i 0 }} widget-group-title-current{{ end }}">{{ $widget.Title }}</button>
{{ end }}
</div>
</div>
<div class="widget-group-contents">
{{ range $i, $widget := .Widgets }}
<div class="widget-group-content{{ if eq $i 0 }} widget-group-content-current{{ end }}">{{ .Render }}</div>
{{ end }}
</div>
{{ end }}
+33 -40
View File
@@ -1,18 +1,16 @@
{{ template "document.html" . }} {{ template "document.html" . }}
{{ define "document-title" }}{{ .Page.Title }}{{ end }} {{ define "document-title" }}{{ .Page.Title }} - Glance{{ end }}
{{ define "document-head-before" }} {{ define "document-head-before" }}
<script> <script>
const pageData = { const pageData = {
slug: "{{ .Page.Slug }}", slug: "{{ .Page.Slug }}",
baseURL: "{{ .App.Config.Server.BaseURL }}",
}; };
</script> </script>
{{ end }} {{ end }}
{{ define "document-root-attrs" }}class="{{ if .App.Config.Theme.Light }}light-scheme {{ end }}{{ if ne "" .Page.Width }}page-width-{{ .Page.Width }}{{ end }}"{{ end }} {{ define "document-root-attrs" }}{{ if .App.Config.Theme.Light }}class="light-scheme"{{ end }}{{ end }}
{{ define "document-head-after" }} {{ define "document-head-after" }}
{{ template "page-style-overrides.gotmpl" . }} {{ template "page-style-overrides.gotmpl" . }}
{{ if ne "" .App.Config.Theme.CustomCSSFile }} {{ if ne "" .App.Config.Theme.CustomCSSFile }}
@@ -22,53 +20,48 @@
{{ define "navigation-links" }} {{ define "navigation-links" }}
{{ range .App.Config.Pages }} {{ range .App.Config.Pages }}
<a href="{{ $.App.Config.Server.BaseURL }}/{{ .Slug }}" class="nav-item{{ if eq .Slug $.Page.Slug }} nav-item-current{{ end }}">{{ .Title }}</a> <a href="/{{ .Slug }}" class="nav-item{{ if eq .Slug $.Page.Slug }} nav-item-current{{ end }}">{{ .Title }}</a>
{{ end }} {{ end }}
{{ end }} {{ end }}
{{ define "document-body" }} {{ define "document-body" }}
<div class="flex flex-column height-100"> <div class="header-container content-bounds">
{{ if not .Page.HideDesktopNavigation }} <div class="header flex padding-inline-widget widget-content-frame">
<div class="header-container content-bounds"> <!-- TODO: Replace G with actual logo, first need an actual logo -->
<div class="header flex padding-inline-widget widget-content-frame"> <div class="logo">G</div>
<!-- TODO: Replace G with actual logo, first need an actual logo --> <div class="nav flex grow">
<div class="logo">G</div>
<div class="nav flex grow">
{{ template "navigation-links" . }}
</div>
</div>
</div>
{{ end }}
<div class="mobile-navigation">
<div class="mobile-navigation-icons">
<a class="mobile-navigation-label" href="#top"></a>
{{ range $i, $column := .Page.Columns }}
<label class="mobile-navigation-label"><input type="radio" class="mobile-navigation-input" name="column" value="{{ $i }}" autocomplete="off"{{ if eq "full" $column.Size }} checked{{ end }}><div class="mobile-navigation-pill"></div></label>
{{ end }}
<label class="mobile-navigation-label"><input type="checkbox" class="mobile-navigation-page-links-input" autocomplete="on"><div class="hamburger-icon"></div></label>
</div>
<div class="mobile-navigation-page-links">
{{ template "navigation-links" . }} {{ template "navigation-links" . }}
</div> </div>
</div> </div>
</div>
<div class="content-bounds grow"> <div class="mobile-navigation">
<div class="page" id="page"> <div class="mobile-navigation-icons">
<div class="page-content" id="page-content"></div> <a class="mobile-navigation-label" href="#top"></a>
<div class="page-loading-container"> {{ range $i, $column := .Page.Columns }}
<!-- TODO: add a bigger/better loading indicator --> <label class="mobile-navigation-label"><input type="radio" class="mobile-navigation-input" name="column" value="{{ $i }}" autocomplete="off"{{ if eq "full" $column.Size }} checked{{ end }}><div class="mobile-navigation-pill"></div></label>
<div class="loading-icon"></div> {{ end }}
</div> <label class="mobile-navigation-label"><input type="checkbox" class="mobile-navigation-page-links-input" autocomplete="on"><div class="hamburger-icon"></div></label>
</div>
<div class="mobile-navigation-page-links">
{{ template "navigation-links" . }}
</div>
</div>
<div class="content-bounds">
<div class="page" id="page">
<div class="page-content" id="page-content"></div>
<div class="page-loading-container">
<!-- TODO: add a bigger/better loading indicator -->
<div class="loading-icon"></div>
</div> </div>
</div> </div>
</div>
<div class="footer flex items-center flex-column"> <div class="footer flex items-center flex-column">
<div> <div>
<a class="size-h3" href="https://github.com/glanceapp/glance" target="_blank" rel="noreferrer">Glance</a> {{ if ne "dev" .App.Version }}<a class="visited-indicator" title="Release notes" href="https://github.com/glanceapp/glance/releases/tag/{{ .App.Version }}" target="_blank" rel="noreferrer">{{ .App.Version }}</a>{{ else }}({{ .App.Version }}){{ end }} <a class="size-h3" href="https://github.com/glanceapp/glance" target="_blank" rel="noreferrer">Glance</a> {{ if ne "dev" .App.Version }}<a class="visited-indicator" title="Release notes" href="https://github.com/glanceapp/glance/releases/tag/{{ .App.Version }}" target="_blank" rel="noreferrer">{{ .App.Version }}</a>{{ else }}({{ .App.Version }}){{ end }}
</div>
</div> </div>
<a class="color-primary block margin-top-5 size-h5" href="https://github.com/glanceapp/glance/issues" target="_blank" rel="noreferrer">Report issue</a>
<div class="mobile-navigation-offset"></div>
</div> </div>
{{ end }} {{ end }}
+2 -2
View File
@@ -3,7 +3,7 @@
{{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }}
{{ define "widget-content" }} {{ define "widget-content" }}
<div class="search widget-content-frame padding-inline-widget flex gap-15 items-center" data-default-search-url="{{ .SearchEngine }}" data-new-tab="{{ .NewTab }}"> <div class="search widget-content-frame padding-inline-widget flex gap-15 items-center" data-default-search-url="{{ .SearchEngine }}">
<div class="search-bangs"> <div class="search-bangs">
{{ range .Bangs }} {{ range .Bangs }}
<input type="hidden" data-shortcut="{{ .Shortcut }}" data-title="{{ .Title }}" data-url="{{ .URL }}"> <input type="hidden" data-shortcut="{{ .Shortcut }}" data-title="{{ .Title }}" data-url="{{ .URL }}">
@@ -16,7 +16,7 @@
</svg> </svg>
</div> </div>
<input class="search-input" type="text" placeholder="Type here to search…" autocomplete="off"{{ if .Autofocus }} autofocus{{ end }}> <input class="search-input" type="text" placeholder="Type here to search…" autocomplete="off">
<div class="search-bang"></div> <div class="search-bang"></div>
<kbd class="hide-on-mobile" title="Press [S] to focus the search input">S</kbd> <kbd class="hide-on-mobile" title="Press [S] to focus the search input">S</kbd>
@@ -7,9 +7,7 @@
<div class="{{ if .IsLive }}twitch-channel-live {{ end }}flex gap-10 items-start thumbnail-parent"> <div class="{{ if .IsLive }}twitch-channel-live {{ end }}flex gap-10 items-start thumbnail-parent">
<div class="twitch-channel-avatar-container"> <div class="twitch-channel-avatar-container">
{{ if .Exists }} {{ if .Exists }}
<a href="https://twitch.tv/{{ .Login }}" class="twitch-channel-avatar-link" target="_blank" rel="noreferrer"> <img class="twitch-channel-avatar thumbnail" src="{{ .AvatarUrl }}" alt="" loading="lazy">
<img class="twitch-channel-avatar thumbnail" src="{{ .AvatarUrl }}" alt="" loading="lazy">
</a>
{{ else }} {{ else }}
<svg class="twitch-channel-avatar thumbnail" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"> <svg class="twitch-channel-avatar thumbnail" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z" /> <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z" />
@@ -20,9 +18,7 @@
<a href="https://twitch.tv/{{ .Login }}" class="size-h3{{ if .IsLive }} color-highlight{{ end }} block text-truncate" target="_blank" rel="noreferrer">{{ .Name }}</a> <a href="https://twitch.tv/{{ .Login }}" class="size-h3{{ if .IsLive }} color-highlight{{ end }} block text-truncate" target="_blank" rel="noreferrer">{{ .Name }}</a>
{{ if .Exists }} {{ if .Exists }}
{{ if .IsLive }} {{ if .IsLive }}
{{ if .Category }} <a class="text-truncate block" href="https://www.twitch.tv/directory/category/{{ .CategorySlug }}" target="_blank" rel="noreferrer">{{ .Category }}</a>
<a class="text-truncate block" href="https://www.twitch.tv/directory/category/{{ .CategorySlug }}" target="_blank" rel="noreferrer">{{ .Category }}</a>
{{ end }}
<ul class="list-horizontal-text"> <ul class="list-horizontal-text">
<li {{ dynamicRelativeTimeAttrs .LiveSince }}></li> <li {{ dynamicRelativeTimeAttrs .LiveSince }}></li>
<li>{{ .ViewersCount | formatViewerCount }} viewers</li> <li>{{ .ViewersCount | formatViewerCount }} viewers</li>
+3 -5
View File
@@ -1,15 +1,13 @@
<div class="widget widget-type-{{ .GetType }}{{ if ne "" .CSSClass }} {{ .CSSClass }}{{ end }}"> <div class="widget widget-type-{{ .GetType }}">
{{ if not .HideHeader}}
<div class="widget-header"> <div class="widget-header">
{{ if ne "" .TitleURL}}<a href="{{ .TitleURL }}" target="_blank" rel="noreferrer" class="uppercase">{{ .Title }}</a>{{ else }}<div class="uppercase">{{ .Title }}</div>{{ end }} <div class="uppercase">{{ .Title }}</div>
{{ if and .Error .ContentAvailable }} {{ if and .Error .ContentAvailable }}
<div class="notice-icon notice-icon-major" title="{{ .Error }}"></div> <div class="notice-icon notice-icon-major" title="{{ .Error }}"></div>
{{ else if .Notice }} {{ else if .Notice }}
<div class="notice-icon notice-icon-minor" title="{{ .Notice }}"></div> <div class="notice-icon notice-icon-minor" title="{{ .Notice }}"></div>
{{ end }} {{ end }}
</div> </div>
{{ end }} <div class="widget-content {{ if .ContentAvailable }}{{ block "widget-content-classes" . }}{{ end }}{{ end }}">
<div class="widget-content{{ if .ContentAvailable }} {{ block "widget-content-classes" . }}{{ end }}{{ end }}">
{{ if .ContentAvailable }} {{ if .ContentAvailable }}
{{ block "widget-content" . }}{{ end }} {{ block "widget-content" . }}{{ end }}
{{ else }} {{ else }}
+11 -21
View File
@@ -55,30 +55,20 @@ func getLobstersPostsFromFeed(feedUrl string) (ForumPosts, error) {
return posts, nil return posts, nil
} }
func FetchLobstersPosts(customURL string, instanceURL string, sortBy string, tags []string) (ForumPosts, error) { func FetchLobstersPosts(sortBy string, tags []string) (ForumPosts, error) {
var feedUrl string var feedUrl string
if customURL != "" { if sortBy == "hot" {
feedUrl = customURL sortBy = "hottest"
} else if sortBy == "new" {
sortBy = "newest"
}
if len(tags) == 0 {
feedUrl = "https://lobste.rs/" + sortBy + ".json"
} else { } else {
if instanceURL != "" { tags := strings.Join(tags, ",")
instanceURL = strings.TrimRight(instanceURL, "/") + "/" feedUrl = "https://lobste.rs/t/" + tags + ".json"
} else {
instanceURL = "https://lobste.rs/"
}
if sortBy == "hot" {
sortBy = "hottest"
} else if sortBy == "new" {
sortBy = "newest"
}
if len(tags) == 0 {
feedUrl = instanceURL + sortBy + ".json"
} else {
tags := strings.Join(tags, ",")
feedUrl = instanceURL + "t/" + tags + ".json"
}
} }
posts, err := getLobstersPostsFromFeed(feedUrl) posts, err := getLobstersPostsFromFeed(feedUrl)
+1 -8
View File
@@ -9,7 +9,6 @@ import (
type SiteStatusRequest struct { type SiteStatusRequest struct {
URL string `yaml:"url"` URL string `yaml:"url"`
CheckURL string `yaml:"check-url"`
AllowInsecure bool `yaml:"allow-insecure"` AllowInsecure bool `yaml:"allow-insecure"`
} }
@@ -21,13 +20,7 @@ type SiteStatus struct {
} }
func getSiteStatusTask(statusRequest *SiteStatusRequest) (SiteStatus, error) { func getSiteStatusTask(statusRequest *SiteStatusRequest) (SiteStatus, error) {
var url string request, err := http.NewRequest(http.MethodGet, statusRequest.URL, nil)
if statusRequest.CheckURL != "" {
url = statusRequest.CheckURL
} else {
url = statusRequest.URL
}
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil { if err != nil {
return SiteStatus{ return SiteStatus{
+23 -35
View File
@@ -44,25 +44,12 @@ func sanitizeFeedDescription(description string) string {
return description return description
} }
func shortenFeedDescriptionLen(description string, maxLen int) string {
description, _ = limitStringLength(description, 1000)
description = sanitizeFeedDescription(description)
description, limited := limitStringLength(description, maxLen)
if limited {
description += "…"
}
return description
}
type RSSFeedRequest struct { type RSSFeedRequest struct {
Url string `yaml:"url"` Url string `yaml:"url"`
Title string `yaml:"title"` Title string `yaml:"title"`
HideCategories bool `yaml:"hide-categories"` HideCategories bool `yaml:"hide-categories"`
HideDescription bool `yaml:"hide-description"` HideDescription bool `yaml:"hide-description"`
ItemLinkPrefix string `yaml:"item-link-prefix"` ItemLinkPrefix string `yaml:"item-link-prefix"`
IsDetailed bool `yaml:"-"`
} }
type RSSFeedItems []RSSFeedItem type RSSFeedItems []RSSFeedItem
@@ -94,6 +81,7 @@ func getItemsFromRSSFeedTask(request RSSFeedRequest) ([]RSSFeedItem, error) {
rssItem := RSSFeedItem{ rssItem := RSSFeedItem{
ChannelURL: feed.Link, ChannelURL: feed.Link,
Title: item.Title,
} }
if request.ItemLinkPrefix != "" { if request.ItemLinkPrefix != "" {
@@ -120,34 +108,34 @@ func getItemsFromRSSFeedTask(request RSSFeedRequest) ([]RSSFeedItem, error) {
} }
} }
if item.Title != "" { if !request.HideDescription && item.Description != "" {
rssItem.Title = item.Title description, _ := limitStringLength(item.Description, 1000)
} else { description = sanitizeFeedDescription(description)
rssItem.Title = shortenFeedDescriptionLen(item.Description, 100) description, limited := limitStringLength(description, 200)
if limited {
description += "…"
}
rssItem.Description = description
} }
if request.IsDetailed { if !request.HideCategories {
if !request.HideDescription && item.Description != "" && item.Title != "" { var categories = make([]string, 0, 6)
rssItem.Description = shortenFeedDescriptionLen(item.Description, 200)
}
if !request.HideCategories { for _, category := range item.Categories {
var categories = make([]string, 0, 6) if len(categories) == 6 {
break
for _, category := range item.Categories {
if len(categories) == 6 {
break
}
if len(category) == 0 || len(category) > 30 {
continue
}
categories = append(categories, category)
} }
rssItem.Categories = categories if len(category) == 0 || len(category) > 30 {
continue
}
categories = append(categories, category)
} }
rssItem.Categories = categories
} }
if request.Title != "" { if request.Title != "" {
+3 -5
View File
@@ -204,11 +204,9 @@ func fetchChannelFromTwitchTask(channel string) (TwitchChannel, error) {
result.IsLive = true result.IsLive = true
result.ViewersCount = channelShell.UserOrError.Stream.ViewersCount result.ViewersCount = channelShell.UserOrError.Stream.ViewersCount
if streamMetadata.UserOrNull != nil && streamMetadata.UserOrNull.Stream != nil { if streamMetadata.UserOrNull != nil && streamMetadata.UserOrNull.Stream != nil && streamMetadata.UserOrNull.Stream.Game != nil {
if streamMetadata.UserOrNull.Stream.Game != nil { result.Category = streamMetadata.UserOrNull.Stream.Game.Name
result.Category = streamMetadata.UserOrNull.Stream.Game.Name result.CategorySlug = streamMetadata.UserOrNull.Stream.Game.Slug
result.CategorySlug = streamMetadata.UserOrNull.Stream.Game.Slug
}
startedAt, err := time.Parse("2006-01-02T15:04:05Z", streamMetadata.UserOrNull.Stream.StartedAt) startedAt, err := time.Parse("2006-01-02T15:04:05Z", streamMetadata.UserOrNull.Stream.StartedAt)
if err == nil { if err == nil {
+9 -11
View File
@@ -10,7 +10,7 @@ import (
) )
type youtubeFeedResponseXml struct { type youtubeFeedResponseXml struct {
Channel string `xml:"author>name"` Channel string `xml:"title"`
ChannelLink struct { ChannelLink struct {
Href string `xml:"href,attr"` Href string `xml:"href,attr"`
} `xml:"link"` } `xml:"link"`
@@ -39,19 +39,11 @@ func parseYoutubeFeedTime(t string) time.Time {
return parsedTime return parsedTime
} }
func FetchYoutubeChannelUploads(channelIds []string, videoUrlTemplate string, includeShorts bool) (Videos, error) { func FetchYoutubeChannelUploads(channelIds []string, videoUrlTemplate string) (Videos, error) {
requests := make([]*http.Request, 0, len(channelIds)) requests := make([]*http.Request, 0, len(channelIds))
for i := range channelIds { for i := range channelIds {
var feedUrl string request, _ := http.NewRequest("GET", "https://www.youtube.com/feeds/videos.xml?channel_id="+channelIds[i], nil)
if !includeShorts && strings.HasPrefix(channelIds[i], "UC") {
playlistId := strings.Replace(channelIds[i], "UC", "UULF", 1)
feedUrl = "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlistId
} else {
feedUrl = "https://www.youtube.com/feeds/videos.xml?channel_id=" + channelIds[i]
}
request, _ := http.NewRequest("GET", feedUrl, nil)
requests = append(requests, request) requests = append(requests, request)
} }
@@ -78,6 +70,12 @@ func FetchYoutubeChannelUploads(channelIds []string, videoUrlTemplate string, in
for j := range response.Videos { for j := range response.Videos {
video := &response.Videos[j] video := &response.Videos[j]
// TODO: figure out a better way of skipping shorts
if strings.Contains(video.Title, "#shorts") {
continue
}
var videoUrl string var videoUrl string
if videoUrlTemplate == "" { if videoUrlTemplate == "" {
+2 -22
View File
@@ -32,16 +32,6 @@ func NewConfigFromYml(contents io.Reader) (*Config, error) {
return nil, err return nil, err
} }
for p := range config.Pages {
for c := range config.Pages[p].Columns {
for w := range config.Pages[p].Columns[c].Widgets {
if err := config.Pages[p].Columns[c].Widgets[w].Initialize(); err != nil {
return nil, err
}
}
}
}
return config, nil return config, nil
} }
@@ -60,22 +50,12 @@ func configIsValid(config *Config) error {
return fmt.Errorf("Page %d has no title", i+1) return fmt.Errorf("Page %d has no title", i+1)
} }
if config.Pages[i].Width != "" && (config.Pages[i].Width != "wide" && config.Pages[i].Width != "slim") {
return fmt.Errorf("Page %d: width can only be either wide or slim", i+1)
}
if len(config.Pages[i].Columns) == 0 { if len(config.Pages[i].Columns) == 0 {
return fmt.Errorf("Page %d has no columns", i+1) return fmt.Errorf("Page %d has no columns", i+1)
} }
if config.Pages[i].Width == "slim" { if len(config.Pages[i].Columns) > 3 {
if len(config.Pages[i].Columns) > 2 { return fmt.Errorf("Page %d has more than 3 columns: %d", i+1, len(config.Pages[i].Columns))
return fmt.Errorf("Page %d is slim and cannot have more than 2 columns", i+1)
}
} else {
if len(config.Pages[i].Columns) > 3 {
return fmt.Errorf("Page %d has more than 3 columns: %d", i+1, len(config.Pages[i].Columns))
}
} }
columnSizesCount := make(map[string]int) columnSizesCount := make(map[string]int)
+12 -68
View File
@@ -8,7 +8,6 @@ import (
"net/http" "net/http"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -25,7 +24,6 @@ type Application struct {
Version string Version string
Config Config Config Config
slugToPage map[string]*Page slugToPage map[string]*Page
widgetByID map[uint64]widget.Widget
} }
type Theme struct { type Theme struct {
@@ -43,9 +41,7 @@ type Server struct {
Host string `yaml:"host"` Host string `yaml:"host"`
Port uint16 `yaml:"port"` Port uint16 `yaml:"port"`
AssetsPath string `yaml:"assets-path"` AssetsPath string `yaml:"assets-path"`
BaseURL string `yaml:"base-url"` StartedAt time.Time `yaml:"-"`
AssetsHash string `yaml:"-"`
StartedAt time.Time `yaml:"-"` // used in custom css file
} }
type Column struct { type Column struct {
@@ -59,13 +55,11 @@ type templateData struct {
} }
type Page struct { type Page struct {
Title string `yaml:"name"` Title string `yaml:"name"`
Slug string `yaml:"slug"` Slug string `yaml:"slug"`
Width string `yaml:"width"` ShowMobileHeader bool `yaml:"show-mobile-header"`
ShowMobileHeader bool `yaml:"show-mobile-header"` Columns []Column `yaml:"columns"`
HideDesktopNavigation bool `yaml:"hide-desktop-navigation"` mu sync.Mutex
Columns []Column `yaml:"columns"`
mu sync.Mutex
} }
func (p *Page) UpdateOutdatedWidgets() { func (p *Page) UpdateOutdatedWidgets() {
@@ -111,34 +105,16 @@ func NewApplication(config *Config) (*Application, error) {
Version: buildVersion, Version: buildVersion,
Config: *config, Config: *config,
slugToPage: make(map[string]*Page), slugToPage: make(map[string]*Page),
widgetByID: make(map[uint64]widget.Widget),
} }
app.slugToPage[""] = &config.Pages[0] app.slugToPage[""] = &config.Pages[0]
for p := range config.Pages { for i := range config.Pages {
if config.Pages[p].Slug == "" { if config.Pages[i].Slug == "" {
config.Pages[p].Slug = titleToSlug(config.Pages[p].Title) config.Pages[i].Slug = titleToSlug(config.Pages[i].Title)
} }
app.slugToPage[config.Pages[p].Slug] = &config.Pages[p] app.slugToPage[config.Pages[i].Slug] = &config.Pages[i]
for c := range config.Pages[p].Columns {
for w := range config.Pages[p].Columns[c].Widgets {
widget := config.Pages[p].Columns[c].Widgets[w]
app.widgetByID[widget.GetID()] = widget
}
}
}
config = &app.Config
config.Server.BaseURL = strings.TrimRight(config.Server.BaseURL, "/")
if config.Server.BaseURL != "" &&
config.Theme.CustomCSSFile != "" &&
strings.HasPrefix(config.Theme.CustomCSSFile, "/assets/") {
config.Theme.CustomCSSFile = config.Server.BaseURL + config.Theme.CustomCSSFile
} }
return app, nil return app, nil
@@ -213,47 +189,15 @@ func FileServerWithCache(fs http.FileSystem, cacheDuration time.Duration) http.H
}) })
} }
func (a *Application) HandleWidgetRequest(w http.ResponseWriter, r *http.Request) {
widgetValue := r.PathValue("widget")
widgetID, err := strconv.ParseUint(widgetValue, 10, 64)
if err != nil {
a.HandleNotFound(w, r)
return
}
widget, exists := a.widgetByID[widgetID]
if !exists {
a.HandleNotFound(w, r)
return
}
widget.HandleRequest(w, r)
}
func (a *Application) AssetPath(asset string) string {
return a.Config.Server.BaseURL + "/static/" + a.Config.Server.AssetsHash + "/" + asset
}
func (a *Application) Serve() error { func (a *Application) Serve() error {
a.Config.Server.AssetsHash = assets.PublicFSHash
// TODO: add gzip support, static files must have their gzipped contents cached // TODO: add gzip support, static files must have their gzipped contents cached
// TODO: add HTTPS support // TODO: add HTTPS support
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", a.HandlePageRequest) mux.HandleFunc("GET /{$}", a.HandlePageRequest)
mux.HandleFunc("GET /{page}", a.HandlePageRequest) mux.HandleFunc("GET /{page}", a.HandlePageRequest)
mux.HandleFunc("GET /api/pages/{page}/content/{$}", a.HandlePageContentRequest) mux.HandleFunc("GET /api/pages/{page}/content/{$}", a.HandlePageContentRequest)
mux.HandleFunc("/api/widgets/{widget}/{path...}", a.HandleWidgetRequest) mux.Handle("GET /static/{path...}", http.StripPrefix("/static/", FileServerWithCache(http.FS(assets.PublicFS), 2*time.Hour)))
mux.Handle(
fmt.Sprintf("GET /static/%s/{path...}", a.Config.Server.AssetsHash),
http.StripPrefix("/static/"+a.Config.Server.AssetsHash, FileServerWithCache(http.FS(assets.PublicFS), 8*time.Hour)),
)
if a.Config.Server.AssetsPath != "" { if a.Config.Server.AssetsPath != "" {
absAssetsPath, err := filepath.Abs(a.Config.Server.AssetsPath) absAssetsPath, err := filepath.Abs(a.Config.Server.AssetsPath)
@@ -273,7 +217,7 @@ func (a *Application) Serve() error {
} }
a.Config.Server.StartedAt = time.Now() a.Config.Server.StartedAt = time.Now()
slog.Info("Starting server", "host", a.Config.Server.Host, "port", a.Config.Server.Port, "base-url", a.Config.Server.BaseURL)
slog.Info("Starting server", "host", a.Config.Server.Host, "port", a.Config.Server.Port)
return server.ListenAndServe() return server.ListenAndServe()
} }
-70
View File
@@ -1,70 +0,0 @@
package widget
import (
"context"
"errors"
"html/template"
"sync"
"time"
"github.com/glanceapp/glance/internal/assets"
)
type Group struct {
widgetBase `yaml:",inline"`
Widgets Widgets `yaml:"widgets"`
}
func (widget *Group) Initialize() error {
widget.withError(nil)
widget.HideHeader = true
for i := range widget.Widgets {
widget.Widgets[i].SetHideHeader(true)
if widget.Widgets[i].GetType() == "group" {
return errors.New("nested groups are not allowed")
}
if err := widget.Widgets[i].Initialize(); err != nil {
return err
}
}
return nil
}
func (widget *Group) Update(ctx context.Context) {
var wg sync.WaitGroup
now := time.Now()
for w := range widget.Widgets {
widget := widget.Widgets[w]
if !widget.RequiresUpdate(&now) {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
widget.Update(ctx)
}()
}
wg.Wait()
}
func (widget *Group) RequiresUpdate(now *time.Time) bool {
for i := range widget.Widgets {
if widget.Widgets[i].RequiresUpdate(now) {
return true
}
}
return false
}
func (widget *Group) Render() template.HTML {
return widget.render(widget, assets.GroupTemplate)
}
+1 -4
View File
@@ -21,10 +21,7 @@ type HackerNews struct {
} }
func (widget *HackerNews) Initialize() error { func (widget *HackerNews) Initialize() error {
widget. widget.withTitle("Hacker News").withCacheDuration(30 * time.Minute)
withTitle("Hacker News").
withTitleURL("https://news.ycombinator.com/").
withCacheDuration(30 * time.Minute)
if widget.Limit <= 0 { if widget.Limit <= 0 {
widget.Limit = 15 widget.Limit = 15
+2 -10
View File
@@ -12,8 +12,6 @@ import (
type Lobsters struct { type Lobsters struct {
widgetBase `yaml:",inline"` widgetBase `yaml:",inline"`
Posts feed.ForumPosts `yaml:"-"` Posts feed.ForumPosts `yaml:"-"`
InstanceURL string `yaml:"instance-url"`
CustomURL string `yaml:"custom-url"`
Limit int `yaml:"limit"` Limit int `yaml:"limit"`
CollapseAfter int `yaml:"collapse-after"` CollapseAfter int `yaml:"collapse-after"`
SortBy string `yaml:"sort-by"` SortBy string `yaml:"sort-by"`
@@ -22,13 +20,7 @@ type Lobsters struct {
} }
func (widget *Lobsters) Initialize() error { func (widget *Lobsters) Initialize() error {
widget.withTitle("Lobsters").withCacheDuration(time.Hour) widget.withTitle("Lobsters").withCacheDuration(30 * time.Minute)
if widget.InstanceURL == "" {
widget.withTitleURL("https://lobste.rs")
} else {
widget.withTitleURL(widget.InstanceURL)
}
if widget.SortBy == "" || (widget.SortBy != "hot" && widget.SortBy != "new") { if widget.SortBy == "" || (widget.SortBy != "hot" && widget.SortBy != "new") {
widget.SortBy = "hot" widget.SortBy = "hot"
@@ -46,7 +38,7 @@ func (widget *Lobsters) Initialize() error {
} }
func (widget *Lobsters) Update(ctx context.Context) { func (widget *Lobsters) Update(ctx context.Context) {
posts, err := feed.FetchLobstersPosts(widget.CustomURL, widget.InstanceURL, widget.SortBy, widget.Tags) posts, err := feed.FetchLobstersPosts(widget.SortBy, widget.Tags)
if !widget.canContinueUpdateAfterHandlingErr(err) { if !widget.canContinueUpdateAfterHandlingErr(err) {
return return
+1 -4
View File
@@ -54,10 +54,7 @@ func (widget *Reddit) Initialize() error {
} }
} }
widget. widget.withTitle("/r/" + widget.Subreddit).withCacheDuration(30 * time.Minute)
withTitle("/r/" + widget.Subreddit).
withTitleURL("https://www.reddit.com/r/" + widget.Subreddit + "/").
withCacheDuration(30 * time.Minute)
return nil return nil
} }
+3 -2
View File
@@ -39,9 +39,10 @@ func (widget *RSS) Initialize() error {
widget.CardHeight = 0 widget.CardHeight = 0
} }
if widget.Style == "detailed-list" { if widget.Style != "detailed-list" {
for i := range widget.FeedRequests { for i := range widget.FeedRequests {
widget.FeedRequests[i].IsDetailed = true widget.FeedRequests[i].HideCategories = true
widget.FeedRequests[i].HideDescription = true
} }
} }
-2
View File
@@ -19,8 +19,6 @@ type Search struct {
cachedHTML template.HTML `yaml:"-"` cachedHTML template.HTML `yaml:"-"`
SearchEngine string `yaml:"search-engine"` SearchEngine string `yaml:"search-engine"`
Bangs []SearchBang `yaml:"bangs"` Bangs []SearchBang `yaml:"bangs"`
NewTab bool `yaml:"new-tab"`
Autofocus bool `yaml:"autofocus"`
} }
func convertSearchUrl(url string) string { func convertSearchUrl(url string) string {
+1 -4
View File
@@ -18,10 +18,7 @@ type TwitchChannels struct {
} }
func (widget *TwitchChannels) Initialize() error { func (widget *TwitchChannels) Initialize() error {
widget. widget.withTitle("Twitch Channels").withCacheDuration(time.Minute * 10)
withTitle("Twitch Channels").
withTitleURL("https://www.twitch.tv/directory/following").
withCacheDuration(time.Minute * 10)
if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {
widget.CollapseAfter = 5 widget.CollapseAfter = 5
+1 -4
View File
@@ -18,10 +18,7 @@ type TwitchGames struct {
} }
func (widget *TwitchGames) Initialize() error { func (widget *TwitchGames) Initialize() error {
widget. widget.withTitle("Top games on Twitch").withCacheDuration(time.Minute * 10)
withTitle("Top games on Twitch").
withTitleURL("https://www.twitch.tv/directory?sort=VIEWER_COUNT").
withCacheDuration(time.Minute * 10)
if widget.Limit <= 0 { if widget.Limit <= 0 {
widget.Limit = 10 widget.Limit = 10
+1 -2
View File
@@ -17,7 +17,6 @@ type Videos struct {
CollapseAfterRows int `yaml:"collapse-after-rows"` CollapseAfterRows int `yaml:"collapse-after-rows"`
Channels []string `yaml:"channels"` Channels []string `yaml:"channels"`
Limit int `yaml:"limit"` Limit int `yaml:"limit"`
IncludeShorts bool `yaml:"include-shorts"`
} }
func (widget *Videos) Initialize() error { func (widget *Videos) Initialize() error {
@@ -35,7 +34,7 @@ func (widget *Videos) Initialize() error {
} }
func (widget *Videos) Update(ctx context.Context) { func (widget *Videos) Update(ctx context.Context) {
videos, err := feed.FetchYoutubeChannelUploads(widget.Channels, widget.VideoUrlTemplate, widget.IncludeShorts) videos, err := feed.FetchYoutubeChannelUploads(widget.Channels, widget.VideoUrlTemplate)
if !widget.canContinueUpdateAfterHandlingErr(err) { if !widget.canContinueUpdateAfterHandlingErr(err) {
return return
+24 -64
View File
@@ -8,8 +8,6 @@ import (
"html/template" "html/template"
"log/slog" "log/slog"
"math" "math"
"net/http"
"sync/atomic"
"time" "time"
"github.com/glanceapp/glance/internal/feed" "github.com/glanceapp/glance/internal/feed"
@@ -17,61 +15,51 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
var uniqueID atomic.Uint64
func New(widgetType string) (Widget, error) { func New(widgetType string) (Widget, error) {
var widget Widget
switch widgetType { switch widgetType {
case "calendar": case "calendar":
widget = &Calendar{} return &Calendar{}, nil
case "clock": case "clock":
widget = &Clock{} return &Clock{}, nil
case "weather": case "weather":
widget = &Weather{} return &Weather{}, nil
case "bookmarks": case "bookmarks":
widget = &Bookmarks{} return &Bookmarks{}, nil
case "iframe": case "iframe":
widget = &IFrame{} return &IFrame{}, nil
case "html": case "html":
widget = &HTML{} return &HTML{}, nil
case "hacker-news": case "hacker-news":
widget = &HackerNews{} return &HackerNews{}, nil
case "releases": case "releases":
widget = &Releases{} return &Releases{}, nil
case "videos": case "videos":
widget = &Videos{} return &Videos{}, nil
case "markets", "stocks": case "markets", "stocks":
widget = &Markets{} return &Markets{}, nil
case "reddit": case "reddit":
widget = &Reddit{} return &Reddit{}, nil
case "rss": case "rss":
widget = &RSS{} return &RSS{}, nil
case "monitor": case "monitor":
widget = &Monitor{} return &Monitor{}, nil
case "twitch-top-games": case "twitch-top-games":
widget = &TwitchGames{} return &TwitchGames{}, nil
case "twitch-channels": case "twitch-channels":
widget = &TwitchChannels{} return &TwitchChannels{}, nil
case "lobsters": case "lobsters":
widget = &Lobsters{} return &Lobsters{}, nil
case "change-detection": case "change-detection":
widget = &ChangeDetection{} return &ChangeDetection{}, nil
case "repository": case "repository":
widget = &Repository{} return &Repository{}, nil
case "search": case "search":
widget = &Search{} return &Search{}, nil
case "extension": case "extension":
widget = &Extension{} return &Extension{}, nil
case "group":
widget = &Group{}
default: default:
return nil, fmt.Errorf("unknown widget type: %s", widgetType) return nil, fmt.Errorf("unknown widget type: %s", widgetType)
} }
widget.SetID(uniqueID.Add(1))
return widget, nil
} }
type Widgets []Widget type Widgets []Widget
@@ -102,6 +90,10 @@ func (w *Widgets) UnmarshalYAML(node *yaml.Node) error {
return err return err
} }
if err = widget.Initialize(); err != nil {
return err
}
*w = append(*w, widget) *w = append(*w, widget)
} }
@@ -114,10 +106,6 @@ type Widget interface {
Update(context.Context) Update(context.Context)
Render() template.HTML Render() template.HTML
GetType() string GetType() string
GetID() uint64
SetID(uint64)
HandleRequest(w http.ResponseWriter, r *http.Request)
SetHideHeader(bool)
} }
type cacheType int type cacheType int
@@ -129,11 +117,8 @@ const (
) )
type widgetBase struct { type widgetBase struct {
ID uint64 `yaml:"-"`
Type string `yaml:"type"` Type string `yaml:"type"`
Title string `yaml:"title"` Title string `yaml:"title"`
TitleURL string `yaml:"title-url"`
CSSClass string `yaml:"css-class"`
CustomCacheDuration DurationField `yaml:"cache"` CustomCacheDuration DurationField `yaml:"cache"`
ContentAvailable bool `yaml:"-"` ContentAvailable bool `yaml:"-"`
Error error `yaml:"-"` Error error `yaml:"-"`
@@ -143,7 +128,6 @@ type widgetBase struct {
cacheType cacheType `yaml:"-"` cacheType cacheType `yaml:"-"`
nextUpdate time.Time `yaml:"-"` nextUpdate time.Time `yaml:"-"`
updateRetriedTimes int `yaml:"-"` updateRetriedTimes int `yaml:"-"`
HideHeader bool `yaml:"-"`
} }
func (w *widgetBase) RequiresUpdate(now *time.Time) bool { func (w *widgetBase) RequiresUpdate(now *time.Time) bool {
@@ -162,22 +146,6 @@ func (w *widgetBase) Update(ctx context.Context) {
} }
func (w *widgetBase) GetID() uint64 {
return w.ID
}
func (w *widgetBase) SetID(id uint64) {
w.ID = id
}
func (w *widgetBase) SetHideHeader(value bool) {
w.HideHeader = value
}
func (widget *widgetBase) HandleRequest(w http.ResponseWriter, r *http.Request) {
http.Error(w, "not implemented", http.StatusNotImplemented)
}
func (w *widgetBase) GetType() string { func (w *widgetBase) GetType() string {
return w.Type return w.Type
} }
@@ -217,14 +185,6 @@ func (w *widgetBase) withTitle(title string) *widgetBase {
return w return w
} }
func (w *widgetBase) withTitleURL(titleURL string) *widgetBase {
if w.TitleURL == "" {
w.TitleURL = titleURL
}
return w
}
func (w *widgetBase) withCacheDuration(duration time.Duration) *widgetBase { func (w *widgetBase) withCacheDuration(duration time.Duration) *widgetBase {
w.cacheType = cacheTypeDuration w.cacheType = cacheTypeDuration