Compare commits
7
Commits
5001cae163
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e31d787769 | ||
|
|
51b52abb15 | ||
|
|
af73a386ed | ||
|
|
b6e5d81dc0 | ||
|
|
cba6eddc56 | ||
|
|
56ed40e8b0 | ||
|
|
c3225a7b91 |
@@ -19,5 +19,10 @@ OIDC_CLIENT_ID=
|
||||
OIDC_CLIENT_SECRET=
|
||||
OIDC_PROVIDER_NAME=SSO
|
||||
|
||||
# Set to "true" to show on every link whether its address answers. The server then
|
||||
# calls the addresses that users save as links, once a minute. Leave it off when
|
||||
# people you do not trust can sign up: they could probe your network with it.
|
||||
STATUS_CHECKS=false
|
||||
|
||||
# SearXNG instance (must be reachable from the browser and from this server)
|
||||
SEARXNG_URL=
|
||||
|
||||
@@ -101,14 +101,30 @@ scripts/sync-collabry.sh copies them from upstream at a pinned commit
|
||||
wallpaper is shown, and where "Back to dashboard" goes.
|
||||
- [x] 16. Cards are dragged by their title bar: `card.position` (migration `0008_card_position`),
|
||||
`saveLayout` (was `moveLinks`) stores the order of the cards and of their links.
|
||||
- [x] 17. Password change in Settings → Account (Better Auth `changePassword`, other sessions are
|
||||
revoked). Hidden for accounts without a password (SSO only).
|
||||
- [x] 18. The search bar opens links by name: `matchLinks` in `src/lib/search.ts`. A link whose name
|
||||
or a word of it starts with the text is preselected, Enter opens it.
|
||||
- [x] 19. Light icons: a link without an icon of its own uses the library's `-light` version when
|
||||
there is one. The server keeps the library's names for a day (`src/lib/icon-library.ts`) and
|
||||
sends `lightIcon` with each link.
|
||||
- [x] 20. Status dots: `STATUS_CHECKS=true` turns them on (`src/lib/status.ts`, `getStatuses`).
|
||||
Off by default, because the server then requests addresses that users chose.
|
||||
- [x] 21. Export and import: `exportData` / `importData`, the file format and the bookmarks parser
|
||||
in `src/lib/transfer.ts`. An import only adds dashboards.
|
||||
- [x] 22. Cards move to another dashboard in the card dialog, dashboards are ordered with arrows
|
||||
in Settings (`dashboard.position`, migration `0009_dashboard_position`), uploaded icons are
|
||||
offered again in the link dialog (`getIcons`).
|
||||
|
||||
## Not doing (not asked)
|
||||
|
||||
- Unraid version/uptime chip and the Sonarr/Plex notification pills from the screenshot
|
||||
- Inline SearXNG result rendering (search opens the engine's result page)
|
||||
- Free placement of cards with gaps in the grid, per-user SearXNG URL (SSRF risk — it is a server env)
|
||||
- Per dashboard clock or search engine (they stay per user), moving a card to another dashboard,
|
||||
reordering dashboards, remembering the last opened dashboard (the default opens)
|
||||
- A list of the icons a user uploaded, to use one again for another link
|
||||
- Per dashboard clock or search engine (they stay per user), remembering the last opened
|
||||
dashboard (it would work against the default dashboard, which opens)
|
||||
- Links of other dashboards in the search bar, a keyword per link, a status history or alerts
|
||||
- Info pills (Sonarr, SABnzbd, server status) and a Home Assistant card: each needs its own
|
||||
integration and an API key on the server
|
||||
- Email verification / password reset mail (needs an SMTP setup)
|
||||
- In CI: version tags and releases, a Helm chart, an image vulnerability scan (typst-workspace has all three)
|
||||
|
||||
@@ -49,17 +49,19 @@ Build it yourself: `docker build -t dahoam .`
|
||||
| `DISABLE_SIGNUP` | `true` closes email/password registration. Set it after you made your account. |
|
||||
| `OIDC_DISCOVERY_URL`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | Turns on the SSO button. Redirect URI: `<BETTER_AUTH_URL>/api/auth/callback/sso` |
|
||||
| `OIDC_PROVIDER_NAME` | Text on the SSO button ("Continue with …") |
|
||||
| `STATUS_CHECKS` | `true` shows on every link whether its address answers. Off by default, see Notes. |
|
||||
| `SEARXNG_URL` | Your SearXNG instance. Makes SearXNG selectable in Settings. |
|
||||
|
||||
## Use
|
||||
|
||||
- **Dashboards** are separate sets of cards, for example Home and Work. Settings → Dashboards
|
||||
adds, renames and deletes them and sets the default, the one that opens when you sign in.
|
||||
adds, renames, orders and deletes them and sets the default, the one that opens when you
|
||||
sign in.
|
||||
With more than one, switch at the top of the page or with `/switch to work`. The address
|
||||
of a dashboard (`/?d=…`) can be bookmarked. Every dashboard has its own wallpaper, clock
|
||||
and search are the same on all.
|
||||
- **Cards** group your links (Apps, Media, Bookmarks, ...). "New card" under the cards adds
|
||||
one. Click a card's name to rename or delete it.
|
||||
one. Click a card's name to rename or delete it, or to move it to another dashboard.
|
||||
- **Links**: **+** at the top or on a card adds a link. Hover a link and click the pencil to
|
||||
edit or delete it.
|
||||
- **Move links** by dragging, inside a card or to another card. Touch: press and hold first.
|
||||
@@ -68,14 +70,27 @@ Build it yourself: `docker build -t dahoam .`
|
||||
first. Keyboard: Space on the grip next to the plus, arrow keys, Space.
|
||||
- **Icons**: leave the field empty and the icon is looked up by name in
|
||||
[dashboard-icons](https://github.com/homarr-labs/dashboard-icons), then from the
|
||||
site's `/favicon.ico`. Or type in the field to search that library and click an icon,
|
||||
site's `/favicon.ico`. When the library has a light version of the icon (`github-light`),
|
||||
that one is used, because the cards are dark. Or type in the field to search that library and click an icon,
|
||||
paste an image URL, or upload your own image (PNG, JPEG, WebP, AVIF or SVG, up to 1 MB).
|
||||
- **Search**: `/` focuses the bar. `!w cats` uses DuckDuckGo bangs. `/plex` jumps to
|
||||
a link, `/settings`, `/add link`, `/add card`, `/add dashboard` and `/sign out` run commands.
|
||||
The images that you uploaded before are offered again under "Your images".
|
||||
- **Status** (with `STATUS_CHECKS=true`): a green dot on a link means that its address
|
||||
answers, a red ring that it does not. Checked once a minute.
|
||||
- **Search**: `/` focuses the bar. `!w cats` uses DuckDuckGo bangs. `/settings`, `/add link`,
|
||||
`/add card`, `/add dashboard` and `/sign out` run commands.
|
||||
- **Open a link from the search bar**: type the start of its name (`jel` for Jellyfin). The
|
||||
link is highlighted and Enter opens it. To search the web for the same word, press the up
|
||||
arrow first, so that no row is highlighted. `/jel` shows only your links and commands.
|
||||
- **Wallpaper**: Settings (or the pencil at the bottom right) takes an image URL or an
|
||||
upload (JPEG, PNG, WebP, AVIF, up to 10 MB). A slider sets how much it is darkened.
|
||||
Each dashboard has its own: the pencil opens the one of the dashboard you are on, and
|
||||
Settings → Wallpaper has a switch for the others.
|
||||
- **Export and import**: Settings → Export and import downloads all dashboards with their
|
||||
cards and links as one JSON file, and loads such a file again. It also takes the bookmarks
|
||||
file that a browser exports (HTML) and makes a dashboard "Bookmarks" of it, with a card per
|
||||
folder. An import adds dashboards and replaces nothing. Uploaded wallpapers and icons are
|
||||
not part of an export.
|
||||
- **Password**: Settings → Account changes it. That signs you out on your other devices.
|
||||
- **Clock**: Settings has five fonts and three styles. Glass shows the wallpaper blurred
|
||||
through the digits, Tinted takes its color from the wallpaper.
|
||||
|
||||
@@ -83,10 +98,15 @@ Build it yourself: `docker build -t dahoam .`
|
||||
|
||||
- Suggestions come from DuckDuckGo, or from SearXNG (`/autocompleter`) when it is the
|
||||
selected engine. The server fetches them, the browser never calls those hosts directly.
|
||||
- Status checks: the server requests each link's address (a GET, redirects are not
|
||||
followed, the answer is thrown away) and tells the browser only up or down. Up is any
|
||||
answer below 500, and also a certificate that the server does not trust. Because users
|
||||
choose the addresses, a user can find out which hosts and ports the server can reach.
|
||||
Turn it on for people you trust, together with `DISABLE_SIGNUP=true`.
|
||||
- SSO does not take over an existing password account with the same email
|
||||
(Better Auth blocks it, because password emails are not verified). Use one or the other per email.
|
||||
- Icon lookups send the link name to the jsDelivr CDN. The link dialog also loads the
|
||||
library's list of icons from there.
|
||||
library's list of icons from there, and so does the server, once a day.
|
||||
- Uploaded icons are stored in Postgres and only their owner can load them. One that no
|
||||
link uses any more is deleted with that user's next upload.
|
||||
- UI components come from [collabry-components](https://git.nhaiden.io/niklas/collabry-components),
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "dashboard" ADD COLUMN "position" integer DEFAULT 0 NOT NULL;
|
||||
@@ -0,0 +1,916 @@
|
||||
{
|
||||
"id": "c4525c58-c6aa-4d91-a377-92f7483f75fd",
|
||||
"prevId": "eddd02da-41ed-40a6-b0b0-e5976ea2c371",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.account": {
|
||||
"name": "account",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"account_id": {
|
||||
"name": "account_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"provider_id": {
|
||||
"name": "provider_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"access_token": {
|
||||
"name": "access_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"refresh_token": {
|
||||
"name": "refresh_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"id_token": {
|
||||
"name": "id_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"access_token_expires_at": {
|
||||
"name": "access_token_expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"refresh_token_expires_at": {
|
||||
"name": "refresh_token_expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"scope": {
|
||||
"name": "scope",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"password": {
|
||||
"name": "password",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"account_user_id_idx": {
|
||||
"name": "account_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"account_user_id_user_id_fk": {
|
||||
"name": "account_user_id_user_id_fk",
|
||||
"tableFrom": "account",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.card": {
|
||||
"name": "card",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"dashboard_id": {
|
||||
"name": "dashboard_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"position": {
|
||||
"name": "position",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"card_user_id_idx": {
|
||||
"name": "card_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"card_dashboard_id_idx": {
|
||||
"name": "card_dashboard_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "dashboard_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"card_user_id_user_id_fk": {
|
||||
"name": "card_user_id_user_id_fk",
|
||||
"tableFrom": "card",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"card_dashboard_id_dashboard_id_fk": {
|
||||
"name": "card_dashboard_id_dashboard_id_fk",
|
||||
"tableFrom": "card",
|
||||
"tableTo": "dashboard",
|
||||
"columnsFrom": [
|
||||
"dashboard_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.dashboard": {
|
||||
"name": "dashboard",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"position": {
|
||||
"name": "position",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"wallpaper_url": {
|
||||
"name": "wallpaper_url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"wallpaper_dim": {
|
||||
"name": "wallpaper_dim",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 40
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"dashboard_user_id_idx": {
|
||||
"name": "dashboard_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"dashboard_user_id_user_id_fk": {
|
||||
"name": "dashboard_user_id_user_id_fk",
|
||||
"tableFrom": "dashboard",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.icon": {
|
||||
"name": "icon",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"mime": {
|
||||
"name": "mime",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"data": {
|
||||
"name": "data",
|
||||
"type": "bytea",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"icon_user_id_idx": {
|
||||
"name": "icon_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"icon_user_id_user_id_fk": {
|
||||
"name": "icon_user_id_user_id_fk",
|
||||
"tableFrom": "icon",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.link": {
|
||||
"name": "link",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"card_id": {
|
||||
"name": "card_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"position": {
|
||||
"name": "position",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": 0
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"url": {
|
||||
"name": "url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"icon": {
|
||||
"name": "icon",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"link_user_id_idx": {
|
||||
"name": "link_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"link_card_id_idx": {
|
||||
"name": "link_card_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "card_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"link_user_id_user_id_fk": {
|
||||
"name": "link_user_id_user_id_fk",
|
||||
"tableFrom": "link",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"link_card_id_card_id_fk": {
|
||||
"name": "link_card_id_card_id_fk",
|
||||
"tableFrom": "link",
|
||||
"tableTo": "card",
|
||||
"columnsFrom": [
|
||||
"card_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.session": {
|
||||
"name": "session",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"token": {
|
||||
"name": "token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"ip_address": {
|
||||
"name": "ip_address",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"user_agent": {
|
||||
"name": "user_agent",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"session_user_id_idx": {
|
||||
"name": "session_user_id_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"session_user_id_user_id_fk": {
|
||||
"name": "session_user_id_user_id_fk",
|
||||
"tableFrom": "session",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"session_token_unique": {
|
||||
"name": "session_token_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"token"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.settings": {
|
||||
"name": "settings",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'Dahoam'"
|
||||
},
|
||||
"default_dashboard_id": {
|
||||
"name": "default_dashboard_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"search_engine": {
|
||||
"name": "search_engine",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'duckduckgo'"
|
||||
},
|
||||
"clock_font": {
|
||||
"name": "clock_font",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'serif'"
|
||||
},
|
||||
"clock_style": {
|
||||
"name": "clock_style",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'solid'"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"settings_user_id_user_id_fk": {
|
||||
"name": "settings_user_id_user_id_fk",
|
||||
"tableFrom": "settings",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"settings_default_dashboard_id_dashboard_id_fk": {
|
||||
"name": "settings_default_dashboard_id_dashboard_id_fk",
|
||||
"tableFrom": "settings",
|
||||
"tableTo": "dashboard",
|
||||
"columnsFrom": [
|
||||
"default_dashboard_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.user": {
|
||||
"name": "user",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"email_verified": {
|
||||
"name": "email_verified",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
},
|
||||
"image": {
|
||||
"name": "image",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {
|
||||
"user_email_unique": {
|
||||
"name": "user_email_unique",
|
||||
"nullsNotDistinct": false,
|
||||
"columns": [
|
||||
"email"
|
||||
]
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.verification": {
|
||||
"name": "verification",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"identifier": {
|
||||
"name": "identifier",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"verification_identifier_idx": {
|
||||
"name": "verification_identifier_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "identifier",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.wallpaper": {
|
||||
"name": "wallpaper",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"dashboard_id": {
|
||||
"name": "dashboard_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"mime": {
|
||||
"name": "mime",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"data": {
|
||||
"name": "data",
|
||||
"type": "bytea",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"wallpaper_dashboard_id_dashboard_id_fk": {
|
||||
"name": "wallpaper_dashboard_id_dashboard_id_fk",
|
||||
"tableFrom": "wallpaper",
|
||||
"tableTo": "dashboard",
|
||||
"columnsFrom": [
|
||||
"dashboard_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"wallpaper_user_id_user_id_fk": {
|
||||
"name": "wallpaper_user_id_user_id_fk",
|
||||
"tableFrom": "wallpaper",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"roles": {},
|
||||
"policies": {},
|
||||
"views": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,13 @@
|
||||
"when": 1795106775546,
|
||||
"tag": "0008_card_position",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1795285309906,
|
||||
"tag": "0009_dashboard_position",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
Input,
|
||||
Select,
|
||||
SelectOption,
|
||||
} from "@/vendor/collabry/components/Field/Field"
|
||||
import {
|
||||
Dialog,
|
||||
@@ -21,17 +23,22 @@ import {
|
||||
|
||||
export type CardTarget = { id: string; name: string; links: unknown[] } | "new"
|
||||
|
||||
type Dashboards = { id: string; name: string }[]
|
||||
|
||||
/**
|
||||
* `card` is the card to edit, "new" to add one, or null when closed.
|
||||
* A new card goes on the dashboard `dashboardId`.
|
||||
* `dashboardId` is the open dashboard: where a new card goes, and where a card is
|
||||
* until another of `dashboards` is chosen for it.
|
||||
*/
|
||||
export function CardDialog({
|
||||
card,
|
||||
dashboardId,
|
||||
dashboards,
|
||||
onClose,
|
||||
}: {
|
||||
card: CardTarget | null
|
||||
dashboardId: string
|
||||
dashboards: Dashboards
|
||||
onClose: () => void
|
||||
}) {
|
||||
return (
|
||||
@@ -41,6 +48,7 @@ export function CardDialog({
|
||||
<CardForm
|
||||
card={card === "new" ? null : card}
|
||||
dashboardId={dashboardId}
|
||||
dashboards={dashboards}
|
||||
onClose={onClose}
|
||||
/>
|
||||
)}
|
||||
@@ -52,10 +60,12 @@ export function CardDialog({
|
||||
function CardForm({
|
||||
card,
|
||||
dashboardId,
|
||||
dashboards,
|
||||
onClose,
|
||||
}: {
|
||||
card: Exclude<CardTarget, "new"> | null
|
||||
dashboardId: string
|
||||
dashboards: Dashboards
|
||||
onClose: () => void
|
||||
}) {
|
||||
const router = useRouter()
|
||||
@@ -82,9 +92,16 @@ function CardForm({
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
const name = String(new FormData(e.currentTarget).get("name"))
|
||||
const form = new FormData(e.currentTarget)
|
||||
void submit(() =>
|
||||
saveCard({ data: { id: card?.id, name, dashboardId } })
|
||||
saveCard({
|
||||
data: {
|
||||
id: card?.id,
|
||||
name: String(form.get("name")),
|
||||
// without the field there is only one dashboard
|
||||
dashboardId: String(form.get("dashboardId") ?? dashboardId),
|
||||
},
|
||||
})
|
||||
)
|
||||
}}
|
||||
>
|
||||
@@ -105,6 +122,18 @@ function CardForm({
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
{dashboards.length > 1 && (
|
||||
<Field>
|
||||
<FieldLabel>Dashboard</FieldLabel>
|
||||
<Select name="dashboardId" defaultValue={dashboardId}>
|
||||
{dashboards.map((d) => (
|
||||
<SelectOption key={d.id} value={d.id}>
|
||||
{d.name}
|
||||
</SelectOption>
|
||||
))}
|
||||
</Select>
|
||||
</Field>
|
||||
)}
|
||||
{error && <FieldError role="alert">{error}</FieldError>}
|
||||
</DialogBody>
|
||||
<DialogFooter className="justify-between">
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useRouter } from "@tanstack/react-router"
|
||||
import { Trash2, Upload, X } from "lucide-react"
|
||||
import { GlassDialogContent } from "@/components/glass"
|
||||
import type { HomeLink } from "@/components/link-tile"
|
||||
import { deleteLink, saveLink } from "@/lib/dashboard.functions"
|
||||
import { deleteLink, getIcons, saveLink } from "@/lib/dashboard.functions"
|
||||
import {
|
||||
LIBRARY_INDEX,
|
||||
UPLOADED_ICON,
|
||||
@@ -31,6 +31,51 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/vendor/collabry/components/ui/dialog"
|
||||
|
||||
/** A grid of icons to click. Two and a half rows, so it shows that there is more to scroll to. */
|
||||
function IconChoices({
|
||||
label,
|
||||
icons,
|
||||
chosen,
|
||||
named,
|
||||
onChoose,
|
||||
}: {
|
||||
label: string
|
||||
icons: string[]
|
||||
chosen: string
|
||||
/** names in the icon library. Without it: image addresses. */
|
||||
named?: boolean
|
||||
onChoose: (icon: string) => void
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={label}
|
||||
className="grid max-h-29 grid-cols-7 gap-1 overflow-y-auto rounded-xl bg-white/5 p-1"
|
||||
>
|
||||
{icons.map((icon, i) => (
|
||||
<button
|
||||
key={icon}
|
||||
type="button"
|
||||
title={named ? icon : undefined}
|
||||
// an upload has no name: "Your images 2"
|
||||
aria-label={named ? icon : `${label} ${i + 1}`}
|
||||
aria-pressed={icon === chosen}
|
||||
onClick={() => onChoose(icon)}
|
||||
className="grid h-11 place-items-center rounded-lg outline-none hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-white/60 aria-pressed:bg-white/15"
|
||||
>
|
||||
<img
|
||||
src={named ? libraryIcon(icon) : icon}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
className="size-8 object-contain"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** A link to edit, or only the card that a new link starts in. */
|
||||
export type LinkTarget = HomeLink | { cardId: string }
|
||||
|
||||
@@ -69,6 +114,8 @@ function LinkForm({
|
||||
const [name, setName] = useState(link?.name ?? "")
|
||||
const [icon, setIcon] = useState(link?.icon ?? "")
|
||||
const [library, setLibrary] = useState<string[]>([])
|
||||
// the images that this user uploaded before, to use one again
|
||||
const [uploads, setUploads] = useState<string[]>([])
|
||||
const file = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Without the library's index the field still takes a name or an address.
|
||||
@@ -79,6 +126,9 @@ function LinkForm({
|
||||
setLibrary(index.png.map((f) => f.replace(/\.png$/, "")))
|
||||
)
|
||||
.catch(() => {})
|
||||
getIcons()
|
||||
.then(setUploads)
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
const uploaded = icon.startsWith(UPLOADED_ICON)
|
||||
@@ -94,8 +144,11 @@ function LinkForm({
|
||||
headers: { "Content-Type": image.type },
|
||||
body: image,
|
||||
})
|
||||
if (res.ok) setIcon((await res.json()).icon)
|
||||
else setError(await res.text())
|
||||
if (res.ok) {
|
||||
const added: string = (await res.json()).icon
|
||||
setIcon(added)
|
||||
setUploads((before) => [added, ...before])
|
||||
} else setError(await res.text())
|
||||
} catch {
|
||||
setError("Could not upload. Try again.")
|
||||
}
|
||||
@@ -209,36 +262,26 @@ function LinkForm({
|
||||
</Button>
|
||||
</div>
|
||||
{matches.length > 0 && (
|
||||
// two and a half rows, so it shows that there is more to scroll to
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Icons from the library"
|
||||
className="grid max-h-29 grid-cols-7 gap-1 overflow-y-auto rounded-xl bg-white/5 p-1"
|
||||
>
|
||||
{matches.map((match) => (
|
||||
<button
|
||||
key={match}
|
||||
type="button"
|
||||
title={match}
|
||||
aria-label={match}
|
||||
aria-pressed={match === icon}
|
||||
onClick={() => setIcon(match)}
|
||||
className="grid h-11 place-items-center rounded-lg outline-none hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-white/60 aria-pressed:bg-white/15"
|
||||
>
|
||||
<img
|
||||
src={libraryIcon(match)}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
className="size-8 object-contain"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<IconChoices
|
||||
label="Icons from the library"
|
||||
icons={matches}
|
||||
chosen={icon}
|
||||
named
|
||||
onChoose={setIcon}
|
||||
/>
|
||||
)}
|
||||
{uploads.length > 0 && (
|
||||
<IconChoices
|
||||
label="Your images"
|
||||
icons={uploads}
|
||||
chosen={icon}
|
||||
onChoose={setIcon}
|
||||
/>
|
||||
)}
|
||||
<FieldDescription>
|
||||
Empty: found from the name, then from the site's favicon. Upload a
|
||||
PNG, JPEG, WebP, AVIF or SVG, up to 1 MB.
|
||||
Empty: found from the name (the light version, when the library has
|
||||
one), then from the site's favicon. Upload a PNG, JPEG, WebP, AVIF
|
||||
or SVG, up to 1 MB.
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
<Field>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { createContext, useContext, useEffect, useRef, useState } from "react"
|
||||
import { useDndContext } from "@dnd-kit/core"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
@@ -12,14 +12,19 @@ export type HomeLink = {
|
||||
name: string
|
||||
url: string
|
||||
icon: string | null
|
||||
/** the library's light version of the icon, when the link has no icon of its own */
|
||||
lightIcon: string | null
|
||||
}
|
||||
|
||||
/** Per link id: does its address answer? No entry: not checked (yet). */
|
||||
export const StatusContext = createContext<Partial<Record<string, boolean>>>({})
|
||||
|
||||
type IconProps = { link: HomeLink; className?: string }
|
||||
|
||||
/** Starts the fallback chain again when the link changes. */
|
||||
export function LinkIcon(props: IconProps) {
|
||||
const { id, name, url, icon } = props.link
|
||||
return <Icon key={[id, name, url, icon].join("|")} {...props} />
|
||||
const { id, name, url, icon, lightIcon } = props.link
|
||||
return <Icon key={[id, name, url, icon, lightIcon].join("|")} {...props} />
|
||||
}
|
||||
|
||||
function Icon({ link, className }: IconProps) {
|
||||
@@ -96,6 +101,7 @@ export function LinkTile({
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: link.id, disabled: { droppable: cardDragged } })
|
||||
const up = useContext(StatusContext)[link.id]
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
@@ -113,6 +119,19 @@ export function LinkTile({
|
||||
className="block touch-manipulation rounded-2xl transition-colors outline-none select-none [-webkit-touch-callout:none] hover:bg-white/10 focus-visible:bg-white/10 focus-visible:ring-2 focus-visible:ring-white/60"
|
||||
>
|
||||
<TileFace link={link} />
|
||||
{up !== undefined && (
|
||||
// at the lower right corner of the icon. Filled green or a red ring:
|
||||
// the shape differs too, not only the color.
|
||||
<span
|
||||
title={up ? "Reachable" : "Not reachable"}
|
||||
className={cn(
|
||||
"absolute top-[58px] right-[18px] size-3 rounded-full border-2",
|
||||
up ? "border-black/70 bg-success" : "border-danger bg-black/80"
|
||||
)}
|
||||
>
|
||||
{!up && <span className="sr-only">, not reachable</span>}
|
||||
</span>
|
||||
)}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -7,7 +7,12 @@ import { cn } from "@/vendor/collabry/lib/cn"
|
||||
import { LinkIcon } from "@/components/link-tile"
|
||||
import type { HomeLink } from "@/components/link-tile"
|
||||
import { suggest } from "@/lib/dashboard.functions"
|
||||
import { ENGINE_NAMES, effectiveEngine, searchUrl } from "@/lib/search"
|
||||
import {
|
||||
ENGINE_NAMES,
|
||||
effectiveEngine,
|
||||
matchLinks,
|
||||
searchUrl,
|
||||
} from "@/lib/search"
|
||||
import type { Engine } from "@/lib/search"
|
||||
|
||||
export type Command = { label: string; icon: ReactNode; run: () => void }
|
||||
@@ -25,7 +30,8 @@ export function SearchBar({
|
||||
}) {
|
||||
const [value, setValue] = useState("")
|
||||
const [fetched, setFetched] = useState<string[]>([])
|
||||
const [active, setActive] = useState(-1)
|
||||
// the row that the arrow keys or the mouse chose, null until then
|
||||
const [moved, setMoved] = useState<number | null>(null)
|
||||
const [focused, setFocused] = useState(false)
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
|
||||
@@ -57,7 +63,7 @@ export function SearchBar({
|
||||
}).catch(() => [])
|
||||
if (stale) return
|
||||
setFetched(result)
|
||||
setActive(-1) // the highlighted row now holds another suggestion
|
||||
setMoved(null) // the highlighted row now holds another suggestion
|
||||
}, 150)
|
||||
return () => {
|
||||
stale = true
|
||||
@@ -66,23 +72,34 @@ export function SearchBar({
|
||||
}, [query, commandMode, used])
|
||||
|
||||
const needle = value.slice(1).trim().toLowerCase()
|
||||
const matched = matchLinks(links, commandMode ? needle : query)
|
||||
const linkItem = (link: HomeLink): Command => ({
|
||||
label: link.name,
|
||||
icon: <LinkIcon link={link} className="size-5 rounded-md" />,
|
||||
run: () => window.location.assign(link.url),
|
||||
})
|
||||
const items: Command[] = commandMode
|
||||
? [
|
||||
...links.map((link) => ({
|
||||
label: link.name,
|
||||
icon: <LinkIcon link={link} className="size-5 rounded-md" />,
|
||||
run: () => window.location.assign(link.url),
|
||||
})),
|
||||
...commands,
|
||||
].filter((item) => item.label.toLowerCase().includes(needle))
|
||||
...matched.links.map(linkItem),
|
||||
...commands.filter((c) => c.label.toLowerCase().includes(needle)),
|
||||
]
|
||||
: query
|
||||
? fetched.map((s) => ({
|
||||
label: s,
|
||||
icon: <Search className="size-4 opacity-60" />,
|
||||
run: () => search(s),
|
||||
}))
|
||||
? [
|
||||
// a few, so the suggestions stay in view
|
||||
...matched.links.slice(0, 4).map(linkItem),
|
||||
...fetched.map((s) => ({
|
||||
label: s,
|
||||
icon: <Search className="size-4 opacity-60" />,
|
||||
run: () => search(s),
|
||||
})),
|
||||
]
|
||||
: []
|
||||
const open = focused && items.length > 0
|
||||
// Enter takes the highlighted row. Until the user moves, that is the best match:
|
||||
// with / the first row, else a link whose name starts with what was typed.
|
||||
// Without one, Enter searches the web.
|
||||
const best = commandMode ? items.length > 0 : matched.starts > 0
|
||||
const active = moved ?? (best ? 0 : -1)
|
||||
|
||||
const run = (item: Command) => {
|
||||
setValue("")
|
||||
@@ -96,9 +113,7 @@ export function SearchBar({
|
||||
className="relative w-full max-w-[680px]"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
// in command mode Enter takes the best match
|
||||
const item =
|
||||
active >= 0 ? items[active] : commandMode ? items[0] : undefined
|
||||
const item = active >= 0 ? items[active] : undefined
|
||||
if (item) run(item)
|
||||
else if (query && !commandMode) search(query)
|
||||
}}
|
||||
@@ -115,7 +130,7 @@ export function SearchBar({
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
setValue(e.target.value)
|
||||
setActive(-1)
|
||||
setMoved(null)
|
||||
}}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
@@ -124,7 +139,10 @@ export function SearchBar({
|
||||
if (!open || (e.key !== "ArrowDown" && e.key !== "ArrowUp")) return
|
||||
e.preventDefault()
|
||||
const step = e.key === "ArrowDown" ? 1 : -1
|
||||
setActive((active + step + items.length) % items.length)
|
||||
// the rows and, between the last and the first, no row: Enter then
|
||||
// searches what was typed, also when a link matches it
|
||||
const stops = items.length + 1
|
||||
setMoved(((active + 1 + step + stops) % stops) - 1)
|
||||
}}
|
||||
placeholder={`Search ${ENGINE_NAMES[used]}, or type / for commands`}
|
||||
aria-label="Search"
|
||||
@@ -159,7 +177,7 @@ export function SearchBar({
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
onClick={() => run(item)}
|
||||
onMouseMove={() => setActive(i)}
|
||||
onMouseMove={() => setMoved(i)}
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center gap-3 rounded-xl px-3.5 py-2.5",
|
||||
i === active && "bg-white/10"
|
||||
|
||||
+3
-1
@@ -86,6 +86,8 @@ export const dashboard = pgTable(
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
// order in the switcher and in the settings
|
||||
position: integer("position").notNull().default(0),
|
||||
// null = bundled default wallpaper
|
||||
wallpaperUrl: text("wallpaper_url"),
|
||||
// percent of black over the wallpaper, see DEFAULT_WALLPAPER_DIM
|
||||
@@ -147,7 +149,7 @@ export const settings = pgTable("settings", {
|
||||
.primaryKey()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
title: text("title").notNull().default("Dahoam"),
|
||||
// the dashboard that opens after sign-in; null = the oldest one
|
||||
// the dashboard that opens after sign-in; null = the first one
|
||||
defaultDashboardId: uuid("default_dashboard_id").references(
|
||||
() => dashboard.id,
|
||||
{ onDelete: "set null" }
|
||||
|
||||
+197
-18
@@ -1,12 +1,25 @@
|
||||
import { createServerFn } from "@tanstack/react-start"
|
||||
import { getRequestHeaders } from "@tanstack/react-start/server"
|
||||
import { and, asc, eq, inArray, sql } from "drizzle-orm"
|
||||
import { and, asc, desc, eq, inArray, sql } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import { db } from "@/db"
|
||||
import { card, dashboard, link, settings, wallpaper } from "@/db/schema"
|
||||
import {
|
||||
account,
|
||||
card,
|
||||
dashboard,
|
||||
icon,
|
||||
link,
|
||||
settings,
|
||||
wallpaper,
|
||||
} from "@/db/schema"
|
||||
import { auth, requireUser, signUpEnabled, ssoName } from "@/lib/auth"
|
||||
import { CLOCK_FONTS, CLOCK_STYLES } from "@/lib/clock"
|
||||
import { libraryNames } from "@/lib/icon-library"
|
||||
import { UPLOADED_ICON, lightVariant } from "@/lib/icons"
|
||||
import { ENGINES, parseSuggestions } from "@/lib/search"
|
||||
import { isReachable, statusChecks } from "@/lib/status"
|
||||
import { backupSchema, portable } from "@/lib/transfer"
|
||||
import type { Backup } from "@/lib/transfer"
|
||||
|
||||
const httpUrl = z.url({ protocol: /^https?$/ }).max(2000)
|
||||
|
||||
@@ -30,6 +43,17 @@ async function requireDashboard(userId: string, dashboardId: string) {
|
||||
const endOf = (cardId: string) =>
|
||||
sql<number>`(select coalesce(max(${link.position}) + 1, 0) from ${link} where ${link.cardId} = ${cardId})`
|
||||
|
||||
/** The position after the last card of a dashboard. */
|
||||
const endOfDashboard = (dashboardId: string) =>
|
||||
sql<number>`(select coalesce(max(${card.position}) + 1, 0) from ${card} where ${card.dashboardId} = ${dashboardId})`
|
||||
|
||||
/** The position after the last dashboard of a user. */
|
||||
const lastDashboard = (userId: string) =>
|
||||
sql<number>`(select coalesce(max(${dashboard.position}) + 1, 0) from ${dashboard} where ${dashboard.userId} = ${userId})`
|
||||
|
||||
// dashboards that were never moved all have position 0: oldest first
|
||||
const dashboardOrder = [asc(dashboard.position), asc(dashboard.createdAt)]
|
||||
|
||||
export const getAuthInfo = createServerFn({ method: "GET" }).handler(
|
||||
async () => ({
|
||||
signedIn: !!(await auth.api.getSession({ headers: getRequestHeaders() })),
|
||||
@@ -57,13 +81,18 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
const session = await auth.api.getSession({ headers: getRequestHeaders() })
|
||||
if (!session) return null
|
||||
const userId = session.user.id
|
||||
const [dashboards, rows] = await Promise.all([
|
||||
const [dashboards, rows, passwords] = await Promise.all([
|
||||
db
|
||||
.select(shown)
|
||||
.from(dashboard)
|
||||
.where(eq(dashboard.userId, userId))
|
||||
.orderBy(asc(dashboard.createdAt)),
|
||||
.orderBy(...dashboardOrder),
|
||||
db.select().from(settings).where(eq(settings.userId, userId)),
|
||||
// someone who only ever signed in with SSO has no password to change
|
||||
db.$count(
|
||||
account,
|
||||
and(eq(account.userId, userId), eq(account.providerId, "credential"))
|
||||
),
|
||||
])
|
||||
// Cards need a dashboard and links need a card, so nobody is left without one.
|
||||
// shortcut: two first loads at the same moment make two of each, add a unique
|
||||
@@ -80,7 +109,8 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
const byDefault = find(s?.defaultDashboardId) ?? dashboards[0]
|
||||
const current = find(data?.dashboardId) ?? byDefault
|
||||
const dashboardId = current.id
|
||||
const [cards, links] = await Promise.all([
|
||||
const [library, cards, links] = await Promise.all([
|
||||
libraryNames(),
|
||||
db
|
||||
.select({ id: card.id, name: card.name })
|
||||
.from(card)
|
||||
@@ -108,13 +138,23 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
.returning({ id: card.id, name: card.name }))
|
||||
)
|
||||
return {
|
||||
user: { name: session.user.name, email: session.user.email },
|
||||
user: {
|
||||
name: session.user.name,
|
||||
email: session.user.email,
|
||||
hasPassword: passwords > 0,
|
||||
},
|
||||
dashboards,
|
||||
dashboardId,
|
||||
defaultDashboardId: byDefault.id,
|
||||
cards: cards.map((c) => ({
|
||||
...c,
|
||||
links: links.filter((l) => l.cardId === c.id),
|
||||
links: links
|
||||
.filter((l) => l.cardId === c.id)
|
||||
.map((l) => ({
|
||||
...l,
|
||||
// an icon that the user chose stays as it is
|
||||
lightIcon: l.icon ? null : lightVariant(library, l.name),
|
||||
})),
|
||||
})),
|
||||
title: s?.title ?? "Dahoam",
|
||||
searchEngine: s?.searchEngine ?? "duckduckgo",
|
||||
@@ -123,9 +163,30 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
clockFont: s?.clockFont ?? "serif",
|
||||
clockStyle: s?.clockStyle ?? "solid",
|
||||
searxngUrl: process.env.SEARXNG_URL || null,
|
||||
statusChecks,
|
||||
}
|
||||
})
|
||||
|
||||
/** For every link of a dashboard: does its address answer? Empty when the checks are off. */
|
||||
export const getStatuses = createServerFn({ method: "GET" })
|
||||
.validator(z.object({ dashboardId: z.uuid() }))
|
||||
.handler(async ({ data }): Promise<Record<string, boolean>> => {
|
||||
const user = await requireUser()
|
||||
if (!statusChecks) return {}
|
||||
// only addresses that this user saved as links, never one from the request
|
||||
const links = await db
|
||||
.select({ id: link.id, url: link.url })
|
||||
.from(link)
|
||||
.innerJoin(card, eq(card.id, link.cardId))
|
||||
.where(
|
||||
and(eq(link.userId, user.id), eq(card.dashboardId, data.dashboardId))
|
||||
)
|
||||
// one request must not make the server call thousands of addresses
|
||||
.limit(200)
|
||||
const up = await Promise.all(links.map((l) => isReachable(l.url)))
|
||||
return Object.fromEntries(links.map((l, i) => [l.id, up[i]]))
|
||||
})
|
||||
|
||||
export const saveLink = createServerFn({ method: "POST" })
|
||||
.validator(
|
||||
z.object({
|
||||
@@ -161,26 +222,28 @@ export const saveCard = createServerFn({ method: "POST" })
|
||||
z.object({
|
||||
id: z.uuid().optional(),
|
||||
name: z.string().trim().min(1).max(40),
|
||||
// where a new card goes. A card that exists stays on its dashboard.
|
||||
// the dashboard of the card. Another one than before moves the card there.
|
||||
dashboardId: z.uuid(),
|
||||
})
|
||||
)
|
||||
.handler(async ({ data: { id, name, dashboardId } }) => {
|
||||
const user = await requireUser()
|
||||
await requireDashboard(user.id, dashboardId)
|
||||
const end = endOfDashboard(dashboardId)
|
||||
if (id) {
|
||||
await db
|
||||
.update(card)
|
||||
.set({ name })
|
||||
.set({
|
||||
name,
|
||||
dashboardId,
|
||||
// a card that changes dashboards goes after the last card there
|
||||
position: sql`case when ${card.dashboardId} = ${dashboardId} then ${card.position} else ${end} end`,
|
||||
})
|
||||
.where(and(eq(card.id, id), eq(card.userId, user.id)))
|
||||
} else {
|
||||
await requireDashboard(user.id, dashboardId)
|
||||
await db.insert(card).values({
|
||||
name,
|
||||
dashboardId,
|
||||
userId: user.id,
|
||||
// after the last card of the dashboard
|
||||
position: sql`(select coalesce(max(${card.position}) + 1, 0) from ${card} where ${card.dashboardId} = ${dashboardId})`,
|
||||
})
|
||||
await db
|
||||
.insert(card)
|
||||
.values({ name, dashboardId, userId: user.id, position: end })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -199,10 +262,38 @@ export const saveDashboard = createServerFn({ method: "POST" })
|
||||
.set({ name })
|
||||
.where(and(eq(dashboard.id, id), eq(dashboard.userId, user.id)))
|
||||
} else {
|
||||
await db.insert(dashboard).values({ name, userId: user.id })
|
||||
await db
|
||||
.insert(dashboard)
|
||||
.values({ name, userId: user.id, position: lastDashboard(user.id) })
|
||||
}
|
||||
})
|
||||
|
||||
/** Stores the order of the dashboards: all of the user's, as they should appear. */
|
||||
export const orderDashboards = createServerFn({ method: "POST" })
|
||||
.validator(z.object({ ids: z.array(z.uuid()).max(500) }))
|
||||
.handler(async ({ data }) => {
|
||||
const user = await requireUser()
|
||||
await db.transaction(async (tx) => {
|
||||
for (const [position, id] of data.ids.entries())
|
||||
await tx
|
||||
.update(dashboard)
|
||||
.set({ position })
|
||||
.where(and(eq(dashboard.id, id), eq(dashboard.userId, user.id)))
|
||||
})
|
||||
})
|
||||
|
||||
/** The images that the user uploaded as icons, the newest first, as link icons. */
|
||||
export const getIcons = createServerFn({ method: "GET" }).handler(async () => {
|
||||
const user = await requireUser()
|
||||
const icons = await db
|
||||
.select({ id: icon.id })
|
||||
.from(icon)
|
||||
.where(eq(icon.userId, user.id))
|
||||
.orderBy(desc(icon.createdAt))
|
||||
.limit(60)
|
||||
return icons.map((i) => UPLOADED_ICON + i.id)
|
||||
})
|
||||
|
||||
/** Deletes the dashboard and, through the foreign keys, its cards and their links. */
|
||||
export const deleteDashboard = createServerFn({ method: "POST" })
|
||||
.validator(z.object({ id: z.uuid() }))
|
||||
@@ -316,6 +407,94 @@ export const saveWallpaper = createServerFn({ method: "POST" })
|
||||
await db.delete(wallpaper).where(eq(wallpaper.dashboardId, dashboardId))
|
||||
})
|
||||
|
||||
/** Every dashboard of the user with its cards and links, see backupSchema. */
|
||||
export const exportData = createServerFn({ method: "GET" }).handler(
|
||||
async (): Promise<Backup> => {
|
||||
const user = await requireUser()
|
||||
const [dashboards, cards, links] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(dashboard)
|
||||
.where(eq(dashboard.userId, user.id))
|
||||
.orderBy(...dashboardOrder),
|
||||
db
|
||||
.select()
|
||||
.from(card)
|
||||
.where(eq(card.userId, user.id))
|
||||
.orderBy(asc(card.position), asc(card.createdAt)),
|
||||
db
|
||||
.select()
|
||||
.from(link)
|
||||
.where(eq(link.userId, user.id))
|
||||
.orderBy(asc(link.position), asc(link.createdAt)),
|
||||
])
|
||||
return {
|
||||
dashboards: dashboards.map((d) => ({
|
||||
name: d.name,
|
||||
wallpaperUrl: portable(d.wallpaperUrl),
|
||||
wallpaperDim: d.wallpaperDim,
|
||||
cards: cards
|
||||
.filter((c) => c.dashboardId === d.id)
|
||||
.map((c) => ({
|
||||
name: c.name,
|
||||
links: links
|
||||
.filter((l) => l.cardId === c.id)
|
||||
.map((l) => ({
|
||||
name: l.name,
|
||||
url: l.url,
|
||||
icon: portable(l.icon),
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** Adds the dashboards of an export or of a bookmarks file. Nothing is replaced. */
|
||||
export const importData = createServerFn({ method: "POST" })
|
||||
.validator(backupSchema)
|
||||
.handler(async ({ data }) => {
|
||||
const user = await requireUser()
|
||||
const userId = user.id
|
||||
const added = { dashboards: data.dashboards.length, cards: 0, links: 0 }
|
||||
// all of the file or nothing of it
|
||||
await db.transaction(async (tx) => {
|
||||
for (const d of data.dashboards) {
|
||||
const [{ id: dashboardId }] = await tx
|
||||
.insert(dashboard)
|
||||
.values({
|
||||
userId,
|
||||
name: d.name,
|
||||
position: lastDashboard(userId),
|
||||
wallpaperUrl: d.wallpaperUrl,
|
||||
wallpaperDim: d.wallpaperDim,
|
||||
})
|
||||
.returning({ id: dashboard.id })
|
||||
for (const [position, c] of d.cards.entries()) {
|
||||
const [{ id: cardId }] = await tx
|
||||
.insert(card)
|
||||
.values({ userId, dashboardId, position, name: c.name })
|
||||
.returning({ id: card.id })
|
||||
added.cards++
|
||||
added.links += c.links.length
|
||||
if (c.links.length)
|
||||
await tx.insert(link).values(
|
||||
c.links.map((l, at) => ({
|
||||
userId,
|
||||
cardId,
|
||||
position: at,
|
||||
name: l.name,
|
||||
url: l.url,
|
||||
// an upload of another account would not load here
|
||||
icon: portable(l.icon),
|
||||
}))
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
return added
|
||||
})
|
||||
|
||||
export const suggest = createServerFn({ method: "GET" })
|
||||
.validator(z.object({ q: z.string().max(200), searxng: z.boolean() }))
|
||||
.handler(async ({ data }) => {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Server side: what the icon library has. The link dialog loads the same index in the browser.
|
||||
import { LIBRARY_INDEX } from "@/lib/icons"
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000
|
||||
let known: { names: Set<string>; at: number } | undefined
|
||||
|
||||
/**
|
||||
* The names of the library's icons, kept in memory for a day. Empty when the
|
||||
* library cannot be reached: the dashboard then shows the plain icons.
|
||||
*/
|
||||
export async function libraryNames() {
|
||||
if (known && Date.now() - known.at < DAY) return known.names
|
||||
try {
|
||||
const res = await fetch(LIBRARY_INDEX, {
|
||||
// the page waits for this once a day at most, so not for long
|
||||
signal: AbortSignal.timeout(2000),
|
||||
})
|
||||
const index = (await res.json()) as { png: string[] }
|
||||
known = {
|
||||
names: new Set(index.png.map((file) => file.replace(/\.png$/, ""))),
|
||||
at: Date.now(),
|
||||
}
|
||||
} catch {
|
||||
// what was known before, and the next try in five minutes
|
||||
known = {
|
||||
names: known?.names ?? new Set(),
|
||||
at: Date.now() - DAY + 5 * 60 * 1000,
|
||||
}
|
||||
}
|
||||
return known.names
|
||||
}
|
||||
+23
-1
@@ -1,6 +1,11 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { UPLOADED_ICON, iconSources, searchIcons } from "./icons.ts"
|
||||
import {
|
||||
UPLOADED_ICON,
|
||||
iconSources,
|
||||
lightVariant,
|
||||
searchIcons,
|
||||
} from "./icons.ts"
|
||||
|
||||
const link = { name: "Home Assistant", url: "https://ha.example.com/lovelace" }
|
||||
const first = (icon: string | null) => iconSources({ ...link, icon })[0]
|
||||
@@ -12,6 +17,23 @@ test("no icon: looked up by name, then the site's favicon", () => {
|
||||
])
|
||||
})
|
||||
|
||||
test("the light version is used for a link without an icon of its own", () => {
|
||||
const library = new Set(["github", "github-light", "plex"])
|
||||
assert.equal(lightVariant(library, " GitHub "), "github-light")
|
||||
assert.equal(lightVariant(library, "Plex"), null)
|
||||
const github = { name: "GitHub", url: "https://github.com" }
|
||||
const lightIcon = "github-light"
|
||||
assert.match(
|
||||
iconSources({ ...github, icon: null, lightIcon })[0],
|
||||
/\/png\/github-light\.png$/
|
||||
)
|
||||
// the user chose the dark one
|
||||
assert.match(
|
||||
iconSources({ ...github, icon: "github", lightIcon })[0],
|
||||
/\/png\/github\.png$/
|
||||
)
|
||||
})
|
||||
|
||||
test("an icon name is looked up in the library", () => {
|
||||
assert.match(first(" Plex "), /\/png\/plex\.png$/)
|
||||
})
|
||||
|
||||
+15
-1
@@ -17,6 +17,15 @@ const slug = (name: string) =>
|
||||
|
||||
export const libraryIcon = (name: string) => `${LIBRARY}/png/${slug(name)}.png`
|
||||
|
||||
/**
|
||||
* The library has a light version of some icons (`github-light`), made for dark
|
||||
* backgrounds like the cards. Its name for a link that is called `name`, or null.
|
||||
*/
|
||||
export function lightVariant(libraryNames: Set<string>, name: string) {
|
||||
const light = `${slug(name)}-light`
|
||||
return libraryNames.has(light) ? light : null
|
||||
}
|
||||
|
||||
/** An image address or an upload, not a name in the library. */
|
||||
export const isImageAddress = (icon: string) =>
|
||||
/^https?:\/\//.test(icon) || icon.startsWith(UPLOADED_ICON)
|
||||
@@ -26,13 +35,18 @@ export function iconSources({
|
||||
name,
|
||||
url,
|
||||
icon,
|
||||
lightIcon,
|
||||
}: {
|
||||
name: string
|
||||
url: string
|
||||
icon: string | null
|
||||
/** see lightVariant; only used when the link has no icon of its own */
|
||||
lightIcon?: string | null
|
||||
}) {
|
||||
return [
|
||||
icon && isImageAddress(icon) ? icon : libraryIcon(icon || name),
|
||||
icon && isImageAddress(icon)
|
||||
? icon
|
||||
: libraryIcon(icon || lightIcon || name),
|
||||
`${new URL(url).origin}/favicon.ico`,
|
||||
]
|
||||
}
|
||||
|
||||
+22
-1
@@ -1,6 +1,27 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { parseSuggestions, searchUrl } from "./search.ts"
|
||||
import { matchLinks, parseSuggestions, searchUrl } from "./search.ts"
|
||||
|
||||
test("matchLinks", () => {
|
||||
const links = ["Grafana", "Home Assistant", "IT-Tools", "Sonarr"].map(
|
||||
(name) => ({ name })
|
||||
)
|
||||
const names = (typed: string) => {
|
||||
const { links: found, starts } = matchLinks(links, typed)
|
||||
return [found.map((l) => l.name).join(","), starts]
|
||||
}
|
||||
// the start of the name or of a word in it comes first and counts as a start
|
||||
assert.deepEqual(names("so"), ["Sonarr", 1])
|
||||
assert.deepEqual(names(" ASSIST "), ["Home Assistant", 1])
|
||||
assert.deepEqual(names("tools"), ["IT-Tools", 1])
|
||||
// only inside a word: listed, but Enter does not open it
|
||||
assert.deepEqual(names("ana"), ["Grafana", 0])
|
||||
assert.deepEqual(names("a"), ["Home Assistant,Grafana,Sonarr", 1])
|
||||
assert.deepEqual(names("plex"), ["", 0])
|
||||
// a query with a space is one phrase
|
||||
assert.deepEqual(names("home a"), ["Home Assistant", 1])
|
||||
assert.deepEqual(names("grafana docs"), ["", 0])
|
||||
})
|
||||
|
||||
test("searchUrl", () => {
|
||||
assert.equal(
|
||||
|
||||
@@ -29,6 +29,26 @@ export function searchUrl(
|
||||
return `https://duckduckgo.com/?q=${q}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The links for what was typed. First the ones where the name or a word of it starts
|
||||
* with it (`starts` of them: Enter opens the first), then the ones that contain it.
|
||||
*/
|
||||
export function matchLinks<TLink extends { name: string }>(
|
||||
links: TLink[],
|
||||
typed: string
|
||||
) {
|
||||
const q = typed.trim().toLowerCase()
|
||||
const starts: TLink[] = []
|
||||
const contains: TLink[] = []
|
||||
for (const link of links) {
|
||||
const name = link.name.toLowerCase()
|
||||
const words = [name, ...name.split(/[^\p{L}\p{N}]+/u)]
|
||||
if (words.some((word) => word.startsWith(q))) starts.push(link)
|
||||
else if (name.includes(q)) contains.push(link)
|
||||
}
|
||||
return { links: [...starts, ...contains], starts: starts.length }
|
||||
}
|
||||
|
||||
/** Both DuckDuckGo and SearXNG answer in OpenSearch form: [query, [suggestions]] */
|
||||
export function parseSuggestions(body: unknown): string[] {
|
||||
const list = Array.isArray(body) && Array.isArray(body[1]) ? body[1] : body
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { createServer } from "node:http"
|
||||
import { test } from "node:test"
|
||||
import { isReachable, isUp } from "./status.ts"
|
||||
|
||||
test("isUp: any answer below 500", () => {
|
||||
assert.equal(isUp({ status: 200 }), true)
|
||||
assert.equal(isUp({ status: 302 }), true)
|
||||
assert.equal(isUp({ status: 401 }), true) // a login page is an app that runs
|
||||
assert.equal(isUp({ status: 404 }), true)
|
||||
assert.equal(isUp({ status: 500 }), false)
|
||||
assert.equal(isUp({ status: 502 }), false)
|
||||
})
|
||||
|
||||
test("isUp: a certificate that this server does not trust is still an answer", () => {
|
||||
const failed = (code: string) =>
|
||||
Object.assign(new TypeError("fetch failed"), { cause: { code } })
|
||||
assert.equal(isUp({ error: failed("DEPTH_ZERO_SELF_SIGNED_CERT") }), true)
|
||||
assert.equal(isUp({ error: failed("UNABLE_TO_VERIFY_LEAF_SIGNATURE") }), true)
|
||||
assert.equal(isUp({ error: failed("ERR_TLS_CERT_ALTNAME_INVALID") }), true)
|
||||
assert.equal(isUp({ error: failed("ECONNREFUSED") }), false)
|
||||
assert.equal(isUp({ error: failed("ENOTFOUND") }), false)
|
||||
assert.equal(
|
||||
isUp({ error: new DOMException("timeout", "TimeoutError") }),
|
||||
false
|
||||
)
|
||||
assert.equal(isUp({ error: null }), false)
|
||||
})
|
||||
|
||||
test("isReachable: asks the address, once per minute", async () => {
|
||||
let requests = 0
|
||||
const server = createServer((req, res) => {
|
||||
requests++
|
||||
res.writeHead(req.url === "/broken" ? 503 : 302, {
|
||||
Location: "http://127.0.0.1:1/",
|
||||
})
|
||||
res.end()
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
|
||||
const { port } = server.address() as { port: number }
|
||||
const base = `http://127.0.0.1:${port}`
|
||||
try {
|
||||
// the redirect is not followed: its target does not answer
|
||||
assert.equal(await isReachable(`${base}/`), true)
|
||||
assert.equal(await isReachable(`${base}/`), true)
|
||||
assert.equal(requests, 1)
|
||||
assert.equal(await isReachable(`${base}/broken`), false)
|
||||
} finally {
|
||||
server.close()
|
||||
}
|
||||
assert.equal(await isReachable("http://127.0.0.1:1/"), false) // nothing listens
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
// Is the address of a link reachable? Server side: the server asks, not the browser,
|
||||
// so it also works for apps that do not allow requests from other pages.
|
||||
|
||||
/** Off unless the operator turns it on: users make the server call addresses they typed. */
|
||||
export const statusChecks = process.env.STATUS_CHECKS === "true"
|
||||
|
||||
const TTL = 60_000
|
||||
const TIMEOUT = 4000
|
||||
/** Per address the last check, also while it runs, so one address is asked once a minute. */
|
||||
const checks = new Map<string, { at: number; up: Promise<boolean> }>()
|
||||
|
||||
// A server answered, only this server does not trust its certificate (self-signed,
|
||||
// private CA). The browser of the user may well trust it.
|
||||
const CERTIFICATE = /CERT|SELF_SIGNED|UNABLE_TO_VERIFY|ALTNAME/
|
||||
|
||||
/** Up: any answer below 500. An app behind a proxy that is down answers 502 to 504. */
|
||||
export function isUp(result: { status: number } | { error: unknown }) {
|
||||
if ("status" in result) return result.status < 500
|
||||
const cause = (result.error as { cause?: { code?: unknown } } | null)?.cause
|
||||
return typeof cause?.code === "string" && CERTIFICATE.test(cause.code)
|
||||
}
|
||||
|
||||
async function check(url: string) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
// a redirect is an answer: do not follow it to another host
|
||||
redirect: "manual",
|
||||
signal: AbortSignal.timeout(TIMEOUT),
|
||||
})
|
||||
void res.body?.cancel() // the page itself is of no interest
|
||||
return isUp(res)
|
||||
} catch (error) {
|
||||
return isUp({ error })
|
||||
}
|
||||
}
|
||||
|
||||
export function isReachable(url: string) {
|
||||
const now = Date.now()
|
||||
if (checks.size > 1000)
|
||||
for (const [key, { at }] of checks) if (now - at > TTL) checks.delete(key)
|
||||
let last = checks.get(url)
|
||||
if (!last || now - last.at > TTL)
|
||||
checks.set(url, (last = { at: now, up: check(url) }))
|
||||
return last.up
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { backupSchema, parseBookmarks, portable } from "./transfer.ts"
|
||||
|
||||
// what Firefox and Chrome write, shortened
|
||||
const BOOKMARKS = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://example.com/top" ADD_DATE="1">Top level</A>
|
||||
<DT><H3 ADD_DATE="1" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://git.example.com/?a=1&b=2" ICON="data:image/png;base64,AAAA">Git & "CI" ü</A>
|
||||
<DT><H3>Media</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="http://plex.lan:32400/web">Plex</A>
|
||||
<DT><A HREF="javascript:alert(1)">A bookmarklet</A>
|
||||
<DT><A HREF="https://nameless.example.com/x"></A>
|
||||
</DL><p>
|
||||
<DT><A HREF="place:sort=8">Most visited</A>
|
||||
</DL><p>
|
||||
<DT><H3>Empty folder</H3>
|
||||
<DL><p>
|
||||
</DL><p>
|
||||
</DL><p>`
|
||||
|
||||
test("parseBookmarks: a card per folder that has bookmarks", () => {
|
||||
const found = parseBookmarks(BOOKMARKS)
|
||||
assert.ok(found)
|
||||
assert.equal(found.skipped, 2) // the bookmarklet and place:
|
||||
assert.deepEqual(found.backup, {
|
||||
dashboards: [
|
||||
{
|
||||
name: "Bookmarks",
|
||||
cards: [
|
||||
{
|
||||
name: "Bookmarks",
|
||||
links: [{ name: "Top level", url: "https://example.com/top" }],
|
||||
},
|
||||
{
|
||||
name: "Bookmarks bar",
|
||||
links: [
|
||||
{ name: 'Git & "CI" ü', url: "https://git.example.com/?a=1&b=2" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Media",
|
||||
links: [
|
||||
{ name: "Plex", url: "http://plex.lan:32400/web" },
|
||||
{
|
||||
name: "nameless.example.com",
|
||||
url: "https://nameless.example.com/x",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
// what it makes is what an import takes
|
||||
assert.ok(backupSchema.safeParse(found.backup).success)
|
||||
})
|
||||
|
||||
test("parseBookmarks: limits, long names, files without bookmarks", () => {
|
||||
assert.equal(parseBookmarks("<html><body>Hello</body></html>"), null)
|
||||
assert.equal(parseBookmarks('{"dashboards": []}'), null)
|
||||
const many = Array.from(
|
||||
{ length: 502 },
|
||||
(_, i) => `<DT><A HREF="https://example.com/${i}">${"n".repeat(70)}</A>`
|
||||
).join("")
|
||||
const found = parseBookmarks(`<DL>${many}</DL>`)
|
||||
assert.ok(found)
|
||||
assert.equal(found.backup.dashboards[0].cards[0].links.length, 500)
|
||||
assert.equal(found.backup.dashboards[0].cards[0].links[0].name.length, 60)
|
||||
assert.equal(found.skipped, 2)
|
||||
assert.ok(backupSchema.safeParse(found.backup).success)
|
||||
})
|
||||
|
||||
test("backupSchema refuses what is not a web address", () => {
|
||||
const withUrl = (url: string) => ({
|
||||
dashboards: [
|
||||
{ name: "D", cards: [{ name: "C", links: [{ name: "L", url }] }] },
|
||||
],
|
||||
})
|
||||
assert.ok(backupSchema.safeParse(withUrl("https://example.com")).success)
|
||||
assert.ok(!backupSchema.safeParse(withUrl("javascript:alert(1)")).success)
|
||||
assert.ok(!backupSchema.safeParse({ dashboards: [] }).success)
|
||||
// 11 cards with 500 links each are more than one file may hold
|
||||
const links = Array.from({ length: 500 }, () => ({
|
||||
name: "L",
|
||||
url: "https://example.com",
|
||||
}))
|
||||
const cards = (n: number) =>
|
||||
Array.from({ length: n }, () => ({ name: "C", links }))
|
||||
const file = (n: number) => ({ dashboards: [{ name: "D", cards: cards(n) }] })
|
||||
assert.ok(backupSchema.safeParse(file(10)).success)
|
||||
assert.ok(!backupSchema.safeParse(file(11)).success)
|
||||
})
|
||||
|
||||
test("portable: uploads stay with their account", () => {
|
||||
assert.equal(portable("/api/icon?id=1"), null)
|
||||
assert.equal(portable("plex"), "plex")
|
||||
assert.equal(
|
||||
portable("https://example.com/a.png"),
|
||||
"https://example.com/a.png"
|
||||
)
|
||||
assert.equal(portable(null), null)
|
||||
})
|
||||
@@ -0,0 +1,126 @@
|
||||
// Export and import: the shape of the file, and how a browser's bookmarks become one.
|
||||
import { z } from "zod"
|
||||
|
||||
const httpUrl = z.url({ protocol: /^https?$/ }).max(2000)
|
||||
const MAX_CARDS = 100
|
||||
const MAX_LINKS = 500 // per card
|
||||
const MAX_TOTAL = 5000 // links in one file
|
||||
|
||||
/**
|
||||
* What an export holds and an import takes: dashboards with their cards and links.
|
||||
* Uploaded wallpapers and icons are not in it, they belong to one account.
|
||||
*/
|
||||
export const backupSchema = z.object({
|
||||
dashboards: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string().trim().min(1).max(40),
|
||||
// an image on the web; null or missing: the default photo
|
||||
wallpaperUrl: httpUrl.nullish(),
|
||||
wallpaperDim: z.int().min(0).max(100).optional(),
|
||||
cards: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string().trim().min(1).max(40),
|
||||
links: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string().trim().min(1).max(60),
|
||||
url: httpUrl,
|
||||
// an image on the web or a name in the icon library
|
||||
icon: z.string().trim().max(2000).nullish(),
|
||||
})
|
||||
)
|
||||
.max(MAX_LINKS),
|
||||
})
|
||||
)
|
||||
.max(MAX_CARDS),
|
||||
})
|
||||
)
|
||||
.min(1)
|
||||
.max(20)
|
||||
// one import is one transaction: keep it small enough for that
|
||||
.refine(
|
||||
(dashboards) =>
|
||||
dashboards.flatMap((d) => d.cards.flatMap((c) => c.links)).length <=
|
||||
MAX_TOTAL
|
||||
),
|
||||
})
|
||||
export type Backup = z.infer<typeof backupSchema>
|
||||
|
||||
/** An upload ("/api/icon?id=…") only works for the account that made it. */
|
||||
export const portable = (address?: string | null) =>
|
||||
!address || address.startsWith("/") ? null : address
|
||||
|
||||
const ENTITIES: Record<string, string> = {
|
||||
amp: "&",
|
||||
lt: "<",
|
||||
gt: ">",
|
||||
quot: '"',
|
||||
apos: "'",
|
||||
}
|
||||
const text = (html: string) =>
|
||||
html
|
||||
.replace(/<[^>]*>/g, "")
|
||||
.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (entity, code: string) => {
|
||||
if (code[0] !== "#") return ENTITIES[code.toLowerCase()] ?? entity
|
||||
const point =
|
||||
code[1].toLowerCase() === "x"
|
||||
? parseInt(code.slice(2), 16)
|
||||
: parseInt(code.slice(1), 10)
|
||||
return point <= 0x10ffff ? String.fromCodePoint(point) : entity
|
||||
})
|
||||
.trim()
|
||||
|
||||
/**
|
||||
* The bookmarks file that every browser exports (HTML) as one dashboard: a card per
|
||||
* folder that has bookmarks, named like the folder. `skipped` counts what was left out:
|
||||
* addresses that are not http(s), and what is over the limits of an import.
|
||||
* Null when the file has no bookmark in it.
|
||||
*/
|
||||
export function parseBookmarks(html: string) {
|
||||
const cards = new Map<string, Backup["dashboards"][0]["cards"][0]>()
|
||||
const folders: string[] = [] // the path to where we are
|
||||
let heading: string | null = null // a folder name that waits for its <DL>
|
||||
let skipped = 0
|
||||
let total = 0
|
||||
const tags =
|
||||
/<DL\b|<\/DL>|<H3\b[^>]*>([\s\S]*?)<\/H3>|<A\b([^>]*)>([\s\S]*?)<\/A>/gi
|
||||
for (const [tag, folder, attributes, title] of html.matchAll(tags)) {
|
||||
if (/^<DL/i.test(tag)) {
|
||||
folders.push(heading ?? "")
|
||||
heading = null
|
||||
} else if (/^<\/DL/i.test(tag)) folders.pop()
|
||||
else if (/^<H3/i.test(tag)) heading = text(folder)
|
||||
else {
|
||||
const href = /\bHREF\s*=\s*"([^"]*)"/i.exec(attributes)
|
||||
const url = httpUrl.safeParse(text(href?.[1] ?? ""))
|
||||
// two folders with the same name stay two cards
|
||||
const path = folders.join("\n")
|
||||
const card = cards.get(path) ?? {
|
||||
name: (folders.filter(Boolean).at(-1) ?? "Bookmarks").slice(0, 40),
|
||||
links: [],
|
||||
}
|
||||
if (
|
||||
!url.success ||
|
||||
total >= MAX_TOTAL ||
|
||||
card.links.length >= MAX_LINKS ||
|
||||
(!cards.has(path) && cards.size >= MAX_CARDS)
|
||||
) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
cards.set(path, card)
|
||||
total++
|
||||
card.links.push({
|
||||
name: (text(title) || new URL(url.data).hostname).slice(0, 60),
|
||||
url: url.data,
|
||||
})
|
||||
}
|
||||
}
|
||||
if (!cards.size) return null
|
||||
const backup: Backup = {
|
||||
dashboards: [{ name: "Bookmarks", cards: [...cards.values()] }],
|
||||
}
|
||||
return { backup, skipped }
|
||||
}
|
||||
+45
-9
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react"
|
||||
import { useEffect, useState } from "react"
|
||||
import {
|
||||
Link,
|
||||
createFileRoute,
|
||||
@@ -19,11 +19,12 @@ import { CardGrid } from "@/components/card-grid"
|
||||
import { Clock } from "@/components/clock"
|
||||
import { LinkDialog } from "@/components/link-dialog"
|
||||
import type { LinkTarget } from "@/components/link-dialog"
|
||||
import { StatusContext } from "@/components/link-tile"
|
||||
import { Logo } from "@/components/logo"
|
||||
import { SearchBar } from "@/components/search-bar"
|
||||
import { Wallpaper } from "@/components/wallpaper"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
import { getDashboard } from "@/lib/dashboard.functions"
|
||||
import { getDashboard, getStatuses } from "@/lib/dashboard.functions"
|
||||
import { Button } from "@/vendor/collabry/components/Button/Button"
|
||||
import { cn } from "@/vendor/collabry/lib/cn"
|
||||
|
||||
@@ -44,9 +45,41 @@ export const Route = createFileRoute("/")({
|
||||
const onWallpaper =
|
||||
"rounded-full text-white/80 hover:bg-white/10 hover:text-white"
|
||||
|
||||
/**
|
||||
* Which links answer, asked again every minute and when the tab is opened again.
|
||||
* `links` is their ids: a new link is checked at once.
|
||||
*/
|
||||
function useStatuses(on: boolean, dashboardId: string, links: string) {
|
||||
const [statuses, setStatuses] = useState<Record<string, boolean>>({})
|
||||
useEffect(() => {
|
||||
if (!on) return
|
||||
let stale = false
|
||||
const load = () => {
|
||||
if (document.hidden) return
|
||||
getStatuses({ data: { dashboardId } })
|
||||
.then((found) => !stale && setStatuses(found))
|
||||
.catch(() => {}) // the dots stay as they were
|
||||
}
|
||||
load()
|
||||
const timer = setInterval(load, 60_000)
|
||||
document.addEventListener("visibilitychange", load)
|
||||
return () => {
|
||||
stale = true
|
||||
clearInterval(timer)
|
||||
document.removeEventListener("visibilitychange", load)
|
||||
}
|
||||
}, [on, dashboardId, links])
|
||||
return statuses
|
||||
}
|
||||
|
||||
function Dashboard() {
|
||||
const data = Route.useLoaderData()
|
||||
const router = useRouter()
|
||||
const statuses = useStatuses(
|
||||
data.statusChecks,
|
||||
data.dashboardId,
|
||||
data.cards.flatMap((c) => c.links.map((l) => l.id)).join()
|
||||
)
|
||||
const [link, setLink] = useState<LinkTarget | null>(null)
|
||||
const [card, setCard] = useState<CardTarget | null>(null)
|
||||
|
||||
@@ -161,13 +194,15 @@ function Dashboard() {
|
||||
</div>
|
||||
|
||||
<div className="mt-[7vh] flex w-full flex-col items-center">
|
||||
<CardGrid
|
||||
cards={data.cards}
|
||||
onAddCard={() => setCard("new")}
|
||||
onAddLink={(c) => setLink({ cardId: c.id })}
|
||||
onEditLink={setLink}
|
||||
onEditCard={setCard}
|
||||
/>
|
||||
<StatusContext value={statuses}>
|
||||
<CardGrid
|
||||
cards={data.cards}
|
||||
onAddCard={() => setCard("new")}
|
||||
onAddLink={(c) => setLink({ cardId: c.id })}
|
||||
onEditLink={setLink}
|
||||
onEditCard={setCard}
|
||||
/>
|
||||
</StatusContext>
|
||||
</div>
|
||||
|
||||
<div className="flex-[3]" />
|
||||
@@ -206,6 +241,7 @@ function Dashboard() {
|
||||
<CardDialog
|
||||
card={card}
|
||||
dashboardId={data.dashboardId}
|
||||
dashboards={data.dashboards}
|
||||
onClose={() => setCard(null)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
+213
-2
@@ -8,10 +8,14 @@ import {
|
||||
useRouter,
|
||||
} from "@tanstack/react-router"
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowDownUp,
|
||||
ArrowLeft,
|
||||
ArrowUp,
|
||||
Check,
|
||||
CircleUser,
|
||||
Clock,
|
||||
Download,
|
||||
Image,
|
||||
LayoutDashboard,
|
||||
LogOut,
|
||||
@@ -33,13 +37,18 @@ import {
|
||||
import type { ClockFont, ClockStyle } from "@/lib/clock"
|
||||
import {
|
||||
deleteDashboard,
|
||||
exportData,
|
||||
getDashboard,
|
||||
importData,
|
||||
orderDashboards,
|
||||
saveDashboard,
|
||||
saveSettings,
|
||||
saveWallpaper,
|
||||
} from "@/lib/dashboard.functions"
|
||||
import { ENGINES, ENGINE_NAMES } from "@/lib/search"
|
||||
import type { Engine } from "@/lib/search"
|
||||
import { parseBookmarks } from "@/lib/transfer"
|
||||
import type { Backup } from "@/lib/transfer"
|
||||
import { Button } from "@/vendor/collabry/components/Button/Button"
|
||||
import {
|
||||
Field,
|
||||
@@ -95,6 +104,7 @@ const SECTIONS = [
|
||||
{ id: "clock", label: "Clock", icon: Clock },
|
||||
{ id: "search", label: "Search", icon: Search },
|
||||
{ id: "wallpaper", label: "Wallpaper", icon: Image },
|
||||
{ id: "transfer", label: "Export and import", icon: ArrowDownUp },
|
||||
{ id: "account", label: "Account", icon: CircleUser },
|
||||
]
|
||||
|
||||
@@ -130,6 +140,9 @@ function Settings() {
|
||||
const router = useRouter()
|
||||
const hash = useLocation({ select: (l) => l.hash }) || SECTIONS[0].id
|
||||
const file = useRef<HTMLInputElement>(null)
|
||||
const importFile = useRef<HTMLInputElement>(null)
|
||||
// what the last import added
|
||||
const [imported, setImported] = useState("")
|
||||
const [status, setStatus] = useState<"idle" | "saving" | "saved">("idle")
|
||||
const [error, setError] = useState("")
|
||||
// follows the slider at once, the save comes a moment later
|
||||
@@ -174,6 +187,54 @@ function Settings() {
|
||||
|
||||
const uploaded = !!data.wallpaperUrl?.startsWith("/")
|
||||
|
||||
/** Swaps a dashboard with the one before (-1) or after it (1). */
|
||||
const moveDashboard = (index: number, by: -1 | 1) => {
|
||||
const ids = data.dashboards.map((d) => d.id)
|
||||
;[ids[index], ids[index + by]] = [ids[index + by], ids[index]]
|
||||
return run(() => orderDashboards({ data: { ids } }))
|
||||
}
|
||||
|
||||
const download = async () => {
|
||||
const backup = await exportData()
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([JSON.stringify(backup, null, 2)], { type: "application/json" })
|
||||
)
|
||||
const a = document.createElement("a")
|
||||
a.href = url
|
||||
a.download = `dahoam-${new Date().toISOString().slice(0, 10)}.json`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
// an export of this app (JSON) or the bookmarks file of a browser (HTML)
|
||||
const importFrom = (chosen: File) =>
|
||||
run(async () => {
|
||||
setImported("")
|
||||
if (chosen.size > 5 * 1024 * 1024) return "The file is larger than 5 MB."
|
||||
const content = await chosen.text()
|
||||
let backup: unknown
|
||||
let skipped = 0
|
||||
try {
|
||||
backup = JSON.parse(content)
|
||||
} catch {
|
||||
const bookmarks = parseBookmarks(content)
|
||||
if (!bookmarks) return "This file has no dashboards or bookmarks in it."
|
||||
;({ backup, skipped } = bookmarks)
|
||||
}
|
||||
// whether it really is one, the server checks
|
||||
const added = await importData({ data: backup as Backup }).catch(
|
||||
() => null
|
||||
)
|
||||
if (!added) return "This file is not an export of Dahoam."
|
||||
const count = (n: number, thing: string) =>
|
||||
`${n} ${thing}${n === 1 ? "" : "s"}`
|
||||
setImported(
|
||||
`Added ${count(added.dashboards, "dashboard")} with ${count(added.cards, "card")} and ${count(added.links, "link")}.` +
|
||||
(skipped
|
||||
? ` ${count(skipped, "bookmark")} left out: not a web address, or more than a card holds.`
|
||||
: "")
|
||||
)
|
||||
})
|
||||
|
||||
return (
|
||||
// A page of its own: solid Collabry surfaces, no wallpaper behind it
|
||||
<div className="min-h-svh bg-app">
|
||||
@@ -277,10 +338,11 @@ function Settings() {
|
||||
<SettingsSectionDescription>
|
||||
Each dashboard has its own cards, for example Home and Work.
|
||||
With more than one, you switch between them at the top of
|
||||
the dashboard. The default one opens when you sign in.
|
||||
the dashboard, in the order that the arrows here set. The
|
||||
default one opens when you sign in.
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
{data.dashboards.map((d) => {
|
||||
{data.dashboards.map((d, i) => {
|
||||
const isDefault = d.id === data.defaultDashboardId
|
||||
return (
|
||||
<SettingsRow key={d.id}>
|
||||
@@ -296,6 +358,28 @@ function Settings() {
|
||||
/>
|
||||
</SettingsRowText>
|
||||
<SettingsRowControl className="flex flex-wrap gap-2">
|
||||
{data.dashboards.length > 1 && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
iconOnly
|
||||
aria-label={`Move ${d.name} up`}
|
||||
disabled={i === 0}
|
||||
onClick={() => moveDashboard(i, -1)}
|
||||
>
|
||||
<ArrowUp size={15} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
iconOnly
|
||||
aria-label={`Move ${d.name} down`}
|
||||
disabled={i === data.dashboards.length - 1}
|
||||
onClick={() => moveDashboard(i, 1)}
|
||||
>
|
||||
<ArrowDown size={15} />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
disabled={isDefault}
|
||||
onClick={() => save({ defaultDashboardId: d.id })}
|
||||
@@ -481,6 +565,8 @@ function Settings() {
|
||||
<SegmentedControl
|
||||
aria-labelledby="settings-wallpaper-of"
|
||||
size="md"
|
||||
// many dashboards on a narrow screen: scroll, not overflow
|
||||
className="max-w-full overflow-x-auto"
|
||||
value={data.dashboardId}
|
||||
onValueChange={(d) =>
|
||||
router.navigate({
|
||||
@@ -616,6 +702,72 @@ function Settings() {
|
||||
</SettingsRow>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection id="transfer" className={section}>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>Export and import</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
Keep a copy of your dashboards, move them to another
|
||||
account, or start from the bookmarks of your browser.
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
<SettingsRow>
|
||||
<SettingsRowText>
|
||||
<div className="leading-tight font-bold">Export</div>
|
||||
<SettingsRowDescription>
|
||||
One file with all dashboards, their cards and links.
|
||||
Images that you uploaded are not in it.
|
||||
</SettingsRowDescription>
|
||||
</SettingsRowText>
|
||||
<SettingsRowControl>
|
||||
<Button
|
||||
onClick={() =>
|
||||
download().catch(() => setError("Could not export."))
|
||||
}
|
||||
>
|
||||
<Download size={15} /> Export
|
||||
</Button>
|
||||
</SettingsRowControl>
|
||||
</SettingsRow>
|
||||
<SettingsRow>
|
||||
<SettingsRowText>
|
||||
<div className="leading-tight font-bold">Import</div>
|
||||
<SettingsRowDescription>
|
||||
An export of Dahoam, or the bookmarks file that your
|
||||
browser exports (HTML): a dashboard "Bookmarks" with a
|
||||
card per folder. An import adds dashboards, it replaces
|
||||
nothing.
|
||||
</SettingsRowDescription>
|
||||
{imported && (
|
||||
<SettingsRowDescription
|
||||
role="status"
|
||||
className="text-success-fg"
|
||||
>
|
||||
{imported}
|
||||
</SettingsRowDescription>
|
||||
)}
|
||||
</SettingsRowText>
|
||||
<SettingsRowControl>
|
||||
<input
|
||||
ref={importFile}
|
||||
type="file"
|
||||
accept=".json,.html,.htm,application/json,text/html"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const chosen = e.target.files?.[0]
|
||||
if (chosen) void importFrom(chosen)
|
||||
e.target.value = ""
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
disabled={status === "saving"}
|
||||
onClick={() => importFile.current?.click()}
|
||||
>
|
||||
<Upload size={15} /> Choose a file
|
||||
</Button>
|
||||
</SettingsRowControl>
|
||||
</SettingsRow>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection id="account" className={section}>
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>Account</SettingsSectionTitle>
|
||||
@@ -640,6 +792,65 @@ function Settings() {
|
||||
</Button>
|
||||
</SettingsRowControl>
|
||||
</SettingsRow>
|
||||
{data.user.hasPassword && (
|
||||
<SettingsRow stacked>
|
||||
<SettingsRowText>
|
||||
<div className="leading-tight font-bold">Password</div>
|
||||
<SettingsRowDescription>
|
||||
A new password signs you out on your other devices.
|
||||
</SettingsRowDescription>
|
||||
</SettingsRowText>
|
||||
<SettingsRowControl>
|
||||
<form
|
||||
className="flex flex-wrap items-end gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
const form = e.currentTarget
|
||||
const fields = new FormData(form)
|
||||
void run(async () => {
|
||||
// Better Auth returns { error } instead of throwing
|
||||
const { error: failure } =
|
||||
await authClient.changePassword({
|
||||
currentPassword: String(fields.get("current")),
|
||||
newPassword: String(fields.get("new")),
|
||||
revokeOtherSessions: true,
|
||||
})
|
||||
if (failure)
|
||||
return (
|
||||
failure.message ||
|
||||
"Could not change the password."
|
||||
)
|
||||
form.reset()
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Field className="w-56">
|
||||
<FieldLabel>Current password</FieldLabel>
|
||||
<Input
|
||||
name="current"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field className="w-56">
|
||||
<FieldLabel>New password</FieldLabel>
|
||||
<Input
|
||||
name="new"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
minLength={8}
|
||||
maxLength={128}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Button type="submit" disabled={status === "saving"}>
|
||||
Change password
|
||||
</Button>
|
||||
</form>
|
||||
</SettingsRowControl>
|
||||
</SettingsRow>
|
||||
)}
|
||||
</SettingsSection>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user