|
| 1 | +import { authentication, functionProvider } from "@modular-rest/client"; |
| 2 | +import { normaliseSourceUrl } from "../helper/url-normalise"; |
| 3 | +import type { BundleSuggestion } from "../../console-crane/modules/word-detail/types"; |
| 4 | + |
| 5 | +/** |
| 6 | + * Per-page bundle suggestion: which bundle the save modal should default to for |
| 7 | + * the current page + logged-in user. Called once per page (first word-detail |
| 8 | + * open) and cached client-side by normalised URL so repeated word lookups on |
| 9 | + * the same page reuse the result. |
| 10 | + */ |
| 11 | +export class BundleSuggestionService { |
| 12 | + static instance = new BundleSuggestionService(); |
| 13 | + |
| 14 | + // Cache of in-flight / resolved suggestions keyed by normalised URL. |
| 15 | + private cache = new Map<string, Promise<BundleSuggestion>>(); |
| 16 | + |
| 17 | + /** Clear the cache (e.g. after a save creates a new bundle for this page). */ |
| 18 | + clear(url?: string) { |
| 19 | + if (url) this.cache.delete(normaliseSourceUrl(url)); |
| 20 | + else this.cache.clear(); |
| 21 | + } |
| 22 | + |
| 23 | + async getForCurrentPage(): Promise<BundleSuggestion> { |
| 24 | + const empty: BundleSuggestion = { matchedBundle: null, suggestedName: null }; |
| 25 | + |
| 26 | + // Logged-in only; anonymous users get nothing to suggest. |
| 27 | + if (!authentication.user?.id) return empty; |
| 28 | + if (typeof location === "undefined") return empty; |
| 29 | + |
| 30 | + const key = normaliseSourceUrl(location.href); |
| 31 | + if (!key) return empty; |
| 32 | + |
| 33 | + const cached = this.cache.get(key); |
| 34 | + if (cached) return cached; |
| 35 | + |
| 36 | + const pageTitle = typeof document !== "undefined" ? document.title : ""; |
| 37 | + const request = functionProvider |
| 38 | + .run<BundleSuggestion>({ |
| 39 | + name: "getBundleSuggestionForPage", |
| 40 | + args: { |
| 41 | + refId: authentication.user?.id, |
| 42 | + pageTitle, |
| 43 | + pageUrl: location.href, |
| 44 | + }, |
| 45 | + }) |
| 46 | + .catch((error) => { |
| 47 | + // Best-effort; never block the save flow. |
| 48 | + console.error("Bundle suggestion error:", error); |
| 49 | + this.cache.delete(key); |
| 50 | + return empty; |
| 51 | + }); |
| 52 | + |
| 53 | + this.cache.set(key, request); |
| 54 | + return request; |
| 55 | + } |
| 56 | +} |
0 commit comments