favoritter/web/static/js/app.js
Ole-Morten Duesund 1260cfd18f feat: add PWA support with Android share intent
Make Favoritter installable as a Progressive Web App with offline
static asset caching and Web Share Target API for Android.

New files:
- internal/handler/pwa.go: handlers for manifest, service worker,
  and share target
- web/static/sw.js: service worker (cache-first static, network-first
  HTML) with {{BASE_PATH}} placeholder for subpath deployments
- web/static/icons/: placeholder PWA icons (192, 512, 512-maskable)

Key design decisions:
- Share target uses GET (not POST) to avoid CSRF token issues — Android
  apps cannot provide CSRF tokens
- Manifest is generated dynamically to inject BasePath into start_url,
  scope, icon paths, and share_target action
- Service worker served at /sw.js with Cache-Control: no-cache and
  BasePath injected via string replacement
- handleShare extracts URLs from Android's "text" field as fallback
  (many apps put the URL there instead of "url")
- handleFaveNew replaced with handleFaveNewPreFill that reads url,
  description, notes from query params (enables share + bookmarklets)
- SW registration in app.js reads base-path from <meta> tag (CSP-safe)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 10:06:18 +02:00

198 lines
6.9 KiB
JavaScript

// Favoritter — minimal JavaScript for HTMX configuration and form helpers.
// SPDX-License-Identifier: AGPL-3.0-or-later
(function () {
"use strict";
// Auto-include the CSRF token in all HTMX requests.
document.body.addEventListener("htmx:configRequest", function (event) {
var csrfCookie = getCookie("csrf_token");
if (csrfCookie) {
event.detail.headers["X-CSRF-Token"] = csrfCookie;
}
// For the tag search input, send the current value of the last
// comma-separated segment as the 'q' parameter.
var elt = event.detail.elt;
if (elt && elt.id === "tags") {
var val = elt.value;
var parts = val.split(",");
var lastPart = parts[parts.length - 1].trim();
event.detail.parameters["q"] = lastPart;
}
});
// Update aria-expanded and announce suggestion count after HTMX swaps.
document.body.addEventListener("htmx:afterSwap", function (event) {
var target = event.detail.target;
if (!target) return;
// Focus management: if swapped content has autofocus, focus it.
var autoFocus = target.querySelector("[autofocus]");
if (autoFocus) {
autoFocus.focus();
}
// Tag suggestions: update combobox state.
if (target.id === "tag-suggestions") {
var input = document.getElementById("tags");
var items = target.querySelectorAll("[role='option']");
var count = items.length;
if (input) {
input.setAttribute("aria-expanded", count > 0 ? "true" : "false");
}
// Announce suggestion count to screen readers.
var status = document.getElementById("tag-status");
if (status) {
status.textContent = count > 0
? count + " forslag tilgjengelig"
: "Ingen forslag";
}
// Reset active descendant tracking.
activeIndex = -1;
clearActiveDescendant();
}
});
// After a successful HTMX DELETE, redirect if the element has a data-redirect.
document.body.addEventListener("htmx:afterRequest", function (event) {
if (event.detail.successful && event.detail.verb === "delete") {
var redirect = event.detail.elt.getAttribute("data-redirect");
if (redirect) {
window.location.href = redirect;
}
}
});
// --- Tag autocomplete combobox pattern ---
var activeIndex = -1;
// Delegated event handler for tag suggestion selection.
// Uses mousedown (not click) to fire before blur removes the element.
// Uses touchend for mobile support. Both prevent default to keep
// the tags input focused. Inline handlers (onclick/onmousedown) are
// blocked by CSP script-src 'self', so we must use addEventListener.
document.addEventListener("mousedown", function (event) {
var li = event.target.closest("[data-tag-name]");
if (li) {
event.preventDefault();
addTag(null, li.getAttribute("data-tag-name"));
}
});
document.addEventListener("touchend", function (event) {
var li = event.target.closest("[data-tag-name]");
if (li) {
event.preventDefault();
addTag(null, li.getAttribute("data-tag-name"));
}
});
// Handle keyboard navigation in the tag suggestions listbox.
document.addEventListener("keydown", function (event) {
var input = document.getElementById("tags");
if (!input || document.activeElement !== input) return;
var listbox = document.getElementById("tag-suggestions");
if (!listbox) return;
var items = listbox.querySelectorAll("[role='option']");
if (items.length === 0) return;
switch (event.key) {
case "ArrowDown":
event.preventDefault();
activeIndex = Math.min(activeIndex + 1, items.length - 1);
setActiveDescendant(items);
break;
case "ArrowUp":
event.preventDefault();
// Allow arrowing back to -1 to deselect all options.
activeIndex = Math.max(activeIndex - 1, -1);
if (activeIndex === -1) {
clearActiveDescendant();
clearAriaSelected(items);
} else {
setActiveDescendant(items);
}
break;
case "Enter":
if (activeIndex >= 0 && activeIndex < items.length) {
event.preventDefault();
addTag(null, items[activeIndex].textContent.trim());
}
break;
case "Escape":
closeSuggestions();
break;
}
});
function setActiveDescendant(items) {
for (var i = 0; i < items.length; i++) {
items[i].setAttribute("aria-selected", i === activeIndex ? "true" : "false");
}
var input = document.getElementById("tags");
if (input && activeIndex >= 0) {
var activeItem = items[activeIndex];
if (!activeItem.id) {
activeItem.id = "tag-option-" + activeIndex;
}
input.setAttribute("aria-activedescendant", activeItem.id);
activeItem.scrollIntoView({ block: "nearest" });
}
}
function clearActiveDescendant() {
var input = document.getElementById("tags");
if (input) {
input.removeAttribute("aria-activedescendant");
}
}
function clearAriaSelected(items) {
for (var i = 0; i < items.length; i++) {
items[i].setAttribute("aria-selected", "false");
}
}
function closeSuggestions() {
var listbox = document.getElementById("tag-suggestions");
if (listbox) {
while (listbox.firstChild) {
listbox.removeChild(listbox.firstChild);
}
}
var input = document.getElementById("tags");
if (input) {
input.setAttribute("aria-expanded", "false");
}
activeIndex = -1;
}
// Add a selected tag to the tag input.
function addTag(element, tagName) {
var input = document.getElementById("tags");
if (!input) return;
var parts = input.value.split(",").map(function (s) { return s.trim(); });
parts[parts.length - 1] = tagName;
input.value = parts.join(", ") + ", ";
input.focus();
closeSuggestions();
}
function getCookie(name) {
var match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
return match ? match[2] : null;
}
// Register service worker for PWA support.
if ("serviceWorker" in navigator) {
var baseMeta = document.querySelector('meta[name="base-path"]');
var base = baseMeta ? baseMeta.getAttribute("content") : "";
navigator.serviceWorker.register(base + "/sw.js", { scope: base + "/" });
}
})();