From 87e3d1fb30342aab4bba94d7364107e63f0b05be Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 19 Nov 2026 09:51:16 -0800 Subject: [PATCH] Wrap list chips, add list sharing and public/unlisted/private visibility - Home page list chips wrap to new rows instead of scrolling off the edge - Lists are public, unlisted or private (migrated from the visible flag) - Unlisted lists are reachable only at /s/; slug URLs are public-only - Share button on list pages and in the editor/dashboard; owners can reset an unlisted link Co-Authored-By: Claude Opus 5.5 --- docker-compose.yml => compose.yaml | 0 internal/server/api.go | 14 +++++ internal/server/preview.go | 2 +- internal/server/public.go | 35 ++++++++--- internal/server/server.go | 2 + internal/store/lists.go | 70 ++++++++++++++++++--- internal/store/store.go | 7 +++ internal/store/store_test.go | 43 +++++++++++++ web/static/css/app.css | 7 +-- web/static/js/admin-list.js | 8 ++- web/static/js/admin-lists.js | 7 ++- web/static/js/list-form.js | 16 ++++- web/static/js/public.js | 7 +++ web/static/js/share.js | 96 +++++++++++++++++++++++++++++ web/templates/pages/admin_list.html | 3 +- web/templates/pages/list.html | 3 +- 16 files changed, 292 insertions(+), 28 deletions(-) rename docker-compose.yml => compose.yaml (100%) create mode 100644 web/static/js/share.js diff --git a/docker-compose.yml b/compose.yaml similarity index 100% rename from docker-compose.yml rename to compose.yaml diff --git a/internal/server/api.go b/internal/server/api.go index 2cfe16d..b6a1ae9 100644 --- a/internal/server/api.go +++ b/internal/server/api.go @@ -64,6 +64,20 @@ func (s *Server) apiUpdateList(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, l) } +func (s *Server) apiResetShareLink(w http.ResponseWriter, r *http.Request) { + id, err := pathID(r) + if err != nil { + s.writeErr(w, err) + return + } + l, err := s.store.ResetShareToken(r.Context(), id) + if err != nil { + s.writeErr(w, err) + return + } + writeJSON(w, http.StatusOK, l) +} + func (s *Server) apiDeleteList(w http.ResponseWriter, r *http.Request) { id, err := pathID(r) if err != nil { diff --git a/internal/server/preview.go b/internal/server/preview.go index 3f0a027..7b78740 100644 --- a/internal/server/preview.go +++ b/internal/server/preview.go @@ -87,7 +87,7 @@ func (s *Server) handleItemPreview(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - if !l.Visible { + if l.Visibility == store.VisibilityPrivate { if _, ok := s.currentUser(r); !ok { http.NotFound(w, r) return diff --git a/internal/server/public.go b/internal/server/public.go index b6eeee4..be413f3 100644 --- a/internal/server/public.go +++ b/internal/server/public.go @@ -3,6 +3,7 @@ package server import ( "errors" "net/http" + "slices" "strconv" "github.com/cdnutter/canon/internal/store" @@ -153,10 +154,22 @@ type listPage struct { PageNums []int } -// visibleList loads the list named in the URL, treating hidden lists as -// missing for visitors. It writes the error response when ok is false. +// visibleList loads the list named in the URL. Only public lists are +// reachable by slug; unlisted ones go through their share link, and the +// owner sees everything. It writes the error response when ok is false. func (s *Server) visibleList(w http.ResponseWriter, r *http.Request) (l store.List, ok bool) { l, err := s.store.ListBySlug(r.Context(), r.PathValue("slug")) + return s.allowList(w, r, l, err, store.VisibilityPublic) +} + +// sharedList loads the list behind a share link, which works for public +// and unlisted lists. +func (s *Server) sharedList(w http.ResponseWriter, r *http.Request) (l store.List, ok bool) { + l, err := s.store.ListByShareToken(r.Context(), r.PathValue("token")) + return s.allowList(w, r, l, err, store.VisibilityPublic, store.VisibilityUnlisted) +} + +func (s *Server) allowList(w http.ResponseWriter, r *http.Request, l store.List, err error, allowed ...string) (store.List, bool) { if errors.Is(err, store.ErrNotFound) { s.notFound(w, r) return l, false @@ -165,7 +178,7 @@ func (s *Server) visibleList(w http.ResponseWriter, r *http.Request) (l store.Li s.serverError(w, r, err) return l, false } - if !l.Visible { + if !slices.Contains(allowed, l.Visibility) { if _, loggedIn := s.currentUser(r); !loggedIn { s.notFound(w, r) return l, false @@ -175,11 +188,19 @@ func (s *Server) visibleList(w http.ResponseWriter, r *http.Request) (l store.Li } func (s *Server) handleList(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - l, ok := s.visibleList(w, r) - if !ok { - return + if l, ok := s.visibleList(w, r); ok { + s.renderList(w, r, l) } +} + +func (s *Server) handleSharedList(w http.ResponseWriter, r *http.Request) { + if l, ok := s.sharedList(w, r); ok { + s.renderList(w, r, l) + } +} + +func (s *Server) renderList(w http.ResponseWriter, r *http.Request, l store.List) { + ctx := r.Context() site := s.site(ctx) p := listPage{List: l, Page: 1} p.Category = listCategory(l) diff --git a/internal/server/server.go b/internal/server/server.go index 895e4ec..05505b6 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -106,6 +106,7 @@ func (s *Server) Handler() http.Handler { // Public mux.HandleFunc("GET /{$}", s.gated(s.handleHome)) mux.HandleFunc("GET /l/{slug}", s.gated(s.handleList)) + mux.HandleFunc("GET /s/{token}", s.gated(s.handleSharedList)) mux.HandleFunc("GET /l/{slug}/export", s.gatedAsset(s.handleExport)) mux.HandleFunc("GET /preview/{id}", s.gatedAsset(s.handleItemPreview)) mux.HandleFunc("GET /images/{name}", s.gatedAsset(s.handleImage)) @@ -137,6 +138,7 @@ func (s *Server) Handler() http.Handler { api("POST /api/lists", s.apiCreateList) api("POST /api/lists/order", s.apiReorderLists) api("PUT /api/lists/{id}", s.apiUpdateList) + api("POST /api/lists/{id}/share-link", s.apiResetShareLink) api("DELETE /api/lists/{id}", s.apiDeleteList) api("GET /api/lists/{id}/items", s.apiItems) api("POST /api/lists/{id}/items", s.apiAddItem) diff --git a/internal/store/lists.go b/internal/store/lists.go index 8fb5cea..8ccfa01 100644 --- a/internal/store/lists.go +++ b/internal/store/lists.go @@ -15,6 +15,26 @@ const ( SoftListSizeWarning = 1000 ) +// List visibility. Public lists show on the home page; unlisted ones are +// only reachable through their share link; private ones only by the owner. +const ( + VisibilityPublic = "public" + VisibilityUnlisted = "unlisted" + VisibilityPrivate = "private" +) + +// SharePath is the address to send people: the slug for public lists, the +// share token for unlisted ones. Private lists have none. +func (l List) SharePath() string { + switch l.Visibility { + case VisibilityPublic: + return "/l/" + l.Slug + case VisibilityUnlisted: + return "/s/" + l.ShareToken + } + return "" +} + type List struct { ID int64 `json:"id"` Slug string `json:"slug"` @@ -23,19 +43,21 @@ type List struct { Description string `json:"description"` MaxItems int `json:"maxItems"` Position int `json:"position"` - Visible bool `json:"visible"` + Visible bool `json:"visible"` // Visibility == "public"; kept for older clients + Visibility string `json:"visibility"` // "public", "unlisted" or "private" + ShareToken string `json:"shareToken"` Layout string `json:"layout"` // a ListStyles key, e.g. "podium" Art string `json:"art"` // "", "poster" or "square"; "" = category default ItemCount int `json:"itemCount"` UpdatedAt int64 `json:"updatedAt"` } -const listColumns = `l.id, l.slug, l.title, l.category, l.description, l.max_items, l.position, l.visible, l.layout, l.art, l.updated_at, +const listColumns = `l.id, l.slug, l.title, l.category, l.description, l.max_items, l.position, l.visible, l.visibility, l.share_token, l.layout, l.art, l.updated_at, (SELECT COUNT(*) FROM items i WHERE i.list_id = l.id)` func scanList(row interface{ Scan(...any) error }) (List, error) { var l List - err := row.Scan(&l.ID, &l.Slug, &l.Title, &l.Category, &l.Description, &l.MaxItems, &l.Position, &l.Visible, &l.Layout, &l.Art, &l.UpdatedAt, &l.ItemCount) + err := row.Scan(&l.ID, &l.Slug, &l.Title, &l.Category, &l.Description, &l.MaxItems, &l.Position, &l.Visible, &l.Visibility, &l.ShareToken, &l.Layout, &l.Art, &l.UpdatedAt, &l.ItemCount) if errors.Is(err, sql.ErrNoRows) { return l, ErrNotFound } @@ -68,6 +90,13 @@ func (s *Store) ListByID(ctx context.Context, id int64) (List, error) { return scanList(s.db.QueryRowContext(ctx, `SELECT `+listColumns+` FROM lists l WHERE l.id = ?`, id)) } +func (s *Store) ListByShareToken(ctx context.Context, token string) (List, error) { + if token == "" { + return List{}, ErrNotFound + } + return scanList(s.db.QueryRowContext(ctx, `SELECT `+listColumns+` FROM lists l WHERE l.share_token = ?`, token)) +} + func (s *Store) ListBySlug(ctx context.Context, slug string) (List, error) { return scanList(s.db.QueryRowContext(ctx, `SELECT `+listColumns+` FROM lists l WHERE l.slug = ?`, slug)) } @@ -103,6 +132,18 @@ func (l *List) normalize() error { if l.Art != "poster" && l.Art != "square" { l.Art = "" } + switch l.Visibility { + case VisibilityPublic, VisibilityUnlisted, VisibilityPrivate: + case "": + // Older clients only send the visible flag. + l.Visibility = VisibilityPrivate + if l.Visible { + l.Visibility = VisibilityPublic + } + default: + return invalid("Unknown visibility %q", l.Visibility) + } + l.Visible = l.Visibility == VisibilityPublic return nil } @@ -152,9 +193,9 @@ func (s *Store) CreateList(ctx context.Context, l List) (List, error) { if err != nil { return l, err } - res, err := s.db.ExecContext(ctx, `INSERT INTO lists (slug, title, category, description, max_items, position, visible, layout, art) - VALUES (?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), 0) + 1 FROM lists), ?, ?, ?)`, - slug, l.Title, l.Category, l.Description, l.MaxItems, l.Visible, l.Layout, l.Art) + res, err := s.db.ExecContext(ctx, `INSERT INTO lists (slug, title, category, description, max_items, position, visible, visibility, share_token, layout, art) + VALUES (?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), 0) + 1 FROM lists), ?, ?, lower(hex(randomblob(9))), ?, ?)`, + slug, l.Title, l.Category, l.Description, l.MaxItems, l.Visible, l.Visibility, l.Layout, l.Art) if err != nil { return l, err } @@ -187,14 +228,27 @@ func (s *Store) UpdateList(ctx context.Context, l List) (List, error) { return l, err } } - _, err = s.db.ExecContext(ctx, `UPDATE lists SET slug=?, title=?, category=?, description=?, max_items=?, visible=?, layout=?, art=?, updated_at=unixepoch() WHERE id=?`, - slug, l.Title, l.Category, l.Description, l.MaxItems, l.Visible, l.Layout, l.Art, l.ID) + _, err = s.db.ExecContext(ctx, `UPDATE lists SET slug=?, title=?, category=?, description=?, max_items=?, visible=?, visibility=?, layout=?, art=?, updated_at=unixepoch() WHERE id=?`, + slug, l.Title, l.Category, l.Description, l.MaxItems, l.Visible, l.Visibility, l.Layout, l.Art, l.ID) if err != nil { return l, err } return s.ListByID(ctx, l.ID) } +// ResetShareToken gives the list a new share link, so the old one stops +// working. +func (s *Store) ResetShareToken(ctx context.Context, id int64) (List, error) { + res, err := s.db.ExecContext(ctx, `UPDATE lists SET share_token = lower(hex(randomblob(9))) WHERE id = ?`, id) + if err != nil { + return List{}, err + } + if n, _ := res.RowsAffected(); n == 0 { + return List{}, ErrNotFound + } + return s.ListByID(ctx, id) +} + func (s *Store) DeleteList(ctx context.Context, id int64) error { res, err := s.db.ExecContext(ctx, `DELETE FROM lists WHERE id = ?`, id) if err != nil { diff --git a/internal/store/store.go b/internal/store/store.go index e571680..6a068ec 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -117,6 +117,13 @@ CREATE INDEX items_list_rank ON items(list_id, rank); // rather than taking the source's; refresh leaves it alone unless asked. `ALTER TABLE items ADD COLUMN image_custom INTEGER NOT NULL DEFAULT 0; UPDATE items SET image_custom = 1 WHERE image_source = 'upload';`, + // Public / unlisted / private, replacing the visible flag (kept in sync + // for older code paths), plus a random token for unlisted share links. + `ALTER TABLE lists ADD COLUMN visibility TEXT NOT NULL DEFAULT 'public'; +UPDATE lists SET visibility = 'private' WHERE visible = 0; +ALTER TABLE lists ADD COLUMN share_token TEXT NOT NULL DEFAULT ''; +UPDATE lists SET share_token = lower(hex(randomblob(9))); +CREATE UNIQUE INDEX lists_share_token ON lists(share_token);`, } func (s *Store) migrate(ctx context.Context) error { diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 1ca90af..7623468 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -334,3 +334,46 @@ func TestPlaces(t *testing.T) { } check("close gaps", "D,H,A,F,B,G") } + +func TestVisibility(t *testing.T) { + ctx := context.Background() + s := newTestStore(t) + // Old clients send only the visible flag. + pub, err := s.CreateList(ctx, List{Title: "Pub", Category: "movie", MaxItems: 5, Visible: true}) + if err != nil { + t.Fatal(err) + } + if pub.Visibility != VisibilityPublic || !pub.Visible || pub.ShareToken == "" { + t.Fatalf("public: %+v", pub) + } + un, err := s.CreateList(ctx, List{Title: "Un", Category: "movie", MaxItems: 5, Visibility: VisibilityUnlisted}) + if err != nil { + t.Fatal(err) + } + if un.Visible || un.SharePath() != "/s/"+un.ShareToken || un.ShareToken == pub.ShareToken { + t.Fatalf("unlisted: %+v", un) + } + if _, err := s.CreateList(ctx, List{Title: "X", Category: "movie", MaxItems: 5, Visibility: "secret"}); err == nil { + t.Fatal("bad visibility accepted") + } + got, err := s.ListByShareToken(ctx, un.ShareToken) + if err != nil || got.ID != un.ID { + t.Fatalf("by token: %v %+v", err, got) + } + lists, _ := s.Lists(ctx, false) + if len(lists) != 1 || lists[0].ID != pub.ID { + t.Fatalf("home lists: %+v", lists) + } + old := un.ShareToken + un, err = s.ResetShareToken(ctx, un.ID) + if err != nil || un.ShareToken == old { + t.Fatalf("reset: %v %q", err, un.ShareToken) + } + if _, err := s.ListByShareToken(ctx, old); err != ErrNotFound { + t.Fatalf("old token still works: %v", err) + } + un.Visibility = VisibilityPrivate + if un, err = s.UpdateList(ctx, un); err != nil || un.SharePath() != "" { + t.Fatalf("private: %v %+v", err, un) + } +} diff --git a/web/static/css/app.css b/web/static/css/app.css index 2d1417e..335327a 100644 --- a/web/static/css/app.css +++ b/web/static/css/app.css @@ -156,9 +156,7 @@ code { font: 0.9em ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; bac .avatar--lg { width: 92px; height: 92px; font-size: 36px; } } -.jump { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 6px; margin-bottom: 8px; scrollbar-width: none; } -.jump::-webkit-scrollbar { display: none; } -@media (max-width: 640px) { .jump { justify-content: flex-start; } } +.jump { display: flex; flex-wrap: wrap; gap: 8px; padding-bottom: 6px; margin-bottom: 8px; } .shelf { margin-top: 44px; } .shelf-head { display: flex; align-items: center; gap: 14px; margin-bottom: 18px; } @@ -441,7 +439,7 @@ code { font: 0.9em ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; bac .list-title { font-size: clamp(30px, 5vw, 52px); font-weight: 800; margin-top: 8px; } .list-desc { color: var(--muted); font-size: 16px; margin-top: 10px; max-width: 70ch; } .list-meta { display: flex; align-items: center; gap: 10px; margin-top: 14px; font-size: 14px; font-weight: 550; } -.list-actions { display: flex; align-items: center; gap: 10px; } +.list-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } .list-body { padding-top: 30px; } .segmented { display: inline-flex; padding: 3px; gap: 2px; border-radius: calc(var(--radius) + 2px); background: var(--surface); border: 1px solid var(--border); } @@ -857,6 +855,7 @@ input[type="checkbox"] { accent-color: var(--accent); width: 18px; height: 18px; .radio-cards label { display: flex; align-items: center; gap: 8px; padding: 8px 12px; border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: 14px; } .radio-cards label:has(input:checked) { border-color: var(--accent); background: var(--accent-soft); } .radio-cards input { accent-color: var(--accent); margin: 0; } +.radio-cards label .icon { width: 15px; height: 15px; color: var(--muted); } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } diff --git a/web/static/js/admin-list.js b/web/static/js/admin-list.js index c9af532..dda2232 100644 --- a/web/static/js/admin-list.js +++ b/web/static/js/admin-list.js @@ -3,6 +3,7 @@ import { h, icon, api, readBoot, toast, confirmDialog, chooseDialog, openDialog, import { sortable } from "./sortable.js"; import { Places } from "./places.js"; import { openListForm } from "./list-form.js"; +import { shareDialog, VISIBILITY, visibilityOf } from "./share.js"; import { previewButton } from "./player.js"; import { openImport } from "./import.js"; @@ -40,7 +41,8 @@ function renderHeader() { document.querySelector("[data-bind=title]").textContent = list.title; document.querySelector("[data-bind=count]").textContent = fmt.format(list.itemCount); document.querySelector("[data-bind=max]").textContent = fmt.format(list.maxItems); - document.querySelector("[data-bind=hidden]").textContent = list.visible ? "" : " · Hidden"; + const vis = visibilityOf(list); + document.querySelector("[data-bind=hidden]").textContent = vis === "public" ? "" : ` · ${VISIBILITY[vis].label}`; document.querySelector("[data-bind=public]").href = `/l/${list.slug}`; document.querySelector("[data-bind=export-csv]").href = `/l/${list.slug}/export?format=csv`; document.querySelector("[data-bind=export-txt]").href = `/l/${list.slug}/export?format=txt`; @@ -51,6 +53,10 @@ function renderHeader() { const isFull = () => list.itemCount >= list.maxItems; +document.querySelector("[data-action=share]").addEventListener("click", () => { + shareDialog(list, { onChange: (saved) => { list = saved; renderHeader(); } }); +}); + document.querySelector("[data-action=edit-list]").addEventListener("click", () => { openListForm({ categories, limits, styles: boot.styles, list, diff --git a/web/static/js/admin-lists.js b/web/static/js/admin-lists.js index 2b17fe4..dbe4180 100644 --- a/web/static/js/admin-lists.js +++ b/web/static/js/admin-lists.js @@ -1,5 +1,6 @@ // Admin dashboard: all lists, their order, create/edit/delete. import { h, icon, api, readBoot, toast, confirmDialog, fmt } from "./common.js"; +import { shareDialog, VISIBILITY, visibilityOf } from "./share.js"; import { sortable } from "./sortable.js"; import { openListForm } from "./list-form.js"; @@ -67,12 +68,14 @@ function card(list) { h("span", { "aria-hidden": "true" }, "·"), h("span", {}, `${fmt.format(list.itemCount)} / ${fmt.format(list.maxItems)}`), h("span", { class: "list-card-bar", "aria-hidden": "true" }, h("span", { style: { width: pct + "%" } })), - !list.visible && h("span", { class: "badge badge--muted" }, icon("eye-off"), "Hidden"), + visibilityOf(list) !== "public" && h("span", { class: "badge badge--muted" }, icon(VISIBILITY[visibilityOf(list)].icon), VISIBILITY[visibilityOf(list)].label), ), ), ), h("div", { class: "list-card-actions" }, - h("a", { class: "icon-btn", href: `/l/${list.slug}`, title: "View public page", "aria-label": "View public page" }, icon("external")), + h("a", { class: "icon-btn", href: `/l/${list.slug}`, title: "View page", "aria-label": "View page" }, icon("external")), + h("button", { type: "button", class: "icon-btn", title: "Share", "aria-label": `Share ${list.title}`, + onclick: () => shareDialog(list, { onChange: (saved) => { lists = lists.map((l) => (l.id === saved.id ? saved : l)); render(); } }) }, icon("link")), h("button", { type: "button", class: "icon-btn", title: "List settings", "aria-label": "List settings", onclick: () => editList(list) }, icon("settings")), h("button", { type: "button", class: "icon-btn icon-btn--danger", title: "Delete", "aria-label": "Delete list", onclick: () => deleteList(list) }, icon("trash")), ), diff --git a/web/static/js/list-form.js b/web/static/js/list-form.js index f8af0ea..d9f8da6 100644 --- a/web/static/js/list-form.js +++ b/web/static/js/list-form.js @@ -1,5 +1,6 @@ // Create / edit list dialog, shared by the dashboard and the list editor. import { h, icon, api, openDialog, dialogHead, busy, fmt } from "./common.js"; +import { VISIBILITY, visibilityOf } from "./share.js"; const SIZE_PRESETS = [5, 10, 25, 50, 100]; @@ -91,7 +92,16 @@ export function openListForm({ categories, limits, styles, list, category, onSav h("label", {}, h("input", { type: "radio", name: "art", value: "square", checked: art === "square" }), "Square (logos, covers)"), h("label", {}, h("input", { type: "radio", name: "art", value: "poster", checked: art === "poster" }), "Tall (posters, photos)"), )); - const visible = h("input", { type: "checkbox", name: "visible", checked: list ? list.visible : true }); + const vis = list ? visibilityOf(list) : "public"; + const visHint = h("span", { class: "field-hint" }, VISIBILITY[vis].hint); + const visField = h("div", { class: "field" }, + h("span", { class: "field-label" }, "Who can see it"), + h("div", { class: "radio-cards", role: "radiogroup", "aria-label": "Who can see it" }, + Object.entries(VISIBILITY).map(([key, o]) => h("label", {}, + h("input", { type: "radio", name: "visibility", value: key, checked: vis === key, + onchange: () => { visHint.textContent = o.hint; } }), + icon(o.icon), o.label))), + visHint); const error = h("p", { class: "alert alert--error", role: "alert", hidden: true }); const save = h("button", { type: "submit", class: "btn btn--primary" }, editing ? "Save changes" : "Create list"); @@ -110,7 +120,7 @@ export function openListForm({ categories, limits, styles, list, category, onSav h("div", { class: "field" }, h("span", { class: "field-label" }, "Style"), layoutGroup, h("span", { class: "field-hint" }, "How the list looks on your page. Visitors can switch styles on the list's own page.")), artField, - h("label", { class: "check" }, visible, "Show this list on my public page"), + visField, error, ), h("div", { class: "dialog-foot" }, @@ -140,7 +150,7 @@ export function openListForm({ categories, limits, styles, list, category, onSav maxItems: n, description: desc.value, layout: form.querySelector("input[name=layout]:checked").value, - visible: visible.checked, + visibility: form.querySelector("input[name=visibility]:checked").value, art: isCustom() ? form.querySelector("input[name=art]:checked").value : "", }; if (editing) body.slug = slug.value; diff --git a/web/static/js/public.js b/web/static/js/public.js index 6860796..2e5aa06 100644 --- a/web/static/js/public.js +++ b/web/static/js/public.js @@ -1,6 +1,7 @@ // Public pages: item detail dialog and grid/list toggle. import { h, icon, openDialog } from "./common.js"; import { previewButton } from "./player.js"; +import { quickShare } from "./share.js"; // Each ranked list on the page ships its items as JSON next to the markup. const lists = [...document.querySelectorAll("[data-items]")].map((el) => ({ @@ -79,3 +80,9 @@ document.addEventListener("click", (e) => { const found = findItem(Number(btn.dataset.item)); if (found) show(found.list, found.idx); }); + +// Share button on a list page. +document.querySelector("[data-share]")?.addEventListener("click", (e) => { + const btn = e.currentTarget; + quickShare(new URL(btn.dataset.share, location.origin).href, btn.dataset.shareTitle); +}); diff --git a/web/static/js/share.js b/web/static/js/share.js new file mode 100644 index 0000000..7b07829 --- /dev/null +++ b/web/static/js/share.js @@ -0,0 +1,96 @@ +// Sharing a list: copy its link, or hand it to the system share sheet. +import { h, icon, api, toast, openDialog, dialogHead, confirmDialog, busy } from "./common.js"; + +export const VISIBILITY = { + public: { label: "Public", icon: "external", hint: "On your page, and anyone with the link can see it." }, + unlisted: { label: "Unlisted", icon: "link", hint: "Hidden from your page. Only people you send the link to can see it." }, + private: { label: "Private", icon: "lock", hint: "Only you can see it." }, +}; + +export function visibilityOf(list) { + return list.visibility || (list.visible ? "public" : "private"); +} + +export function shareURL(list) { + const v = visibilityOf(list); + if (v === "public") return new URL(`/l/${list.slug}`, location.origin).href; + if (v === "unlisted" && list.shareToken) return new URL(`/s/${list.shareToken}`, location.origin).href; + return ""; +} + +async function copy(url, input) { + try { + await navigator.clipboard.writeText(url); + toast("Link copied"); + } catch { + // Clipboard needs HTTPS; fall back to selecting the text. + input?.select(); + toast("Press Ctrl+C to copy the link"); + } +} + +const canNativeShare = () => typeof navigator.share === "function" && matchMedia("(pointer: coarse)").matches; + +/** Visitor share: native sheet on phones, copy elsewhere. */ +export async function quickShare(url, title) { + if (canNativeShare()) { + try { await navigator.share({ title, url }); return; } catch (e) { if (e.name === "AbortError") return; } + } + await copy(url); +} + +/** Owner share dialog. onChange gets the updated list after a link reset. */ +export function shareDialog(list, { onChange } = {}) { + let dlg; + const v = visibilityOf(list); + const body = h("div", { class: "dialog-body stack" }); + const draw = () => { + const url = shareURL(list); + if (!url) { + body.replaceChildren(h("p", {}, "This list is private, so there's nothing to send yet. Set it to public or unlisted in List settings first.")); + return; + } + const input = h("input", { type: "text", readonly: true, value: url, onfocus: (e) => e.target.select() }); + const copyBtn = h("button", { type: "button", class: "btn btn--primary", onclick: () => copy(url, input) }, icon("link"), "Copy"); + const parts = [ + h("p", { class: "muted" }, VISIBILITY[v].hint), + h("div", { class: "input-group" }, input, copyBtn), + ]; + if (typeof navigator.share === "function") { + parts.push(h("button", { type: "button", class: "btn", onclick: () => quickShare(url, list.title) }, icon("external"), "Share…")); + } + if (v === "unlisted") { + const reset = h("button", { type: "button", class: "btn btn--ghost" }, icon("refresh"), "Make a new link"); + reset.addEventListener("click", async () => { + const ok = await confirmDialog({ + title: "Make a new link?", + message: "The current link will stop working for anyone you've sent it to.", + confirm: "Make new link", + danger: true, + }); + if (!ok) return; + busy(reset, true); + try { + list = await api("POST", `/api/lists/${list.id}/share-link`); + onChange?.(list); + draw(); + toast("New link made"); + } catch (err) { + toast(err.message, { error: true }); + } finally { + busy(reset, false); + } + }); + parts.push(h("div", {}, reset, h("p", { class: "field-hint" }, "Use this if the link got passed around further than you wanted."))); + } + body.replaceChildren(...parts); + }; + draw(); + const content = h("div", {}, + dialogHead(`Share “${list.title}”`, () => dlg), + body, + h("div", { class: "dialog-foot" }, h("button", { type: "button", class: "btn", onclick: () => dlg.close() }, "Done")), + ); + dlg = openDialog(content); + return dlg; +} diff --git a/web/templates/pages/admin_list.html b/web/templates/pages/admin_list.html index b1f24e5..7d052f3 100644 --- a/web/templates/pages/admin_list.html +++ b/web/templates/pages/admin_list.html @@ -8,11 +8,12 @@ {{icon $c.Icon}}

{{.Data.List.Title}}

-

{{.Data.List.ItemCount}} of {{.Data.List.MaxItems}} · {{$c.Label}}{{if not .Data.List.Visible}} · Hidden{{end}}

+

{{.Data.List.ItemCount}} of {{.Data.List.MaxItems}} · {{$c.Label}}{{if eq .Data.List.Visibility "unlisted"}} · Unlisted{{else if eq .Data.List.Visibility "private"}} · Private{{end}}

{{icon "external"}}View + {{template "export" .Data.List.Slug}} {{if ne $c.Key "custom"}}{{end}} diff --git a/web/templates/pages/list.html b/web/templates/pages/list.html index 06eb5f6..5ce287f 100644 --- a/web/templates/pages/list.html +++ b/web/templates/pages/list.html @@ -12,10 +12,11 @@ {{with .List.Description}}

{{.}}

{{end}}

{{num .List.ItemCount}} {{plural .List.ItemCount "entry" "entries"}}{{if lt .List.ItemCount .List.MaxItems}} of {{num .List.MaxItems}}{{end}} - {{if not .List.Visible}}{{icon "eye-off"}}Hidden{{end}} + {{if eq .List.Visibility "unlisted"}}{{icon "link"}}Unlisted{{else if eq .List.Visibility "private"}}{{icon "lock"}}Private{{end}}

+ {{with .List.SharePath}}{{end}} {{if $.LoggedIn}}{{icon "pencil"}}Edit{{if .Items}}{{template "export" .List.Slug}}{{end}}{{end}} {{if .Items}}