@mushi-mushi/web 1.14.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createLogger, noopLogger, createApiClient, createPreFilter, createOfflineQueue, createRateLimiter, createPiiScrubber, createBreadcrumbBuffer, getReporterToken, getDeviceFingerprintHash, MAX_SCREENSHOT_DATA_URL_BYTES, getSessionId, captureEnvironment, newUuid, DEFAULT_API_ENDPOINT, MUSHI_INTERNAL_INIT_MARKER, MUSHI_INTERNAL_HEADER, normaliseThrown } from '@mushi-mushi/core';
1
+ import { resolveEnvConfig, createLogger, noopLogger, createApiClient, createPreFilter, createOfflineQueue, createRateLimiter, createPiiScrubber, createBreadcrumbBuffer, getReporterToken, getDeviceFingerprintHash, MAX_SCREENSHOT_DATA_URL_BYTES, getSessionId, captureEnvironment, newUuid, DEFAULT_API_ENDPOINT, MUSHI_INTERNAL_INIT_MARKER, MUSHI_INTERNAL_HEADER, parseIdentityToken, normaliseThrown } from '@mushi-mushi/core';
2
2
 
3
3
  // src/capture/compress-screenshot.ts
4
4
  async function compressScreenshotDataUrl(dataUrl, maxBytes = MAX_SCREENSHOT_DATA_URL_BYTES) {
@@ -291,6 +291,9 @@ function getAvailableLocales() {
291
291
  // src/styles.ts
292
292
  function getWidgetStyles(theme, accent = "", accentText = "") {
293
293
  const isDark = theme === "dark";
294
+ const safeHex = (v) => /^#[0-9a-fA-F]{3,8}$/.test(v) ? v : "";
295
+ const safeAccent = safeHex(accent);
296
+ const safeAccentText = safeHex(accentText);
294
297
  const paper = isDark ? "#0F0E0C" : "#F8F4ED";
295
298
  const ink = isDark ? "#F2EBDD" : "#0E0D0B";
296
299
  const inkMuted = isDark ? "#928B7E" : "#5C5852";
@@ -298,9 +301,9 @@ function getWidgetStyles(theme, accent = "", accentText = "") {
298
301
  const inkDim = isDark ? "#7A7268" : "#6E6760";
299
302
  const rule = isDark ? "rgba(242,235,221,0.10)" : "rgba(14,13,11,0.10)";
300
303
  const ruleStrong = isDark ? "rgba(242,235,221,0.18)" : "rgba(14,13,11,0.16)";
301
- const widgetAccent = accent || (isDark ? "#FF5A47" : "#E03C2C");
304
+ const widgetAccent = safeAccent || (isDark ? "#FF5A47" : "#E03C2C");
302
305
  const widgetAccentWash = isDark ? `${widgetAccent}1F` : `${widgetAccent}14`;
303
- const widgetAccentInk = accentText || (isDark ? "#FFE5E0" : "#7A1F15");
306
+ const widgetAccentInk = safeAccentText || (isDark ? "#FFE5E0" : "#7A1F15");
304
307
  const fontDisplay = `'Iowan Old Style', 'Palatino Linotype', 'Palatino', 'Book Antiqua', 'Cambria', Georgia, 'Times New Roman', serif`;
305
308
  const fontBody = `system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI Variable Display', 'Segoe UI', sans-serif`;
306
309
  const fontMono = `ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, Consolas, 'Liberation Mono', monospace`;
@@ -476,8 +479,8 @@ function getWidgetStyles(theme, accent = "", accentText = "") {
476
479
 
477
480
  @keyframes mushi-pulse {
478
481
  0% { box-shadow: 0 0 0 0 ${widgetAccent}; opacity: 1; }
479
- 70% { box-shadow: 0 0 0 8px rgba(224,60,44,0); opacity: 0.5; }
480
- 100% { box-shadow: 0 0 0 0 rgba(224,60,44,0); opacity: 1; }
482
+ 70% { box-shadow: 0 0 0 8px ${widgetAccent}00; opacity: 0.5; }
483
+ 100% { box-shadow: 0 0 0 0 ${widgetAccent}00; opacity: 1; }
481
484
  }
482
485
 
483
486
  .mushi-panel {
@@ -1623,12 +1626,18 @@ function getWidgetStyles(theme, accent = "", accentText = "") {
1623
1626
  position: fixed;
1624
1627
  left: 0;
1625
1628
  right: 0;
1626
- height: 36px;
1629
+ /* min-height (not fixed height) + border-box so the safe-area padding
1630
+ below extends the bar into the notch/home-indicator zone instead of
1631
+ letting content bleed under the status bar (mobile safe-area bleed
1632
+ fix \u2014 Workstream C). Horizontal padding also clears the left/right
1633
+ insets for landscape notches. */
1634
+ box-sizing: border-box;
1635
+ min-height: 36px;
1627
1636
  display: flex;
1628
1637
  align-items: center;
1629
1638
  justify-content: center;
1630
1639
  gap: 10px;
1631
- padding: 0 16px;
1640
+ padding: 0 calc(16px + env(safe-area-inset-right, 0px)) 0 calc(16px + env(safe-area-inset-left, 0px));
1632
1641
  font-family: ${fontMono};
1633
1642
  font-size: 12px;
1634
1643
  letter-spacing: 0.04em;
@@ -1638,8 +1647,8 @@ function getWidgetStyles(theme, accent = "", accentText = "") {
1638
1647
  animation: mushi-banner-slide-in 0.3s ${easeStamp} both;
1639
1648
  }
1640
1649
 
1641
- .mushi-banner.top { top: 0; }
1642
- .mushi-banner.bottom { bottom: 0; }
1650
+ .mushi-banner.top { top: 0; padding-top: env(safe-area-inset-top, 0px); }
1651
+ .mushi-banner.bottom { bottom: 0; padding-bottom: env(safe-area-inset-bottom, 0px); }
1643
1652
 
1644
1653
  /* --- neon variant (electric lime \u2014 dev / beta tool aesthetic) --- */
1645
1654
  .mushi-banner.neon {
@@ -1891,10 +1900,35 @@ function getWidgetStyles(theme, accent = "", accentText = "") {
1891
1900
  .mushi-xapp-app-name{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;margin:0 0 6px}
1892
1901
  .mushi-xapp-group{margin-bottom:14px}
1893
1902
  .mushi-label{display:block;font-weight:600;margin-bottom:6px}
1903
+
1904
+ /* \u2500\u2500 Assistant tab (P5) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
1905
+ .mushi-assistant{display:flex;flex-direction:column;height:100%;min-height:0;max-height:60vh}
1906
+ .mushi-assistant-log{flex:1;min-height:120px;overflow-y:auto;display:flex;flex-direction:column;gap:8px;padding:4px 2px 8px}
1907
+ .mushi-assistant-greeting{font:400 14px/1.5 ${fontBody};color:${inkMuted};padding:6px 2px}
1908
+ .mushi-assistant-suggestions{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px}
1909
+ .mushi-assistant-chip{background:${widgetAccentWash};color:${widgetAccentInk};border:1px solid ${ruleStrong};border-radius:999px;padding:5px 12px;font-size:12px;cursor:pointer;font-family:${fontBody};transition:background .15s}
1910
+ .mushi-assistant-chip:hover{background:${isDark ? "rgba(255,90,71,0.22)" : "rgba(224,60,44,0.14)"}}
1911
+ .mushi-assistant-chip:focus-visible{outline:2px solid ${widgetAccent};outline-offset:2px}
1912
+ .mushi-assistant-msg{max-width:85%;padding:8px 12px;border-radius:12px;font:400 14px/1.45 ${fontBody};white-space:pre-wrap;word-break:break-word}
1913
+ .mushi-assistant-msg-user{align-self:flex-end;background:${widgetAccent};color:#fff;border-bottom-right-radius:4px}
1914
+ .mushi-assistant-msg-bot{align-self:flex-start;background:${isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.05)"};color:${ink};border-bottom-left-radius:4px}
1915
+ .mushi-assistant-thinking{opacity:0.6;font-size:18px;letter-spacing:2px}
1916
+ .mushi-assistant-error{align-self:flex-start;color:${isDark ? "#F87171" : "#DC2626"};font-size:12px;padding:4px 2px}
1917
+ .mushi-assistant-form{display:flex;align-items:flex-end;gap:8px;border-top:1px solid ${rule};padding-top:8px}
1918
+ .mushi-assistant-input{flex:1;resize:none;max-height:120px;border:1px solid ${ruleStrong};border-radius:10px;padding:8px 12px;font:400 14px/1.4 ${fontBody};background:${paper};color:${ink}}
1919
+ .mushi-assistant-input:focus-visible{outline:2px solid ${widgetAccent};outline-offset:1px}
1920
+ .mushi-assistant-submit{flex-shrink:0;width:36px;height:36px;border:none;border-radius:50%;background:${widgetAccent};color:#fff;font-size:18px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:transform .15s,opacity .15s}
1921
+ .mushi-assistant-submit:hover{transform:translateY(-1px)}
1922
+ .mushi-assistant-submit:disabled{opacity:0.5;cursor:default;transform:none}
1923
+ .mushi-assistant-submit:focus-visible{outline:2px solid ${widgetAccent};outline-offset:2px}
1894
1924
  `;
1895
1925
  }
1896
1926
 
1897
- // src/widget.ts
1927
+ // src/version.ts
1928
+ var MUSHI_SDK_PACKAGE = "@mushi-mushi/web";
1929
+ var MUSHI_SDK_VERSION = "1.16.0" ;
1930
+
1931
+ // src/widget-helpers.ts
1898
1932
  var CATEGORY_ICONS = {
1899
1933
  bug: "\u26A0\uFE0F",
1900
1934
  slow: "\u{1F40C}",
@@ -2014,1735 +2048,1874 @@ function isSubmitShortcut(e) {
2014
2048
  function escapeHtml(value) {
2015
2049
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2016
2050
  }
2017
- var MushiWidget = class _MushiWidget {
2018
- constructor(config = {}, callbacks, sdkVersion = "0.7.0") {
2019
- this.sdkVersion = sdkVersion;
2020
- this.config = {
2021
- position: config.position ?? "bottom-right",
2022
- anchor: config.anchor ?? {},
2023
- theme: config.theme ?? "auto",
2024
- // Falsy-OR (NOT `??`) on purpose: `triggerText: ''` is semantically
2025
- // nonsense — it would render a labelless, glyphless trigger button
2026
- // that users can't see or aim at. Treat empty string the same as
2027
- // omitted so any caller that wires this to a cleared form input or
2028
- // pastes a legacy snippet that emitted `triggerText: ""` (see
2029
- // apps/admin/src/lib/sdkSnippets.ts widgetLines history) still gets
2030
- // the default 🐛 and a visible button.
2031
- triggerText: config.triggerText || "\u{1F41B}",
2032
- expandedTitle: config.expandedTitle ?? "",
2033
- mode: config.mode ?? "conversational",
2034
- locale: config.locale ?? "auto",
2035
- zIndex: config.zIndex ?? 99999,
2036
- trigger: config.trigger ?? "auto",
2037
- bannerConfig: config.bannerConfig ?? {},
2038
- attachToSelector: config.attachToSelector ?? "",
2039
- inset: config.inset ?? {},
2040
- respectSafeArea: config.respectSafeArea ?? true,
2041
- hideOnSelector: config.hideOnSelector ?? "",
2042
- hideOnRoutes: config.hideOnRoutes ?? [],
2043
- environments: config.environments ?? {},
2044
- smartHide: config.smartHide ?? false,
2045
- draggable: config.draggable ?? false,
2046
- brandFooter: config.brandFooter ?? true,
2047
- outdatedBanner: config.outdatedBanner ?? "auto",
2048
- betaMode: config.betaMode ?? {},
2049
- minDescriptionLength: config.minDescriptionLength ?? 20,
2050
- dashboardUrl: config.dashboardUrl ?? "",
2051
- responseSlaLabel: config.responseSlaLabel ?? "",
2052
- featureRequestCard: config.featureRequestCard ?? true,
2053
- featureRequestLabel: config.featureRequestLabel ?? "",
2054
- featureRequestDescription: config.featureRequestDescription ?? "",
2055
- avoidSelectors: config.avoidSelectors ?? [],
2056
- categories: config.categories ?? [],
2057
- accent: config.accent ?? "",
2058
- accentText: config.accentText ?? ""
2059
- };
2060
- this.callbacks = callbacks;
2061
- this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
2062
- this.host = document.createElement("div");
2063
- this.host.id = "mushi-mushi-widget";
2064
- this.shadow = this.host.attachShadow({ mode: "closed" });
2065
- }
2066
- sdkVersion;
2067
- host;
2068
- shadow;
2069
- config;
2070
- callbacks;
2071
- locale;
2072
- isOpen = false;
2073
- step = "category";
2074
- /**
2075
- * The selected category id. May be a built-in `MushiReportCategory` or a
2076
- * custom id from `config.categories`. Cast to `MushiReportCategory` only
2077
- * after resolving through `resolveBaseCategory()`.
2078
- */
2079
- selectedCategory = null;
2080
- selectedIntent = null;
2081
- /**
2082
- * True when the user took the "Feature request" shortcut. We track this
2083
- * separately from `selectedCategory='other'` so the Back button on the
2084
- * details step jumps straight back to the category picker instead of
2085
- * landing on the intent picker the user explicitly skipped.
2086
- */
2087
- viaFeatureRequest = false;
2088
- screenshotAttached = false;
2089
- screenshotCapturing = false;
2090
- screenshotError = false;
2091
- allowScreenshotRemove = true;
2092
- elementSelected = false;
2093
- elementCapturing = false;
2094
- submitting = false;
2095
- /** Hint element injected outside the shadow DOM during element selection. */
2096
- selectorHint = null;
2097
- triggerVisible = true;
2098
- triggerShrunk = false;
2099
- triggerHiddenByScroll = false;
2100
- /** Milliseconds since mount — used for the 30s first-time nudge gate. */
2101
- mountedAt = null;
2102
- nudgeShown = false;
2103
- nudgeEl = null;
2104
- nudgeTimer = null;
2105
- sdkFreshness = null;
2106
- reporterReports = [];
2107
- featureBoard = [];
2108
- reporterComments = [];
2109
- selectedReportId = null;
2110
- reporterLoading = false;
2111
- reporterError = null;
2112
- attachedLaunchers = [];
2113
- smartHideCleanup = null;
2114
- smartHideTimer = null;
2115
- /** Captured at the moment of submit so the success ledger metadata
2116
- * ("REPORT · 14:23:07 JST") doesn't drift while the success step
2117
- * is on screen. */
2118
- submittedAt = null;
2119
- /** Pending success-state + auto-close timers. Tracked so destroy()
2120
- * can clear them — otherwise a host that unmounts mid-submit leaks
2121
- * this MushiWidget reference (and re-renders into a detached shadow
2122
- * root) for up to ~3.3s after destroy. */
2123
- successTimer = null;
2124
- autoCloseTimer = null;
2125
- rewardsState = null;
2126
- leaderboardEntries = null;
2127
- leaderboardLoading = false;
2128
- /** Server-confirmed id for the just-submitted report. Surfaces in
2129
- * the success step as a copyable receipt + optional deep link to
2130
- * the Mushi console (when `dashboardUrl` is configured). Cleared
2131
- * on every new `open()` so a re-opened widget never reuses a
2132
- * stale id from the previous session. */
2133
- lastReportId = null;
2134
- /** True when the just-submitted report was queued offline (no
2135
- * network, or the API errored and went into the retry queue).
2136
- * Drives a different success copy so the user knows the report
2137
- * hasn't actually reached the console yet. */
2138
- lastSubmitQueuedOffline = false;
2139
- /** Whether the user has clicked ✕ on the header banner this session. */
2140
- bannerDismissed = false;
2141
- /** Persisted FAB position when draggable is enabled. */
2142
- fabPos = null;
2143
- /** Cleanup fn for visualViewport keyboard listener. */
2144
- vvCleanup = null;
2145
- /** Mushi tester session JWT — set after in-widget sign-in or by mushi.ts. */
2146
- testerJwt = null;
2147
- /** Tester identity (public_handle, display_name). */
2148
- testerInfo = null;
2149
- /** Cross-app reports for the signed-in tester. */
2150
- crossAppReports = null;
2151
- crossAppLoading = false;
2152
- /** Global leaderboard entries (from mushi_testers, not org-scoped). */
2153
- globalLeaderboard = null;
2154
- globalLeaderboardLoading = false;
2155
- /** Reputation for the signed-in tester. */
2156
- testerReputation = null;
2157
- /** Whether an in-widget magic-link email was just sent. */
2158
- magicLinkSent = false;
2159
- magicLinkEmail = "";
2160
- magicLinkError = "";
2161
- mount() {
2162
- if (this.host.isConnected) return;
2163
- this.syncHostChromeState();
2164
- document.body.appendChild(this.host);
2165
- this.syncAttachedLaunchers();
2166
- this.syncSmartHide();
2167
- this.render();
2168
- this.mountedAt = Date.now();
2169
- }
2170
- getIsMounted() {
2171
- return this.host.isConnected;
2172
- }
2173
- updateConfig(config = {}) {
2174
- this.config = {
2175
- ...this.config,
2176
- ...config.position ? { position: config.position } : {},
2177
- ...config.anchor !== void 0 ? { anchor: config.anchor } : {},
2178
- ...config.theme ? { theme: config.theme } : {},
2179
- ...config.triggerText !== void 0 ? { triggerText: config.triggerText || "\u{1F41B}" } : {},
2180
- ...config.expandedTitle !== void 0 ? { expandedTitle: config.expandedTitle } : {},
2181
- ...config.mode ? { mode: config.mode } : {},
2182
- ...config.locale ? { locale: config.locale } : {},
2183
- ...config.zIndex !== void 0 ? { zIndex: config.zIndex } : {},
2184
- ...config.trigger ? { trigger: config.trigger } : {},
2185
- ...config.attachToSelector !== void 0 ? { attachToSelector: config.attachToSelector } : {},
2186
- ...config.inset !== void 0 ? { inset: config.inset } : {},
2187
- ...config.respectSafeArea !== void 0 ? { respectSafeArea: config.respectSafeArea } : {},
2188
- ...config.hideOnSelector !== void 0 ? { hideOnSelector: config.hideOnSelector } : {},
2189
- ...config.hideOnRoutes !== void 0 ? { hideOnRoutes: config.hideOnRoutes } : {},
2190
- ...config.environments !== void 0 ? { environments: config.environments } : {},
2191
- ...config.smartHide !== void 0 ? { smartHide: config.smartHide } : {},
2192
- ...config.draggable !== void 0 ? { draggable: config.draggable } : {},
2193
- ...config.brandFooter !== void 0 ? { brandFooter: config.brandFooter } : {},
2194
- ...config.outdatedBanner !== void 0 ? { outdatedBanner: config.outdatedBanner } : {},
2195
- ...config.betaMode !== void 0 ? { betaMode: config.betaMode } : {},
2196
- ...config.minDescriptionLength !== void 0 ? { minDescriptionLength: config.minDescriptionLength } : {},
2197
- ...config.dashboardUrl !== void 0 ? { dashboardUrl: config.dashboardUrl } : {},
2198
- ...config.responseSlaLabel !== void 0 ? { responseSlaLabel: config.responseSlaLabel } : {},
2199
- ...config.featureRequestCard !== void 0 ? { featureRequestCard: config.featureRequestCard } : {},
2200
- ...config.featureRequestLabel !== void 0 ? { featureRequestLabel: config.featureRequestLabel } : {},
2201
- ...config.featureRequestDescription !== void 0 ? { featureRequestDescription: config.featureRequestDescription } : {},
2202
- // Runtime/dashboard config delivers bannerMessage/bannerLabel via
2203
- // mergeRuntimeConfig → bannerConfig. The widget is constructed before
2204
- // that fetch resolves, so this pass-through is what makes server-driven
2205
- // banner copy actually render.
2206
- ...config.bannerConfig !== void 0 ? { bannerConfig: config.bannerConfig } : {},
2207
- ...config.categories !== void 0 ? { categories: config.categories } : {}
2208
- };
2209
- this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
2210
- if (this.host.isConnected) this.syncHostChromeState();
2211
- this.syncAttachedLaunchers();
2212
- this.syncSmartHide();
2213
- this.render();
2214
- }
2215
- // ─── Custom category helpers ──────────────────────────────────────────────
2216
- /** Find a custom category entry by id. Returns undefined for built-in ids. */
2217
- resolveCustomCategory(id) {
2218
- return this.config.categories?.find((c) => c.id === id);
2219
- }
2220
- /**
2221
- * Map a (possibly custom) category id to the built-in `MushiReportCategory`
2222
- * used for the report wire format. Falls back to `'other'`.
2223
- */
2224
- resolveBaseCategory(id) {
2225
- const BUILTIN = ["bug", "slow", "visual", "confusing", "other"];
2226
- if (BUILTIN.includes(id)) return id;
2227
- const custom = this.resolveCustomCategory(id);
2228
- return custom?.baseCategory ?? "other";
2229
- }
2230
- /** Icon for the selected category — custom entry's icon or built-in emoji. */
2231
- categoryIcon(id) {
2232
- const custom = this.resolveCustomCategory(id);
2233
- if (custom?.icon) return custom.icon;
2234
- return CATEGORY_ICONS[id] ?? "\u{1F4AC}";
2235
- }
2236
- /** Label for the selected category — custom entry label or built-in i18n string. */
2237
- categoryLabel(id) {
2238
- const custom = this.resolveCustomCategory(id);
2239
- if (custom) return custom.label;
2240
- const t = this.locale;
2241
- return t.step1.categories[id] ?? id;
2051
+
2052
+ // src/widget-render.ts
2053
+ function renderStep(ctx) {
2054
+ switch (ctx.step) {
2055
+ case "category":
2056
+ return renderCategoryStep(ctx);
2057
+ case "intent":
2058
+ return renderIntentStep(ctx);
2059
+ case "details":
2060
+ return renderDetailsStep(ctx);
2061
+ case "success":
2062
+ return renderSuccessStep(ctx);
2063
+ case "reports":
2064
+ return renderReportsStep(ctx);
2065
+ case "report-detail":
2066
+ return renderReportDetailStep(ctx);
2067
+ case "leaderboard":
2068
+ return renderLeaderboardStep(ctx);
2069
+ case "roadmap":
2070
+ return renderRoadmapStep(ctx);
2071
+ case "account":
2072
+ return renderAccountStep(ctx);
2073
+ case "cross-app-reports":
2074
+ return renderCrossAppReportsStep(ctx);
2075
+ case "assistant":
2076
+ return renderAssistantStep(ctx);
2242
2077
  }
2243
- // ─── Open / close ─────────────────────────────────────────────────────────
2244
- open(options) {
2245
- if (this.isOpen) return;
2246
- this.isOpen = true;
2247
- this.screenshotAttached = false;
2248
- this.screenshotCapturing = false;
2249
- this.screenshotError = false;
2250
- this.elementSelected = false;
2251
- this.elementCapturing = false;
2252
- this.submitting = false;
2253
- this.submittedAt = null;
2254
- this.removeSelectorHint();
2255
- this.lastReportId = null;
2256
- this.lastSubmitQueuedOffline = false;
2257
- this.viaFeatureRequest = false;
2258
- if (options?.featureRequest) {
2259
- this.selectedCategory = "other";
2260
- this.selectedIntent = FEATURE_REQUEST_INTENT;
2261
- this.viaFeatureRequest = true;
2262
- this.step = "details";
2263
- } else if (options?.category) {
2264
- this.selectedCategory = options.category;
2265
- this.selectedIntent = null;
2266
- const custom = this.resolveCustomCategory(options.category);
2267
- this.step = custom && (!custom.intents || custom.intents.length === 0) ? "details" : "intent";
2268
- } else {
2269
- this.selectedCategory = null;
2270
- this.selectedIntent = null;
2271
- this.step = "category";
2272
- }
2273
- this.render();
2274
- this.callbacks.onOpen();
2275
- }
2276
- close() {
2277
- if (!this.isOpen) return;
2278
- this.isOpen = false;
2279
- this.render();
2280
- this.callbacks.onClose();
2281
- }
2282
- /**
2283
- * Briefly highlight the trigger button (a soft pulse + tooltip) without
2284
- * opening the full reporter panel. Use for first-session welcome nudges
2285
- * and other "by the way, this exists" prompts where forcing the panel
2286
- * open would feel aggressive. Honours `position: 'none'` (no-op when
2287
- * the trigger button is hidden).
2288
- */
2289
- pulseTrigger() {
2290
- if (this.isOpen) return;
2291
- const trigger = this.shadow.querySelector(".mushi-trigger");
2292
- if (!trigger) return;
2293
- trigger.classList.add("mushi-trigger-pulse");
2294
- window.setTimeout(() => {
2295
- trigger.classList.remove("mushi-trigger-pulse");
2296
- }, 2400);
2297
- }
2298
- getIsOpen() {
2299
- return this.isOpen;
2300
- }
2301
- showTrigger() {
2302
- this.triggerVisible = true;
2303
- this.render();
2304
- }
2305
- hideTrigger() {
2306
- this.triggerVisible = false;
2307
- this.render();
2308
- }
2309
- setTrigger(trigger) {
2310
- this.updateConfig({ trigger });
2311
- }
2312
- attachTo(selectorOrElement, options = {}) {
2313
- const elements = typeof selectorOrElement === "string" ? Array.from(document.querySelectorAll(selectorOrElement)) : [selectorOrElement];
2314
- const cleanups = elements.map((el) => {
2315
- const onClick = (event) => {
2316
- event.preventDefault();
2317
- this.updateConfig(options);
2318
- this.open();
2319
- };
2320
- el.addEventListener("click", onClick);
2321
- return () => el.removeEventListener("click", onClick);
2322
- });
2323
- return () => cleanups.forEach((cleanup) => cleanup());
2324
- }
2325
- setScreenshotAttached(attached) {
2326
- this.screenshotAttached = attached;
2327
- if (this.isOpen) this.render();
2328
- }
2329
- setAllowScreenshotRemove(allow) {
2330
- this.allowScreenshotRemove = allow;
2331
- if (this.isOpen) this.render();
2332
- }
2333
- setElementSelected(selected) {
2334
- this.elementSelected = selected;
2335
- this.elementCapturing = false;
2336
- this.removeSelectorHint();
2337
- if (this.isOpen) this.render();
2338
- }
2339
- setScreenshotCapturing(capturing) {
2340
- this.screenshotCapturing = capturing;
2341
- this.screenshotError = false;
2342
- if (this.isOpen) this.render();
2343
- }
2344
- setScreenshotError(failed) {
2345
- this.screenshotError = failed;
2346
- this.screenshotCapturing = false;
2347
- if (this.isOpen) this.render();
2348
- }
2349
- setElementCapturing(capturing) {
2350
- this.elementCapturing = capturing;
2351
- if (capturing) {
2352
- this.showSelectorHint();
2353
- } else {
2354
- this.removeSelectorHint();
2355
- }
2356
- if (this.isOpen) this.render();
2357
- }
2358
- /** Hide the widget panel (but keep the host element) during element selection
2359
- * so the user can click any element on the page without the panel
2360
- * intercepting the event. */
2361
- hidePanel() {
2362
- const panel = this.shadow.querySelector(".mushi-panel");
2363
- if (panel) panel.style.display = "none";
2364
- }
2365
- showPanel() {
2366
- const panel = this.shadow.querySelector(".mushi-panel");
2367
- if (panel) panel.style.display = "";
2368
- }
2369
- showSelectorHint() {
2370
- this.removeSelectorHint();
2371
- const hint = document.createElement("div");
2372
- hint.id = "mushi-selector-hint";
2373
- hint.setAttribute("role", "status");
2374
- hint.setAttribute("aria-live", "polite");
2375
- hint.style.cssText = `
2376
- position: fixed;
2377
- bottom: 24px;
2378
- left: 50%;
2379
- transform: translateX(-50%);
2380
- z-index: 2147483646;
2381
- background: rgba(17,17,17,0.92);
2382
- color: #fff;
2383
- font-family: ui-monospace, SFMono-Regular, monospace;
2384
- font-size: 12px;
2385
- letter-spacing: 0.04em;
2386
- padding: 8px 16px;
2387
- border-radius: 20px;
2388
- pointer-events: none;
2389
- white-space: nowrap;
2390
- backdrop-filter: blur(4px);
2391
- box-shadow: 0 2px 12px rgba(0,0,0,0.35);
2078
+ }
2079
+ function renderAssistantStep(ctx) {
2080
+ const label = ctx.callbacks.assistantLabel || "Ask";
2081
+ const greeting = ctx.callbacks.assistantGreeting || "Ask me anything about this app.";
2082
+ const suggestions = ctx.callbacks.assistantSuggestions ?? [];
2083
+ const empty = ctx.assistantTurns.length === 0;
2084
+ const transcript = empty ? `<div class="mushi-assistant-greeting">${escapeHtml(greeting)}</div>
2085
+ ${suggestions.length ? `<div class="mushi-assistant-suggestions">${suggestions.map((s) => `<button type="button" class="mushi-assistant-chip" data-action="assistant-suggest" data-value="${escapeHtml(s)}">${escapeHtml(s)}</button>`).join("")}</div>` : ""}` : ctx.assistantTurns.map((turn) => {
2086
+ const cls = turn.role === "user" ? "mushi-assistant-msg-user" : "mushi-assistant-msg-bot";
2087
+ const opts = turn.options && turn.options.length ? `<div class="mushi-assistant-suggestions">${turn.options.map((o) => `<button type="button" class="mushi-assistant-chip" data-action="assistant-suggest" data-value="${escapeHtml(o)}">${escapeHtml(o)}</button>`).join("")}</div>` : "";
2088
+ return `<div class="mushi-assistant-msg ${cls}">${escapeHtml(turn.text)}</div>${opts}`;
2089
+ }).join("");
2090
+ const thinking = ctx.assistantSending ? `<div class="mushi-assistant-msg mushi-assistant-msg-bot mushi-assistant-thinking">\u2026</div>` : "";
2091
+ const error = ctx.assistantError ? `<div class="mushi-assistant-error" role="alert">${escapeHtml(ctx.assistantError)}</div>` : "";
2092
+ return `
2093
+ ${renderHeader(ctx, { title: label, showBack: true })}
2094
+ <div class="mushi-assistant">
2095
+ <div class="mushi-assistant-log">
2096
+ ${transcript}
2097
+ ${thinking}
2098
+ ${error}
2099
+ </div>
2100
+ <form class="mushi-assistant-form" data-action="assistant-send">
2101
+ <textarea
2102
+ class="mushi-assistant-input"
2103
+ rows="1"
2104
+ placeholder="Type your question\u2026"
2105
+ ${ctx.assistantSending ? "disabled" : ""}
2106
+ ></textarea>
2107
+ <button type="submit" class="mushi-assistant-submit" ${ctx.assistantSending ? "disabled" : ""} aria-label="Send">\u2191</button>
2108
+ </form>
2109
+ </div>
2110
+ `;
2111
+ }
2112
+ function renderOutdatedBanner(ctx) {
2113
+ if (!ctx.sdkFreshness) return "";
2114
+ if (ctx.config.outdatedBanner === "off" || ctx.config.outdatedBanner === "console-only") return "";
2115
+ const { latest, current, deprecated, message } = ctx.sdkFreshness;
2116
+ if (!latest && !deprecated) return "";
2117
+ return `
2118
+ <div class="mushi-outdated" role="status">
2119
+ <strong>Mushi SDK ${escapeHtml(current)}</strong>
2120
+ ${latest ? `latest is ${escapeHtml(latest)}.` : "needs attention."}
2121
+ ${message ? `<span>${escapeHtml(message)}</span>` : ""}
2122
+ </div>
2392
2123
  `;
2393
- hint.textContent = this.locale.step3.elementSelectorHint;
2394
- document.body.appendChild(hint);
2395
- this.selectorHint = hint;
2396
- }
2397
- removeSelectorHint() {
2398
- this.selectorHint?.remove();
2399
- this.selectorHint = null;
2400
- document.getElementById("mushi-selector-hint")?.remove();
2401
- }
2402
- showNudge() {
2403
- if (this.nudgeShown || this.nudgeEl) return;
2404
- this.nudgeShown = true;
2405
- const trigger = this.shadow.querySelector(".mushi-trigger");
2406
- const rect = trigger?.getBoundingClientRect();
2407
- const nudge = document.createElement("div");
2408
- nudge.id = "mushi-nudge-bubble";
2409
- nudge.setAttribute("role", "tooltip");
2410
- const isRight = this.config.position.includes("right");
2411
- nudge.style.cssText = `
2412
- position: fixed;
2413
- z-index: 2147483645;
2414
- ${rect ? `bottom: ${window.innerHeight - rect.top + 8}px; ${isRight ? `right: ${window.innerWidth - rect.right}px;` : `left: ${rect.left}px;`}` : "bottom: 80px; right: 24px;"}
2415
- background: rgba(17,17,17,0.92);
2416
- color: #fff;
2417
- font-family: ui-sans-serif, system-ui, sans-serif;
2418
- font-size: 12px;
2419
- line-height: 1.4;
2420
- padding: 8px 12px;
2421
- border-radius: 8px;
2422
- max-width: 200px;
2423
- pointer-events: none;
2424
- backdrop-filter: blur(4px);
2425
- box-shadow: 0 2px 12px rgba(0,0,0,0.35);
2426
- animation: mushi-fade-in 0.15s ease forwards;
2124
+ }
2125
+ function renderBrandFooter(ctx) {
2126
+ if (ctx.config.brandFooter === false) return "";
2127
+ return `<div class="mushi-brand-footer">Powered by Mushi v${escapeHtml(ctx.sdkVersion)}</div>`;
2128
+ }
2129
+ function renderHeader(ctx, opts) {
2130
+ const t = ctx.locale;
2131
+ const { title, showBack = false, step, eyebrow } = opts;
2132
+ const eyebrowHtml = showBack ? `<button type="button" class="mushi-back" data-action="back" aria-label="${t.widget.back}">\u2190</button>` : `<span class="mushi-header-eyebrow">${eyebrow ?? "Mushi \xB7 Report"}</span>`;
2133
+ const counterHtml = step ? `<span class="mushi-step-counter" aria-label="Step ${step} of ${TOTAL_STEPS}"><b>${pad2(step)}</b> / ${pad2(TOTAL_STEPS)}</span>` : "";
2134
+ return `
2135
+ <div class="mushi-header">
2136
+ <div class="mushi-header-mark" aria-hidden="true">\u866B</div>
2137
+ <div class="mushi-header-titles">
2138
+ ${eyebrowHtml}
2139
+ <h3>${title}</h3>
2140
+ </div>
2141
+ <div class="mushi-header-meta">
2142
+ ${counterHtml}
2143
+ <button type="button" class="mushi-close" data-action="close" aria-label="${t.widget.close}">\u2715</button>
2144
+ </div>
2145
+ </div>
2427
2146
  `;
2428
- nudge.textContent = this.locale.step3.tooShort.startsWith("A bit") ? "Found a bug? One sentence is enough \u{1F41B}" : "\u30D0\u30B0\u3092\u898B\u3064\u3051\u305F\uFF1F\u4E00\u884C\u3067\u5927\u4E08\u592B\u3067\u3059 \u{1F41B}";
2429
- document.body.appendChild(nudge);
2430
- this.nudgeEl = nudge;
2431
- if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
2432
- this.nudgeTimer = setTimeout(() => this.removeNudge(), 5e3);
2433
- }
2434
- removeNudge() {
2435
- if (this.nudgeTimer !== null) {
2436
- clearTimeout(this.nudgeTimer);
2437
- this.nudgeTimer = null;
2438
- }
2439
- this.nudgeEl?.remove();
2440
- this.nudgeEl = null;
2441
- document.getElementById("mushi-nudge-bubble")?.remove();
2442
- }
2443
- setSdkFreshness(info) {
2444
- this.sdkFreshness = info;
2445
- if (this.isOpen) this.render();
2446
- }
2447
- setRewardsState(state) {
2448
- this.rewardsState = state;
2449
- if (this.isOpen) this.render();
2147
+ }
2148
+ function renderStepIndicator(_ctx, currentStep) {
2149
+ const segments = [];
2150
+ for (let i = 1; i <= TOTAL_STEPS; i++) {
2151
+ const cls = i < currentStep ? "mushi-step-num done" : i === currentStep ? "mushi-step-num active" : "mushi-step-num";
2152
+ segments.push(`<span class="${cls}">${pad2(i)}</span>`);
2153
+ if (i < TOTAL_STEPS) segments.push('<span class="mushi-step-sep" aria-hidden="true"></span>');
2154
+ }
2155
+ return `<div class="mushi-step-indicator" aria-hidden="true">${segments.join("")}</div>`;
2156
+ }
2157
+ function renderCategoryStep(ctx) {
2158
+ const t = ctx.locale;
2159
+ const categoryEntries = ctx.config.categories && ctx.config.categories.length > 0 ? ctx.config.categories.map((c) => ({
2160
+ id: c.id,
2161
+ icon: c.icon ?? "\u{1F4AC}",
2162
+ label: c.label,
2163
+ desc: c.description ?? ""
2164
+ })) : ["bug", "slow", "visual", "confusing", "other"].map((id) => ({
2165
+ id,
2166
+ icon: CATEGORY_ICONS[id],
2167
+ label: t.step1.categories[id],
2168
+ desc: t.step1.categoryDescriptions[id]
2169
+ }));
2170
+ const categories = categoryEntries.map(({ id, icon, label, desc }) => `
2171
+ <button type="button" class="mushi-option-btn" data-category="${escapeHtml(id)}" role="radio" aria-checked="false">
2172
+ <span class="mushi-option-icon" aria-hidden="true">${escapeHtml(icon)}</span>
2173
+ <div class="mushi-option-text">
2174
+ <span class="mushi-option-label">${escapeHtml(label)}</span>
2175
+ ${desc ? `<span class="mushi-option-desc">${escapeHtml(desc)}</span>` : ""}
2176
+ </div>
2177
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2178
+ </button>
2179
+ `).join("");
2180
+ return `
2181
+ ${renderHeader(ctx, { title: t.step1.heading, step: STEP_NUMBER.category })}
2182
+ ${ctx.config.betaMode?.enabled ? renderBetaStrip(ctx) : ""}
2183
+ <div class="mushi-body" role="radiogroup" aria-label="${t.step1.heading}">
2184
+ <button type="button" class="mushi-option-btn mushi-reports-entry" data-action="reports">
2185
+ <span class="mushi-option-icon" aria-hidden="true">\u{1F4EC}</span>
2186
+ <div class="mushi-option-text">
2187
+ <span class="mushi-option-label">Your reports${ctx.unreadCount() ? ` (${ctx.unreadCount()} new)` : ""}</span>
2188
+ <span class="mushi-option-desc">See status, developer replies, and respond</span>
2189
+ </div>
2190
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2191
+ </button>
2192
+ ${renderFeatureRequestEntry(ctx)}
2193
+ ${ctx.callbacks.onFeatureBoardRequest ? `
2194
+ <button type="button" class="mushi-option-btn" data-action="roadmap">
2195
+ <span class="mushi-option-icon" aria-hidden="true">\u{1F5F3}\uFE0F</span>
2196
+ <div class="mushi-option-text">
2197
+ <span class="mushi-option-label">Community ideas</span>
2198
+ <span class="mushi-option-desc">Vote on features and see what shipped</span>
2199
+ </div>
2200
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2201
+ </button>` : ""}
2202
+ ${categories}
2203
+ ${ctx.rewardsState ? renderRewardsNudge(ctx) : ""}
2204
+ <div class="mushi-community-footer">
2205
+ <button type="button" class="mushi-link-btn mushi-community-btn" data-action="open-account">
2206
+ ${ctx.testerInfo ? `\u{1F464} ${escapeHtml(ctx.testerInfo.public_handle ?? ctx.testerInfo.display_name ?? "My account")}` : "\u{1F310} Join community \xB7 Track reports across apps"}
2207
+ </button>
2208
+ ${ctx.rewardsState ? `<button type="button" class="mushi-link-btn" data-action="open-leaderboard">\u{1F3C6} Leaderboard</button>` : ""}
2209
+ </div>
2210
+ </div>
2211
+ ${renderStepIndicator(ctx, STEP_NUMBER.category)}
2212
+ `;
2213
+ }
2214
+ function renderFeatureRequestEntry(ctx) {
2215
+ const enabled = ctx.config.featureRequestCard !== false;
2216
+ if (!enabled) return "";
2217
+ const label = ctx.config.featureRequestLabel || "Feature request";
2218
+ const desc = ctx.config.featureRequestDescription || "Suggest something new \u2014 even rough ideas help us prioritise";
2219
+ return `
2220
+ <button
2221
+ type="button"
2222
+ class="mushi-option-btn mushi-feature-entry"
2223
+ data-action="feature-request"
2224
+ aria-label="${escapeHtml(label)}"
2225
+ >
2226
+ <span class="mushi-option-icon" aria-hidden="true">\u2728</span>
2227
+ <div class="mushi-option-text">
2228
+ <span class="mushi-option-label">${escapeHtml(label)}</span>
2229
+ <span class="mushi-option-desc">${escapeHtml(desc)}</span>
2230
+ </div>
2231
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2232
+ </button>
2233
+ `;
2234
+ }
2235
+ function renderBetaChangelog(ctx) {
2236
+ const entries = ctx.config.betaMode?.changelogItems;
2237
+ if (!entries?.length) return "";
2238
+ const latest = entries[0];
2239
+ const items = latest.items.map((item) => `<li>\u2022 ${escapeHtml(item)}</li>`).join("");
2240
+ const label = latest.date ? `What\u2019s new in ${escapeHtml(latest.version)} \xB7 ${escapeHtml(latest.date)}` : `What\u2019s new in ${escapeHtml(latest.version)}`;
2241
+ return `
2242
+ <details class="mushi-changelog">
2243
+ <summary class="mushi-changelog-summary">${label}</summary>
2244
+ <ul class="mushi-changelog-list">${items}</ul>
2245
+ </details>
2246
+ `;
2247
+ }
2248
+ function renderBetaStrip(ctx) {
2249
+ const beta = ctx.config.betaMode;
2250
+ const appName = escapeHtml(beta.appName ?? "This app");
2251
+ const message = beta.message ? escapeHtml(beta.message) : `${appName} is in early development \u2014 updates ship weekly`;
2252
+ const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
2253
+ const perks = beta.perks ?? [];
2254
+ return `
2255
+ <div class="mushi-beta-strip" role="note" aria-label="Beta status">
2256
+ <div class="mushi-beta-strip-row">
2257
+ <span class="mushi-beta-tag" aria-hidden="true">BETA</span>
2258
+ <span class="mushi-beta-msg">${message}</span>
2259
+ </div>
2260
+ ${email ? `<div class="mushi-beta-contact-hint">Reports go to ${email} \xB7 reviewed by the team</div>` : ""}
2261
+ ${perks.length > 0 ? `
2262
+ <ul class="mushi-beta-perks" aria-label="Beta tester perks">
2263
+ ${perks.map((p) => `<li>\u2713 ${escapeHtml(p)}</li>`).join("")}
2264
+ </ul>
2265
+ ` : ""}
2266
+ ${renderBetaChangelog(ctx)}
2267
+ </div>
2268
+ `;
2269
+ }
2270
+ function renderReportsStep(ctx) {
2271
+ const reports = ctx.reporterReports.map((report) => {
2272
+ const title = report.summary ?? report.description ?? `Report ${report.id.slice(0, 8)}`;
2273
+ const tone = reporterStatusTone(report.status);
2274
+ const when = formatRelativeTime(report.created_at);
2275
+ const unread = report.unread_count && report.unread_count > 0 ? `<span class="mushi-unread-badge" aria-label="${report.unread_count} unread">${report.unread_count}</span>` : "";
2276
+ return `
2277
+ <button type="button" class="mushi-report-row" data-report-id="${escapeHtml(report.id)}" aria-label="View report: ${escapeHtml(title)}">
2278
+ <div class="mushi-report-main">
2279
+ <span class="mushi-report-title">${escapeHtml(title)}</span>
2280
+ <span class="mushi-report-meta">
2281
+ <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusShort(report.status))}</span>
2282
+ ${when ? `<span class="mushi-report-when">${escapeHtml(when)}</span>` : ""}
2283
+ ${unread}
2284
+ </span>
2285
+ </div>
2286
+ <span class="mushi-report-chevron" aria-hidden="true">\u203A</span>
2287
+ </button>`;
2288
+ }).join("");
2289
+ const leaderboardBtn = ctx.rewardsState ? `<button type="button" class="mushi-leaderboard-link" data-action="open-leaderboard">\u{1F3C6} Leaderboard</button>` : "";
2290
+ return `
2291
+ ${renderHeader(ctx, { title: "Your reports", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
2292
+ <div class="mushi-body">
2293
+ ${ctx.reporterLoading ? '<p class="mushi-muted">Loading reports\u2026</p>' : ""}
2294
+ ${ctx.reporterError ? `<p class="mushi-error-inline">${escapeHtml(ctx.reporterError)}</p>` : ""}
2295
+ ${reports || (!ctx.reporterLoading ? '<p class="mushi-muted">No reports from this browser yet.</p>' : "")}
2296
+ ${leaderboardBtn}
2297
+ </div>
2298
+ `;
2299
+ }
2300
+ function renderRoadmapStep(ctx) {
2301
+ const rows = ctx.featureBoard.map((ticket) => {
2302
+ const id = String(ticket.id ?? "");
2303
+ const subject = escapeHtml(String(ticket.subject ?? "Untitled idea"));
2304
+ const votes = Number(ticket.vote_count ?? 0);
2305
+ const shipped = Boolean(ticket.shipped_at);
2306
+ const voted = Boolean(ticket.my_vote);
2307
+ const status = shipped ? "Shipped" : String(ticket.status_label ?? ticket.status ?? "open");
2308
+ return `
2309
+ <div class="mushi-report-row mushi-roadmap-row">
2310
+ <div class="mushi-report-main">
2311
+ <span class="mushi-report-title">${subject}</span>
2312
+ <span class="mushi-report-meta">
2313
+ <span class="mushi-report-status">${escapeHtml(status)}</span>
2314
+ <span class="mushi-report-when">${votes} vote${votes === 1 ? "" : "s"}</span>
2315
+ </span>
2316
+ </div>
2317
+ ${ctx.callbacks.onFeatureBoardVote ? `
2318
+ <button type="button" class="mushi-vote-btn" data-vote-id="${escapeHtml(id)}" aria-pressed="${voted}">
2319
+ ${voted ? "Voted" : "Vote"}
2320
+ </button>` : ""}
2321
+ </div>`;
2322
+ }).join("");
2323
+ return `
2324
+ ${renderHeader(ctx, { title: "Community ideas", showBack: true, eyebrow: "Mushi \xB7 Roadmap" })}
2325
+ <div class="mushi-body">
2326
+ ${ctx.reporterLoading ? '<p class="mushi-muted">Loading ideas\u2026</p>' : ""}
2327
+ ${ctx.reporterError ? `<p class="mushi-error-inline">${escapeHtml(ctx.reporterError)}</p>` : ""}
2328
+ ${rows || (!ctx.reporterLoading ? '<p class="mushi-muted">No community ideas yet. Be the first to suggest one.</p>' : "")}
2329
+ </div>
2330
+ `;
2331
+ }
2332
+ function renderLeaderboardStep(ctx) {
2333
+ const isGlobal = ctx.globalLeaderboard !== null || ctx.globalLeaderboardLoading;
2334
+ const entries = isGlobal ? ctx.globalLeaderboard ?? [] : (ctx.leaderboardEntries ?? []).map((e) => ({
2335
+ tester_id: "",
2336
+ public_handle: null,
2337
+ display_name: e.display_name,
2338
+ rank: 0,
2339
+ points_30d: e.points_30d,
2340
+ total_points: e.total_points
2341
+ }));
2342
+ const loading = isGlobal ? ctx.globalLeaderboardLoading : ctx.leaderboardLoading;
2343
+ const myRank = ctx.testerReputation?.rank ?? null;
2344
+ const rows = entries.map((e, i) => {
2345
+ const rank = e.rank || i + 1;
2346
+ const isMe = ctx.testerReputation && e.tester_id === ctx.testerReputation.tester_id;
2347
+ return `
2348
+ <div class="mushi-lb-row ${rank === 1 ? "mushi-lb-top" : ""}${isMe ? " mushi-lb-me" : ""}">
2349
+ <span class="mushi-lb-rank">#${rank}</span>
2350
+ <span class="mushi-lb-name">${escapeHtml(e.public_handle ?? e.display_name ?? "Anon")}</span>
2351
+ <span class="mushi-lb-pts">${(e.points_30d ?? e.total_points).toLocaleString()} pts</span>
2352
+ </div>
2353
+ `;
2354
+ }).join("");
2355
+ const myRankBadge = myRank ? `<div class="mushi-lb-myrank">You are ranked <strong>#${myRank}</strong> this month</div>` : !ctx.testerJwt ? `<button type="button" class="mushi-link-btn" data-action="open-account">Sign in to see your rank \u2192</button>` : "";
2356
+ return `
2357
+ ${renderHeader(ctx, { title: "\u{1F3C6} Global Leaderboard", showBack: true, eyebrow: "Mushi \xB7 Community" })}
2358
+ <div class="mushi-body">
2359
+ ${loading ? '<p class="mushi-muted">Loading leaderboard\u2026</p>' : ""}
2360
+ ${!loading && !entries.length ? '<p class="mushi-muted">No contributors yet \u2014 be the first!</p>' : ""}
2361
+ <div class="mushi-lb-list">${rows}</div>
2362
+ ${myRankBadge}
2363
+ <p class="mushi-lb-note">Global contributors this month \xB7 Points refresh monthly</p>
2364
+ </div>
2365
+ `;
2366
+ }
2367
+ function renderAccountStep(ctx) {
2368
+ const tester = ctx.testerInfo;
2369
+ if (tester) {
2370
+ const handle = tester.public_handle ?? tester.display_name ?? "Tester";
2371
+ const rep = ctx.testerReputation;
2372
+ return `
2373
+ ${renderHeader(ctx, { title: "\u866B Mushi Account", showBack: true, eyebrow: "Mushi \xB7 Identity" })}
2374
+ <div class="mushi-body">
2375
+ <div class="mushi-account-card">
2376
+ <div class="mushi-account-avatar">${escapeHtml(handle.charAt(0).toUpperCase())}</div>
2377
+ <div class="mushi-account-info">
2378
+ <strong>${escapeHtml(handle)}</strong>
2379
+ ${rep ? `<span class="mushi-account-rank">Rank #${rep.rank ?? "\u2014"} \xB7 ${(rep.points_30d ?? 0).toLocaleString()} pts this month</span>` : ""}
2380
+ </div>
2381
+ </div>
2382
+ <button type="button" class="mushi-nav-item" data-action="open-cross-app-reports">
2383
+ My reports across all apps \u2192
2384
+ </button>
2385
+ <button type="button" class="mushi-nav-item" data-action="open-global-leaderboard">
2386
+ View global leaderboard \u2192
2387
+ </button>
2388
+ <button type="button" class="mushi-link-btn" data-action="sign-out-tester">Sign out</button>
2389
+ </div>
2390
+ `;
2450
2391
  }
2451
- setLeaderboard(entries, loading = false) {
2452
- this.leaderboardEntries = entries;
2453
- this.leaderboardLoading = loading;
2454
- if (this.isOpen && this.step === "leaderboard") this.render();
2392
+ if (ctx.magicLinkSent) {
2393
+ return `
2394
+ ${renderHeader(ctx, { title: "\u866B Check your email", showBack: true, eyebrow: "Mushi \xB7 Sign in" })}
2395
+ <div class="mushi-body">
2396
+ <p class="mushi-muted">We sent a sign-in link to <strong>${escapeHtml(ctx.magicLinkEmail)}</strong>. Click it to connect your reports across apps and join the community.</p>
2397
+ <button type="button" class="mushi-link-btn" data-action="resend-magic-link">Resend email</button>
2398
+ ${ctx.magicLinkError ? `<p class="mushi-error">${escapeHtml(ctx.magicLinkError)}</p>` : ""}
2399
+ </div>
2400
+ `;
2455
2401
  }
2456
- // ── Community public setters (called by mushi.ts after API calls) ──────────
2457
- setTesterSession(jwt, info) {
2458
- this.testerJwt = jwt;
2459
- this.testerInfo = info;
2460
- if (this.isOpen) this.render();
2402
+ return `
2403
+ ${renderHeader(ctx, { title: "\u866B Join the community", showBack: true, eyebrow: "Mushi \xB7 Sign in" })}
2404
+ <div class="mushi-body">
2405
+ <p class="mushi-muted">Sign in to see your reports across all apps and climb the global leaderboard. No password needed.</p>
2406
+ <label class="mushi-label" for="mushi-email-input">Email address</label>
2407
+ <input
2408
+ id="mushi-email-input"
2409
+ type="email"
2410
+ class="mushi-textarea"
2411
+ data-role="magic-link-email"
2412
+ placeholder="you@example.com"
2413
+ autocomplete="email"
2414
+ value="${escapeHtml(ctx.magicLinkEmail)}"
2415
+ style="padding: 10px 12px; height: auto; resize: none;"
2416
+ />
2417
+ ${ctx.magicLinkError ? `<p class="mushi-error">${escapeHtml(ctx.magicLinkError)}</p>` : ""}
2418
+ <button type="button" class="mushi-submit" data-action="send-magic-link"${ctx.magicLinkSending ? ' disabled aria-disabled="true"' : ""}>
2419
+ <span>${ctx.magicLinkSending ? "Sending\u2026" : "Send sign-in link"}</span><span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
2420
+ </button>
2421
+ </div>
2422
+ `;
2423
+ }
2424
+ function renderCrossAppReportsStep(ctx) {
2425
+ const reports = ctx.crossAppReports ?? [];
2426
+ const grouped = /* @__PURE__ */ new Map();
2427
+ for (const r of reports) {
2428
+ const key = r.project_id ?? "unknown";
2429
+ if (!grouped.has(key)) grouped.set(key, { name: r.app_name ?? "Unknown App", reports: [] });
2430
+ grouped.get(key).reports.push(r);
2431
+ }
2432
+ const rows = [...grouped.entries()].map(([, group]) => `
2433
+ <div class="mushi-xapp-group">
2434
+ <h4 class="mushi-xapp-app-name">${escapeHtml(group.name)}</h4>
2435
+ ${group.reports.map((r) => {
2436
+ const tone = reporterStatusTone(r.status);
2437
+ return `
2438
+ <div class="mushi-report-row" data-report-id="${escapeHtml(r.id)}" tabindex="0" role="button">
2439
+ <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusShort(r.status))}</span>
2440
+ <span class="mushi-report-title">${escapeHtml(r.title ?? r.category)}</span>
2441
+ <span class="mushi-report-when">${escapeHtml(formatRelativeTime(r.created_at))}</span>
2442
+ </div>
2443
+ `;
2444
+ }).join("")}
2445
+ </div>
2446
+ `).join("");
2447
+ return `
2448
+ ${renderHeader(ctx, { title: "My reports", showBack: true, eyebrow: "Mushi \xB7 All apps" })}
2449
+ <div class="mushi-body">
2450
+ ${ctx.crossAppLoading ? '<p class="mushi-muted">Loading your reports\u2026</p>' : ""}
2451
+ ${!ctx.crossAppLoading && !reports.length ? '<p class="mushi-muted">No reports filed yet.</p>' : ""}
2452
+ ${rows}
2453
+ </div>
2454
+ `;
2455
+ }
2456
+ function renderReportDetailStep(ctx) {
2457
+ const report = ctx.reporterReports.find((r) => r.id === ctx.selectedReportId);
2458
+ const status = report?.status ?? "unknown";
2459
+ const tone = reporterStatusTone(status);
2460
+ const when = report?.created_at ? formatRelativeTime(report.created_at) : "";
2461
+ const comments = ctx.reporterComments.map((comment) => `
2462
+ <div class="mushi-thread-comment ${comment.author_kind}">
2463
+ <strong>${escapeHtml(comment.author_kind === "reporter" ? "You" : comment.author_name ?? "Developer")}</strong>
2464
+ <p>${escapeHtml(comment.body)}</p>
2465
+ </div>
2466
+ `).join("");
2467
+ return `
2468
+ ${renderHeader(ctx, { title: "Report thread", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
2469
+ <div class="mushi-body">
2470
+ <div class="mushi-thread-summary">
2471
+ <div class="mushi-thread-summary-meta">
2472
+ <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusLabel(status))}</span>
2473
+ ${when ? `<span class="mushi-report-when">Reported ${escapeHtml(when)}</span>` : ""}
2474
+ </div>
2475
+ <p>${escapeHtml(report?.summary ?? report?.description ?? "Report details")}</p>
2476
+ </div>
2477
+ <div class="mushi-thread">
2478
+ ${ctx.reporterLoading ? '<p class="mushi-muted">Loading thread\u2026</p>' : comments || '<p class="mushi-muted">No developer replies yet.</p>'}
2479
+ </div>
2480
+ ${["fixed", "resolved", "verified"].includes(status) ? `
2481
+ <div class="mushi-verify-actions" role="group" aria-label="Fix verification">
2482
+ <button type="button" class="mushi-intent-btn" data-action="reporter-confirms">Yes, fixed for me</button>
2483
+ <button type="button" class="mushi-intent-btn" data-action="reporter-not-fixed">Not fixed yet</button>
2484
+ </div>
2485
+ ` : ""}
2486
+ <textarea class="mushi-textarea" data-role="reporter-reply" rows="3" placeholder="Reply to the developer\u2026"></textarea>
2487
+ <button type="button" class="mushi-submit" data-action="reporter-reply">
2488
+ <span>Reply</span><span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
2489
+ </button>
2490
+ </div>
2491
+ `;
2492
+ }
2493
+ function renderIntentStep(ctx) {
2494
+ const t = ctx.locale;
2495
+ const catId = ctx.selectedCategory;
2496
+ const customEntry = ctx.resolveCustomCategory(catId);
2497
+ const intents = customEntry?.intents ?? (t.step2.intents[catId] || []);
2498
+ const options = intents.map((intent) => `
2499
+ <button type="button" class="mushi-intent-btn" data-intent="${escapeHtml(intent)}">
2500
+ ${escapeHtml(intent)}
2501
+ </button>
2502
+ `).join("");
2503
+ const icon = ctx.categoryIcon(catId);
2504
+ const label = ctx.categoryLabel(catId);
2505
+ return `
2506
+ ${renderHeader(ctx, { title: t.step2.heading, showBack: true, step: STEP_NUMBER.intent })}
2507
+ <div class="mushi-body">
2508
+ <div class="mushi-selected-category">
2509
+ <span aria-hidden="true">${escapeHtml(icon)}</span>
2510
+ <span>${escapeHtml(label)}</span>
2511
+ </div>
2512
+ <div class="mushi-intents">
2513
+ ${options}
2514
+ </div>
2515
+ </div>
2516
+ ${renderStepIndicator(ctx, STEP_NUMBER.intent)}
2517
+ `;
2518
+ }
2519
+ function renderDetailsStep(ctx) {
2520
+ const t = ctx.locale;
2521
+ const minLen = ctx.effectiveMinLength();
2522
+ const screenshotLabel = ctx.screenshotCapturing ? t.step3.screenshotCapturing : ctx.screenshotError ? t.step3.screenshotFailed : ctx.screenshotAttached ? t.step3.screenshotAttached : t.step3.screenshotButton;
2523
+ const screenshotClass = [
2524
+ "mushi-attach-btn",
2525
+ ctx.screenshotAttached ? "active" : "",
2526
+ ctx.screenshotError ? "error" : "",
2527
+ ctx.screenshotCapturing ? "loading" : ""
2528
+ ].filter(Boolean).join(" ");
2529
+ const elementLabel = ctx.elementCapturing ? t.step3.elementCapturing : ctx.elementSelected ? t.step3.elementSelected : t.step3.elementButton;
2530
+ const elementClass = [
2531
+ "mushi-attach-btn",
2532
+ ctx.elementSelected ? "active" : "",
2533
+ ctx.elementCapturing ? "loading" : ""
2534
+ ].filter(Boolean).join(" ");
2535
+ const exampleChips = t.step3.examplePrompts.map((p) => `<button type="button" class="mushi-example-chip" data-example="${escapeHtml(p)}">${escapeHtml(p)}</button>`).join("");
2536
+ return `
2537
+ ${renderHeader(ctx, { title: t.step3.heading, showBack: true, step: STEP_NUMBER.details })}
2538
+ <div class="mushi-body">
2539
+ <div class="mushi-example-chips" aria-label="Example prompts">${exampleChips}</div>
2540
+ <div class="mushi-textarea-wrap">
2541
+ <textarea
2542
+ class="mushi-textarea"
2543
+ placeholder="${t.step3.descriptionPlaceholder}"
2544
+ rows="4"
2545
+ aria-label="${t.step3.heading}"
2546
+ autofocus
2547
+ ></textarea>
2548
+ <div class="mushi-char-counter" data-role="char-counter" aria-hidden="true">
2549
+ <span data-role="char-current">0</span>/<span data-role="char-min">${minLen}</span>
2550
+ </div>
2551
+ </div>
2552
+ <div class="mushi-attachments">
2553
+ <button type="button" class="${screenshotClass}"
2554
+ data-action="screenshot"
2555
+ ${ctx.screenshotCapturing ? "disabled" : ""}
2556
+ aria-label="${escapeHtml(screenshotLabel)}"
2557
+ >
2558
+ ${ctx.screenshotCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F4F8}"}
2559
+ ${escapeHtml(screenshotLabel)}
2560
+ </button>
2561
+ ${ctx.screenshotAttached && ctx.allowScreenshotRemove ? '<button type="button" class="mushi-attach-btn danger" data-action="remove-screenshot" aria-label="Remove screenshot">\u2715 Remove</button>' : ""}
2562
+ ${ctx.screenshotAttached ? '<button type="button" class="mushi-attach-btn" data-action="annotate-screenshot" aria-label="Mark up screenshot">\u270F Mark up</button><div class="mushi-annotate-host" data-role="annotate-host"></div>' : ""}
2563
+ <button type="button" class="${elementClass}"
2564
+ data-action="element"
2565
+ ${ctx.elementCapturing ? "disabled" : ""}
2566
+ aria-label="${escapeHtml(elementLabel)}"
2567
+ >
2568
+ ${ctx.elementCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F3AF}"}
2569
+ ${escapeHtml(elementLabel)}
2570
+ </button>
2571
+ </div>
2572
+ <div class="mushi-error" style="display:none" role="alert"></div>
2573
+ </div>
2574
+ <div class="mushi-footer">
2575
+ <span class="mushi-footer-hint" aria-hidden="true">\u2318 + ENTER \u2192 send</span>
2576
+ <button type="button" class="mushi-submit" data-action="submit"${ctx.submitting ? " disabled" : ""}>
2577
+ <span>${ctx.submitting ? t.widget.submitting : t.widget.submit}</span>
2578
+ <span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
2579
+ </button>
2580
+ </div>
2581
+ ${renderStepIndicator(ctx, STEP_NUMBER.details)}
2582
+ `;
2583
+ }
2584
+ function renderSuccessStep(ctx) {
2585
+ const t = ctx.locale;
2586
+ const stamp = ctx.submittedAt ?? /* @__PURE__ */ new Date();
2587
+ const time = stamp.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
2588
+ return `
2589
+ ${renderHeader(ctx, { title: t.widget.title, eyebrow: "Mushi \xB7 Receipt" })}
2590
+ <div class="mushi-body">
2591
+ <div class="mushi-success">
2592
+ <div class="mushi-success-stamp" aria-hidden="true">
2593
+ <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"><circle cx="50" cy="50" r="44"/></svg>
2594
+ <span class="mushi-success-stamp-label">\u53D7</span>
2595
+ </div>
2596
+ <div class="mushi-success-headline">${t.widget.submitted}</div>
2597
+ <div class="mushi-success-meta">REPORT \xB7 ${time}</div>
2598
+ ${renderSuccessReceipt(ctx)}
2599
+ ${ctx.rewardsState ? renderSuccessRewards(ctx) : ""}
2600
+ ${ctx.config.betaMode?.enabled ? renderBetaSuccessFooter(ctx) : ""}
2601
+ </div>
2602
+ </div>
2603
+ `;
2604
+ }
2605
+ function renderSuccessReceipt(ctx) {
2606
+ if (ctx.lastSubmitQueuedOffline) {
2607
+ return `
2608
+ <div class="mushi-success-receipt" role="status">
2609
+ <div class="mushi-success-receipt-row mushi-success-receipt-warn">
2610
+ <span class="mushi-success-receipt-label">Queued offline</span>
2611
+ <span class="mushi-success-receipt-hint">We&rsquo;ll send it the moment you&rsquo;re back online.</span>
2612
+ </div>
2613
+ </div>
2614
+ `;
2461
2615
  }
2462
- setGlobalLeaderboard(entries, loading = false) {
2463
- this.globalLeaderboard = entries;
2464
- this.globalLeaderboardLoading = loading;
2465
- if (this.isOpen && (this.step === "leaderboard" || this.step === "account")) this.render();
2616
+ if (!ctx.lastReportId) {
2617
+ return `
2618
+ <div class="mushi-success-receipt" role="status">
2619
+ <div class="mushi-success-receipt-row">
2620
+ <span class="mushi-success-receipt-spinner" aria-hidden="true"></span>
2621
+ <span class="mushi-success-receipt-hint">Delivering to the team\u2026</span>
2622
+ </div>
2623
+ ${renderSlaLine(ctx)}
2624
+ </div>
2625
+ `;
2466
2626
  }
2467
- setCrossAppReports(reports, loading = false) {
2468
- this.crossAppReports = reports;
2469
- this.crossAppLoading = loading;
2470
- if (this.isOpen && this.step === "cross-app-reports") this.render();
2627
+ const idShort = `#${ctx.lastReportId.slice(0, 8)}`;
2628
+ const dashboard = (ctx.config.dashboardUrl ?? "").replace(/\/$/, "");
2629
+ const trackHref = dashboard ? `${dashboard}/reports/${encodeURIComponent(ctx.lastReportId)}` : "";
2630
+ return `
2631
+ <div class="mushi-success-receipt" role="status">
2632
+ <div class="mushi-success-receipt-row">
2633
+ <span class="mushi-success-receipt-label">Receipt</span>
2634
+ <button
2635
+ type="button"
2636
+ class="mushi-success-receipt-id"
2637
+ data-action="copy-report-id"
2638
+ data-copy-id="${escapeHtml(ctx.lastReportId)}"
2639
+ title="Copy report id ${escapeHtml(ctx.lastReportId)}"
2640
+ aria-label="Copy report id ${escapeHtml(ctx.lastReportId)}"
2641
+ >${escapeHtml(idShort)}<span class="mushi-success-receipt-copy" aria-hidden="true">\u2398</span></button>
2642
+ </div>
2643
+ ${trackHref ? `
2644
+ <a
2645
+ class="mushi-success-receipt-track"
2646
+ href="${escapeHtml(trackHref)}"
2647
+ target="_blank"
2648
+ rel="noopener noreferrer"
2649
+ >Track on Mushi <span aria-hidden="true">\u2197</span></a>
2650
+ ` : ""}
2651
+ ${renderSlaLine(ctx)}
2652
+ </div>
2653
+ `;
2654
+ }
2655
+ function renderSlaLine(ctx) {
2656
+ const sla = (ctx.config.responseSlaLabel ?? "").trim();
2657
+ if (sla) {
2658
+ return `<div class="mushi-success-sla">${escapeHtml(sla)}</div>`;
2471
2659
  }
2472
- setTesterReputation(rep) {
2473
- this.testerReputation = rep;
2474
- if (this.isOpen && (this.step === "account" || this.step === "leaderboard")) this.render();
2660
+ return `<div class="mushi-success-sla mushi-success-sla-default">A human will look at this within a working day.</div>`;
2661
+ }
2662
+ function renderBetaSuccessFooter(ctx) {
2663
+ const beta = ctx.config.betaMode;
2664
+ const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
2665
+ const appName = escapeHtml(beta.appName ?? "the team");
2666
+ return `
2667
+ <div class="mushi-beta-success-footer" role="note" aria-label="Beta feedback acknowledgement">
2668
+ ${email ? `<div class="mushi-beta-success-line">\u{1F4EC} Sent to ${email}</div>` : `<div class="mushi-beta-success-line">\u{1F4EC} Sent to ${appName}</div>`}
2669
+ <div class="mushi-beta-success-line mushi-beta-success-dim">We aim to review within 48h \xB7 thank you for helping build this</div>
2670
+ </div>
2671
+ `;
2672
+ }
2673
+ function renderRewardsNudge(ctx) {
2674
+ const { tier, nextTier, totalPoints, pointsForReport } = ctx.rewardsState;
2675
+ const tierName = tier?.displayName ?? "Free";
2676
+ const tierSlug = tier?.slug ?? "free";
2677
+ const color = ctx.tierColor(tierSlug);
2678
+ let pct = 100;
2679
+ let nextLabel = "";
2680
+ if (nextTier) {
2681
+ const base = tier?.pointsThreshold ?? 0;
2682
+ const ceiling = nextTier.pointsThreshold;
2683
+ pct = ceiling > base ? Math.round(Math.min(1, (totalPoints - base) / (ceiling - base)) * 100) : 100;
2684
+ const remaining = Math.max(0, ceiling - totalPoints);
2685
+ nextLabel = `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}`;
2475
2686
  }
2476
- destroy() {
2477
- if (this.successTimer !== null) {
2478
- clearTimeout(this.successTimer);
2479
- this.successTimer = null;
2480
- }
2481
- if (this.autoCloseTimer !== null) {
2482
- clearTimeout(this.autoCloseTimer);
2483
- this.autoCloseTimer = null;
2484
- }
2485
- if (this.smartHideTimer !== null) {
2486
- clearTimeout(this.smartHideTimer);
2487
- this.smartHideTimer = null;
2488
- }
2489
- this.smartHideCleanup?.();
2490
- this.smartHideCleanup = null;
2491
- this.teardownViewportHandlers();
2492
- this.attachedLaunchers.forEach((cleanup) => cleanup());
2493
- this.attachedLaunchers = [];
2494
- this.removeSelectorHint();
2495
- this.removeNudge();
2496
- this.removeBodyNudge();
2497
- this.host.remove();
2687
+ return `
2688
+ <div class="mushi-rewards-nudge" aria-label="Rewards progress">
2689
+ <div class="mushi-rewards-row">
2690
+ <span class="mushi-tier-pip" style="background:${color}" aria-hidden="true"></span>
2691
+ <span class="mushi-rewards-tier-name">${escapeHtml(tierName)}</span>
2692
+ <span class="mushi-rewards-pts-count">${totalPoints.toLocaleString()} pts</span>
2693
+ <span class="mushi-rewards-pts-earn">+${pointsForReport} pts for a report</span>
2694
+ </div>
2695
+ ${nextTier ? `
2696
+ <div class="mushi-tier-bar-track" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="Progress to ${escapeHtml(nextTier.displayName)}">
2697
+ <div class="mushi-tier-bar-fill" style="width:${pct}%"></div>
2698
+ </div>
2699
+ <div class="mushi-rewards-next-label">${nextLabel}</div>
2700
+ ` : ""}
2701
+ </div>
2702
+ `;
2703
+ }
2704
+ function renderSuccessRewards(ctx) {
2705
+ const { tier, nextTier, totalPoints, pointsForReport } = ctx.rewardsState;
2706
+ const projected = totalPoints + pointsForReport;
2707
+ let pctAfter = 100;
2708
+ let nextLabel = "";
2709
+ if (nextTier) {
2710
+ const base = tier?.pointsThreshold ?? 0;
2711
+ const ceiling = nextTier.pointsThreshold;
2712
+ pctAfter = ceiling > base ? Math.round(Math.min(1, (projected - base) / (ceiling - base)) * 100) : 100;
2713
+ const remaining = Math.max(0, ceiling - projected);
2714
+ nextLabel = remaining > 0 ? `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}` : `\u{1F389} ${escapeHtml(nextTier.displayName)} reached!`;
2498
2715
  }
2499
- /* ── Host chrome contract ────────────────────────────────────────────────
2500
- The host element must never create an invisible full-screen touch blocker.
2501
- We own these inline styles — consumer CSS can only win with `!important`,
2502
- which is explicitly banned by the SDK contract. Calling this at mount()
2503
- and after every zIndex update is the only safe invariant. */
2504
- /**
2505
- * Apply the SDK-owned pass-through layout to the host element so it is
2506
- * always zero-sized and click/touch-transparent. Only the shadow-root
2507
- * internals (`.mushi-trigger`, `.mushi-banner`, `.mushi-panel`) opt back
2508
- * into pointer events. This is idempotent and safe to call repeatedly.
2509
- */
2510
- syncHostChromeState() {
2511
- const s = this.host.style;
2512
- s.setProperty("position", "fixed");
2513
- s.setProperty("top", "0");
2514
- s.setProperty("left", "0");
2515
- s.setProperty("width", "0");
2516
- s.setProperty("height", "0");
2517
- s.setProperty("overflow", "visible");
2518
- s.setProperty("pointer-events", "none");
2519
- s.setProperty("z-index", String(this.config.zIndex));
2520
- s.setProperty("margin", "0");
2521
- s.setProperty("padding", "0");
2522
- s.setProperty("border", "none");
2523
- s.setProperty("background", "none");
2716
+ return `
2717
+ <div class="mushi-success-rewards">
2718
+ <div class="mushi-success-pts-award">+${pointsForReport} pts</div>
2719
+ ${nextTier ? `
2720
+ <div class="mushi-tier-bar-track success-bar" role="progressbar" aria-valuenow="${pctAfter}" aria-valuemin="0" aria-valuemax="100" aria-label="Progress to ${escapeHtml(nextTier.displayName)}">
2721
+ <div class="mushi-tier-bar-fill" style="width:${pctAfter}%"></div>
2722
+ </div>
2723
+ <div class="mushi-rewards-next-label">${nextLabel}</div>
2724
+ ` : ""}
2725
+ </div>
2726
+ `;
2727
+ }
2728
+
2729
+ // src/widget.ts
2730
+ var MushiWidget = class _MushiWidget {
2731
+ constructor(config = {}, callbacks, sdkVersion = MUSHI_SDK_VERSION) {
2732
+ this.sdkVersion = sdkVersion;
2733
+ this.config = {
2734
+ position: config.position ?? "bottom-right",
2735
+ anchor: config.anchor ?? {},
2736
+ theme: config.theme ?? "auto",
2737
+ // Falsy-OR (NOT `??`) on purpose: `triggerText: ''` is semantically
2738
+ // nonsense — it would render a labelless, glyphless trigger button
2739
+ // that users can't see or aim at. Treat empty string the same as
2740
+ // omitted so any caller that wires this to a cleared form input or
2741
+ // pastes a legacy snippet that emitted `triggerText: ""` (see
2742
+ // apps/admin/src/lib/sdkSnippets.ts widgetLines history) still gets
2743
+ // the default 🐛 and a visible button.
2744
+ triggerText: config.triggerText || "\u{1F41B}",
2745
+ expandedTitle: config.expandedTitle ?? "",
2746
+ mode: config.mode ?? "conversational",
2747
+ locale: config.locale ?? "auto",
2748
+ zIndex: config.zIndex ?? 99999,
2749
+ trigger: config.trigger ?? "auto",
2750
+ bannerConfig: config.bannerConfig ?? {},
2751
+ attachToSelector: config.attachToSelector ?? "",
2752
+ inset: config.inset ?? {},
2753
+ respectSafeArea: config.respectSafeArea ?? true,
2754
+ hideOnSelector: config.hideOnSelector ?? "",
2755
+ hideOnRoutes: config.hideOnRoutes ?? [],
2756
+ environments: config.environments ?? {},
2757
+ smartHide: config.smartHide ?? false,
2758
+ draggable: config.draggable ?? false,
2759
+ brandFooter: config.brandFooter ?? true,
2760
+ outdatedBanner: config.outdatedBanner ?? "auto",
2761
+ betaMode: config.betaMode ?? {},
2762
+ minDescriptionLength: config.minDescriptionLength ?? 20,
2763
+ dashboardUrl: config.dashboardUrl ?? "",
2764
+ responseSlaLabel: config.responseSlaLabel ?? "",
2765
+ featureRequestCard: config.featureRequestCard ?? true,
2766
+ featureRequestLabel: config.featureRequestLabel || "Feature request",
2767
+ featureRequestDescription: config.featureRequestDescription || "Suggest something new \u2014 even rough ideas help us prioritise",
2768
+ avoidSelectors: config.avoidSelectors ?? [],
2769
+ categories: config.categories ?? [],
2770
+ accent: config.accent ?? "",
2771
+ accentText: config.accentText ?? ""
2772
+ };
2773
+ this.callbacks = callbacks;
2774
+ this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
2775
+ this.host = document.createElement("div");
2776
+ this.host.id = "mushi-mushi-widget";
2777
+ this.shadow = this.host.attachShadow({ mode: "closed" });
2524
2778
  }
2779
+ sdkVersion;
2780
+ host;
2781
+ shadow;
2782
+ config;
2783
+ callbacks;
2784
+ locale;
2785
+ isOpen = false;
2786
+ step = "category";
2525
2787
  /**
2526
- * Returns true when a DOM element matching `hideOnSelector` is currently
2527
- * present in the host document. Used by both the trigger and the banner
2528
- * so a single selector consistently hides ALL SDK-injected launcher
2529
- * surfaces. Invalid selectors are swallowed silently (non-fatal).
2788
+ * The selected category id. May be a built-in `MushiReportCategory` or a
2789
+ * custom id from `config.categories`. Cast to `MushiReportCategory` only
2790
+ * after resolving through `resolveBaseCategory()`.
2530
2791
  */
2531
- isSuppressedByHost() {
2532
- if (!this.config.hideOnSelector || typeof document === "undefined") return false;
2533
- try {
2534
- return Boolean(document.querySelector(this.config.hideOnSelector));
2535
- } catch {
2536
- return false;
2537
- }
2538
- }
2792
+ selectedCategory = null;
2793
+ selectedIntent = null;
2539
2794
  /**
2540
- * Returns a snapshot of the widget's host-layer health for use in
2541
- * `Mushi.diagnose()`. Callers check this to know whether the widget
2542
- * could ever block host-app UI without opening a browser devtools.
2795
+ * True when the user took the "Feature request" shortcut. We track this
2796
+ * separately from `selectedCategory='other'` so the Back button on the
2797
+ * details step jumps straight back to the category picker instead of
2798
+ * landing on the intent picker the user explicitly skipped.
2543
2799
  */
2544
- getWidgetDiagnostics() {
2545
- const s = this.host.style;
2546
- const widgetHostPointerSafe = s.pointerEvents === "none" && (s.width === "0" || s.width === "0px") && (s.height === "0" || s.height === "0px");
2547
- const widgetHostBounds = this.host.isConnected ? { width: this.host.offsetWidth, height: this.host.offsetHeight } : null;
2548
- const widgetSuppressed = this.isSuppressedByHost() || this.isRouteHidden() || !this.triggerVisible;
2549
- const bannerRendered = this.config.trigger === "banner" && !this.bannerDismissed && !this.isSuppressedByHost() && !this.isRouteHidden() && this.triggerVisible;
2550
- return { widgetHostPointerSafe, widgetHostBounds, widgetSuppressed, bannerRendered };
2551
- }
2552
- syncAttachedLaunchers() {
2553
- this.attachedLaunchers.forEach((cleanup) => cleanup());
2554
- this.attachedLaunchers = [];
2555
- if (this.config.trigger !== "attach" || !this.config.attachToSelector) return;
2556
- if (typeof document === "undefined") return;
2557
- this.attachedLaunchers.push(this.attachTo(this.config.attachToSelector));
2558
- }
2559
- syncSmartHide() {
2560
- this.smartHideCleanup?.();
2561
- this.smartHideCleanup = null;
2562
- this.triggerShrunk = false;
2563
- this.triggerHiddenByScroll = false;
2564
- if (!this.config.smartHide || typeof window === "undefined") return;
2565
- const smart = this.config.smartHide === true ? { onScroll: "shrink", onIdleMs: 900 } : this.config.smartHide;
2566
- if (!smart.onScroll) return;
2567
- const onScroll = () => {
2568
- if (smart.onScroll === "hide") {
2569
- this.triggerHiddenByScroll = true;
2570
- } else {
2571
- this.triggerShrunk = true;
2572
- }
2573
- this.render();
2574
- if (this.smartHideTimer !== null) clearTimeout(this.smartHideTimer);
2575
- this.smartHideTimer = setTimeout(() => {
2576
- this.triggerHiddenByScroll = false;
2577
- this.triggerShrunk = false;
2578
- this.render();
2579
- }, smart.onIdleMs ?? 900);
2580
- };
2581
- window.addEventListener("scroll", onScroll, { passive: true });
2582
- this.smartHideCleanup = () => window.removeEventListener("scroll", onScroll);
2583
- }
2584
- shouldRenderTrigger() {
2585
- if (!this.triggerVisible) return false;
2586
- if (this.triggerHiddenByScroll) return false;
2587
- if (this.config.trigger === "manual" || this.config.trigger === "hidden" || this.config.trigger === "attach" || this.config.trigger === "banner") {
2588
- return false;
2589
- }
2590
- if (this.isMobileSmartHidden()) return false;
2591
- if (this.isRouteHidden()) return false;
2592
- if (this.isSuppressedByHost()) return false;
2593
- const action = this.config.environments[this.detectEnvironment()];
2594
- return action !== "never" && action !== "manual";
2800
+ viaFeatureRequest = false;
2801
+ screenshotAttached = false;
2802
+ screenshotCapturing = false;
2803
+ screenshotError = false;
2804
+ allowScreenshotRemove = true;
2805
+ elementSelected = false;
2806
+ elementCapturing = false;
2807
+ submitting = false;
2808
+ /** Hint element injected outside the shadow DOM during element selection. */
2809
+ selectorHint = null;
2810
+ triggerVisible = true;
2811
+ triggerShrunk = false;
2812
+ triggerHiddenByScroll = false;
2813
+ /** Milliseconds since mount — used for the 30s first-time nudge gate. */
2814
+ mountedAt = null;
2815
+ nudgeShown = false;
2816
+ nudgeEl = null;
2817
+ nudgeTimer = null;
2818
+ sdkFreshness = null;
2819
+ reporterReports = [];
2820
+ featureBoard = [];
2821
+ reporterComments = [];
2822
+ selectedReportId = null;
2823
+ reporterLoading = false;
2824
+ reporterError = null;
2825
+ attachedLaunchers = [];
2826
+ smartHideCleanup = null;
2827
+ smartHideTimer = null;
2828
+ /** Captured at the moment of submit so the success ledger metadata
2829
+ * ("REPORT · 14:23:07 JST") doesn't drift while the success step
2830
+ * is on screen. */
2831
+ submittedAt = null;
2832
+ /** Pending success-state + auto-close timers. Tracked so destroy()
2833
+ * can clear them — otherwise a host that unmounts mid-submit leaks
2834
+ * this MushiWidget reference (and re-renders into a detached shadow
2835
+ * root) for up to ~3.3s after destroy. */
2836
+ successTimer = null;
2837
+ autoCloseTimer = null;
2838
+ rewardsState = null;
2839
+ leaderboardEntries = null;
2840
+ leaderboardLoading = false;
2841
+ /** Server-confirmed id for the just-submitted report. Surfaces in
2842
+ * the success step as a copyable receipt + optional deep link to
2843
+ * the Mushi console (when `dashboardUrl` is configured). Cleared
2844
+ * on every new `open()` so a re-opened widget never reuses a
2845
+ * stale id from the previous session. */
2846
+ lastReportId = null;
2847
+ /** True when the just-submitted report was queued offline (no
2848
+ * network, or the API errored and went into the retry queue).
2849
+ * Drives a different success copy so the user knows the report
2850
+ * hasn't actually reached the console yet. */
2851
+ lastSubmitQueuedOffline = false;
2852
+ /** Whether the user has clicked ✕ on the header banner this session. */
2853
+ bannerDismissed = false;
2854
+ /** Persisted FAB position when draggable is enabled. */
2855
+ fabPos = null;
2856
+ /** Cleanup fn for visualViewport keyboard listener. */
2857
+ vvCleanup = null;
2858
+ /** Mushi tester session JWT — set after in-widget sign-in or by mushi.ts. */
2859
+ testerJwt = null;
2860
+ /** Tester identity (public_handle, display_name). */
2861
+ testerInfo = null;
2862
+ /** Cross-app reports for the signed-in tester. */
2863
+ crossAppReports = null;
2864
+ crossAppLoading = false;
2865
+ /** Global leaderboard entries (from mushi_testers, not org-scoped). */
2866
+ globalLeaderboard = null;
2867
+ globalLeaderboardLoading = false;
2868
+ /** Reputation for the signed-in tester. */
2869
+ testerReputation = null;
2870
+ /** Whether an in-widget magic-link email was just sent. */
2871
+ magicLinkSent = false;
2872
+ magicLinkEmail = "";
2873
+ magicLinkError = "";
2874
+ magicLinkSending = false;
2875
+ // double-submit guard
2876
+ // ─── Assistant tab (P5) ──────────────────────────────────────────
2877
+ assistantTurns = [];
2878
+ assistantThreadId = null;
2879
+ assistantSending = false;
2880
+ assistantError = null;
2881
+ mount() {
2882
+ if (this.host.isConnected) return;
2883
+ this.syncHostChromeState();
2884
+ document.body.appendChild(this.host);
2885
+ this.syncAttachedLaunchers();
2886
+ this.syncSmartHide();
2887
+ this.render();
2888
+ this.mountedAt = Date.now();
2595
2889
  }
2596
- /** Height of the banner in px — kept in sync with the CSS `.mushi-banner` height (36px). */
2597
- static BANNER_HEIGHT = 36;
2598
- /** CSS property applied to document.body so host-app content doesn't slide under the banner. */
2599
- static BODY_NUDGE_PROP = "--mushi-banner-offset";
2600
- applyBodyNudge(position) {
2601
- const h = `${_MushiWidget.BANNER_HEIGHT}px`;
2602
- if (position === "top") {
2603
- document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
2604
- if (!document.body.style.paddingTop) {
2605
- document.body.style.paddingTop = h;
2606
- document.body.dataset.mushiBannerNudged = "top";
2607
- }
2608
- } else {
2609
- document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
2610
- if (!document.body.style.paddingBottom) {
2611
- document.body.style.paddingBottom = h;
2612
- document.body.dataset.mushiBannerNudged = "bottom";
2613
- }
2614
- }
2890
+ getIsMounted() {
2891
+ return this.host.isConnected;
2615
2892
  }
2616
- removeBodyNudge() {
2617
- document.documentElement.style.removeProperty(_MushiWidget.BODY_NUDGE_PROP);
2618
- const nudged = document.body.dataset.mushiBannerNudged;
2619
- if (nudged === "top") {
2620
- document.body.style.paddingTop = "";
2621
- delete document.body.dataset.mushiBannerNudged;
2622
- } else if (nudged === "bottom") {
2623
- document.body.style.paddingBottom = "";
2624
- delete document.body.dataset.mushiBannerNudged;
2625
- }
2893
+ updateConfig(config = {}) {
2894
+ this.config = {
2895
+ ...this.config,
2896
+ ...config.position ? { position: config.position } : {},
2897
+ ...config.anchor !== void 0 ? { anchor: config.anchor } : {},
2898
+ ...config.theme ? { theme: config.theme } : {},
2899
+ ...config.triggerText !== void 0 ? { triggerText: config.triggerText || "\u{1F41B}" } : {},
2900
+ ...config.expandedTitle !== void 0 ? { expandedTitle: config.expandedTitle } : {},
2901
+ ...config.mode ? { mode: config.mode } : {},
2902
+ ...config.locale ? { locale: config.locale } : {},
2903
+ ...config.zIndex !== void 0 ? { zIndex: config.zIndex } : {},
2904
+ ...config.trigger ? { trigger: config.trigger } : {},
2905
+ ...config.attachToSelector !== void 0 ? { attachToSelector: config.attachToSelector } : {},
2906
+ ...config.inset !== void 0 ? { inset: config.inset } : {},
2907
+ ...config.respectSafeArea !== void 0 ? { respectSafeArea: config.respectSafeArea } : {},
2908
+ ...config.hideOnSelector !== void 0 ? { hideOnSelector: config.hideOnSelector } : {},
2909
+ ...config.hideOnRoutes !== void 0 ? { hideOnRoutes: config.hideOnRoutes } : {},
2910
+ ...config.environments !== void 0 ? { environments: config.environments } : {},
2911
+ ...config.smartHide !== void 0 ? { smartHide: config.smartHide } : {},
2912
+ ...config.draggable !== void 0 ? { draggable: config.draggable } : {},
2913
+ ...config.brandFooter !== void 0 ? { brandFooter: config.brandFooter } : {},
2914
+ ...config.outdatedBanner !== void 0 ? { outdatedBanner: config.outdatedBanner } : {},
2915
+ ...config.betaMode !== void 0 ? { betaMode: config.betaMode } : {},
2916
+ ...config.minDescriptionLength !== void 0 ? { minDescriptionLength: config.minDescriptionLength } : {},
2917
+ ...config.dashboardUrl !== void 0 ? { dashboardUrl: config.dashboardUrl } : {},
2918
+ ...config.responseSlaLabel !== void 0 ? { responseSlaLabel: config.responseSlaLabel } : {},
2919
+ ...config.featureRequestCard !== void 0 ? { featureRequestCard: config.featureRequestCard } : {},
2920
+ ...config.featureRequestLabel !== void 0 ? { featureRequestLabel: config.featureRequestLabel || "Feature request" } : {},
2921
+ ...config.featureRequestDescription !== void 0 ? { featureRequestDescription: config.featureRequestDescription || "Suggest something new \u2014 even rough ideas help us prioritise" } : {},
2922
+ // Runtime/dashboard config delivers bannerMessage/bannerLabel via
2923
+ // mergeRuntimeConfig → bannerConfig. The widget is constructed before
2924
+ // that fetch resolves, so this pass-through is what makes server-driven
2925
+ // banner copy actually render.
2926
+ ...config.bannerConfig !== void 0 ? { bannerConfig: config.bannerConfig } : {},
2927
+ ...config.categories !== void 0 ? { categories: config.categories } : {}
2928
+ };
2929
+ this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
2930
+ if (this.host.isConnected) this.syncHostChromeState();
2931
+ this.syncAttachedLaunchers();
2932
+ this.syncSmartHide();
2933
+ this.render();
2626
2934
  }
2627
- renderBanner() {
2628
- if (this.config.trigger !== "banner") return;
2629
- if (this.bannerDismissed) {
2630
- this.removeBodyNudge();
2631
- return;
2632
- }
2633
- if (!this.triggerVisible) {
2634
- this.removeBodyNudge();
2635
- return;
2636
- }
2637
- if (this.isRouteHidden()) {
2638
- this.removeBodyNudge();
2639
- return;
2640
- }
2641
- if (this.isSuppressedByHost()) {
2642
- this.removeBodyNudge();
2643
- return;
2644
- }
2645
- const bc = this.config.bannerConfig ?? {};
2646
- const variant = bc.variant ?? "brand";
2647
- const position = bc.position ?? "top";
2648
- const message = bc.message?.trim() ?? "";
2649
- const richLayout = message.length > 0;
2650
- const bugLabel = bc.bugCta ?? "\u{1F41B} Report a bug";
2651
- const showFeat = bc.featureCta !== false;
2652
- const featLabel = bc.featureCtaLabel ?? "\u2728 Request feature";
2653
- const zIdx = bc.zIndex ?? (this.config.zIndex ?? 99999) - 1;
2654
- const banner = document.createElement("div");
2655
- banner.className = `mushi-banner ${variant} ${position}${richLayout ? " mushi-banner--rich" : ""}`;
2656
- banner.style.setProperty("--mushi-banner-z", String(zIdx));
2657
- banner.setAttribute("role", "banner");
2658
- const dismissBtn = document.createElement("button");
2659
- dismissBtn.className = "mushi-banner-dismiss";
2660
- dismissBtn.textContent = "\u2715";
2661
- dismissBtn.setAttribute("aria-label", "Dismiss feedback banner");
2662
- dismissBtn.addEventListener("click", () => {
2663
- this.bannerDismissed = true;
2664
- this.removeBodyNudge();
2665
- this.render();
2666
- });
2667
- if (richLayout) {
2668
- const body = document.createElement("div");
2669
- body.className = "mushi-banner-body";
2670
- const labelText = bc.label === false ? null : bc.label ?? "Beta";
2671
- if (labelText) {
2672
- const pill = document.createElement("span");
2673
- pill.className = "mushi-banner-pill";
2674
- pill.textContent = labelText;
2675
- body.appendChild(pill);
2676
- }
2677
- const msg = document.createElement("span");
2678
- msg.className = "mushi-banner-message";
2679
- msg.textContent = message;
2680
- body.appendChild(msg);
2681
- banner.appendChild(body);
2682
- const nav = document.createElement("nav");
2683
- nav.className = "mushi-banner-actions";
2684
- nav.setAttribute("aria-label", "Feedback banner actions");
2685
- const appendDivider = (extra = false) => {
2686
- const sep = document.createElement("span");
2687
- sep.className = `mushi-banner-divider${extra ? " mushi-banner-extra" : ""}`;
2688
- sep.setAttribute("aria-hidden", "true");
2689
- sep.textContent = "|";
2690
- nav.appendChild(sep);
2691
- };
2692
- const appendAction = (label, onClick, extra = false) => {
2693
- const btn = document.createElement("button");
2694
- btn.type = "button";
2695
- btn.className = `mushi-banner-link${extra ? " mushi-banner-extra" : ""}`;
2696
- btn.textContent = label;
2697
- btn.addEventListener("click", onClick);
2698
- nav.appendChild(btn);
2699
- };
2700
- appendAction(bugLabel, () => this.open());
2701
- if (showFeat) {
2702
- appendDivider(true);
2703
- appendAction(featLabel, () => this.open({ featureRequest: true }), true);
2704
- }
2705
- for (const link of bc.links ?? []) {
2706
- const linkLabel = link.label?.trim();
2707
- if (!linkLabel) continue;
2708
- const href = link.href && (/^https?:\/\//i.test(link.href) || link.href.startsWith("/")) ? link.href : void 0;
2709
- appendDivider(true);
2710
- if (href) {
2711
- const anchor = document.createElement("a");
2712
- anchor.className = "mushi-banner-link mushi-banner-extra";
2713
- anchor.href = href;
2714
- anchor.textContent = linkLabel;
2715
- anchor.target = "_blank";
2716
- anchor.rel = "noopener noreferrer";
2717
- nav.appendChild(anchor);
2718
- } else {
2719
- appendAction(linkLabel, () => {
2720
- if (link.featureRequest) this.open({ featureRequest: true });
2721
- else this.open();
2722
- }, true);
2723
- }
2724
- }
2725
- banner.appendChild(nav);
2726
- banner.appendChild(dismissBtn);
2727
- } else {
2728
- const bugBtn = document.createElement("button");
2729
- bugBtn.className = "mushi-banner-btn";
2730
- bugBtn.textContent = bugLabel;
2731
- bugBtn.addEventListener("click", () => this.open());
2732
- banner.appendChild(bugBtn);
2733
- if (showFeat) {
2734
- const featBtn = document.createElement("button");
2735
- featBtn.className = "mushi-banner-btn";
2736
- featBtn.textContent = featLabel;
2737
- featBtn.addEventListener("click", () => this.open({ featureRequest: true }));
2738
- banner.appendChild(featBtn);
2739
- }
2740
- banner.appendChild(dismissBtn);
2741
- }
2742
- this.shadow.appendChild(banner);
2743
- this.applyBodyNudge(position);
2935
+ // ─── Custom category helpers ──────────────────────────────────────────────
2936
+ /** Find a custom category entry by id. Returns undefined for built-in ids. */
2937
+ resolveCustomCategory(id) {
2938
+ return this.config.categories?.find((c) => c.id === id);
2744
2939
  }
2745
- effectiveTrigger() {
2746
- if (!this.config.smartHide || typeof window === "undefined") return this.config.trigger;
2747
- const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
2748
- if (window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "edge-tab") {
2749
- return "edge-tab";
2750
- }
2751
- return this.config.trigger;
2940
+ /**
2941
+ * Map a (possibly custom) category id to the built-in `MushiReportCategory`
2942
+ * used for the report wire format. Falls back to `'other'`.
2943
+ */
2944
+ resolveBaseCategory(id) {
2945
+ const BUILTIN = ["bug", "slow", "visual", "confusing", "other"];
2946
+ if (BUILTIN.includes(id)) return id;
2947
+ const custom = this.resolveCustomCategory(id);
2948
+ return custom?.baseCategory ?? "other";
2752
2949
  }
2753
- isMobileSmartHidden() {
2754
- if (!this.config.smartHide || typeof window === "undefined") return false;
2755
- const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
2756
- return window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "hide";
2950
+ /** Icon for the selected category — custom entry's icon or built-in emoji. */
2951
+ categoryIcon(id) {
2952
+ const custom = this.resolveCustomCategory(id);
2953
+ if (custom?.icon) return custom.icon;
2954
+ return CATEGORY_ICONS[id] ?? "\u{1F4AC}";
2757
2955
  }
2758
- detectEnvironment() {
2759
- const host = typeof location !== "undefined" ? location.hostname : "";
2760
- if (host === "localhost" || host === "127.0.0.1" || host.endsWith(".local")) return "development";
2761
- if (/\b(staging|stage|preview|dev)\b/i.test(host)) return "staging";
2762
- return "production";
2956
+ /** Label for the selected category — custom entry label or built-in i18n string. */
2957
+ categoryLabel(id) {
2958
+ const custom = this.resolveCustomCategory(id);
2959
+ if (custom) return custom.label;
2960
+ const t = this.locale;
2961
+ return t.step1.categories[id] ?? id;
2962
+ }
2963
+ // ─── Open / close ─────────────────────────────────────────────────────────
2964
+ open(options) {
2965
+ if (this.isOpen) return;
2966
+ this.isOpen = true;
2967
+ this.screenshotAttached = false;
2968
+ this.screenshotCapturing = false;
2969
+ this.screenshotError = false;
2970
+ this.elementSelected = false;
2971
+ this.elementCapturing = false;
2972
+ this.submitting = false;
2973
+ this.submittedAt = null;
2974
+ this.removeSelectorHint();
2975
+ this.lastReportId = null;
2976
+ this.lastSubmitQueuedOffline = false;
2977
+ this.viaFeatureRequest = false;
2978
+ if (options?.featureRequest) {
2979
+ this.selectedCategory = "other";
2980
+ this.selectedIntent = FEATURE_REQUEST_INTENT;
2981
+ this.viaFeatureRequest = true;
2982
+ this.step = "details";
2983
+ } else if (options?.category) {
2984
+ const custom = this.resolveCustomCategory(options.category);
2985
+ const builtIn = ["bug", "slow", "visual", "confusing", "other"];
2986
+ const isKnown = builtIn.includes(options.category) || custom !== void 0;
2987
+ if (!isKnown) {
2988
+ this.selectedCategory = null;
2989
+ this.selectedIntent = null;
2990
+ this.step = "category";
2991
+ } else {
2992
+ this.selectedCategory = options.category;
2993
+ this.selectedIntent = null;
2994
+ this.step = custom && (!custom.intents || custom.intents.length === 0) ? "details" : "intent";
2995
+ }
2996
+ } else {
2997
+ this.selectedCategory = null;
2998
+ this.selectedIntent = null;
2999
+ this.step = "category";
3000
+ }
3001
+ this.render();
3002
+ this.callbacks.onOpen();
2763
3003
  }
2764
- isRouteHidden() {
2765
- if (!this.config.hideOnRoutes.length || typeof location === "undefined") return false;
2766
- return this.config.hideOnRoutes.some((route) => location.pathname.includes(route));
3004
+ close() {
3005
+ if (!this.isOpen) return;
3006
+ this.isOpen = false;
3007
+ this.render();
3008
+ this.callbacks.onClose();
2767
3009
  }
2768
- getTheme() {
2769
- const t = this.config.theme;
2770
- if (t === "light" || t === "dark") return t;
2771
- if (t === "inherit") {
2772
- const root = document.documentElement;
2773
- const colorScheme = root.getAttribute("data-color-scheme") || root.getAttribute("data-theme") || root.getAttribute("color-scheme") || "";
2774
- if (/dark/i.test(colorScheme)) return "dark";
2775
- if (/light/i.test(colorScheme)) return "light";
2776
- if (root.classList.contains("dark")) return "dark";
2777
- if (root.classList.contains("light")) return "light";
2778
- try {
2779
- const bg = getComputedStyle(root).backgroundColor;
2780
- const m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
2781
- if (m) {
2782
- const L = 0.299 * +m[1] + 0.587 * +m[2] + 0.114 * +m[3];
2783
- return L < 128 ? "dark" : "light";
2784
- }
2785
- } catch {
2786
- }
3010
+ /** Open the panel directly on the assistant ("Ask") tab. */
3011
+ openAssistantTab() {
3012
+ if (!this.callbacks.assistantEnabled) {
3013
+ this.open();
3014
+ return;
2787
3015
  }
2788
- if (typeof window !== "undefined" && window.matchMedia("(prefers-color-scheme: dark)").matches) {
2789
- return "dark";
3016
+ if (!this.isOpen) {
3017
+ this.isOpen = true;
3018
+ this.callbacks.onOpen();
2790
3019
  }
2791
- return "light";
2792
- }
2793
- render() {
2794
- const theme = this.getTheme();
2795
- const pos = this.config.position;
2796
- const t = this.locale;
2797
- this.shadow.innerHTML = "";
2798
- const style = document.createElement("style");
2799
- style.textContent = getWidgetStyles(theme, this.config.accent ?? "", this.config.accentText ?? "");
2800
- this.shadow.appendChild(style);
2801
- this.renderBanner();
2802
- if (this.shouldRenderTrigger()) {
2803
- const effectiveTrigger = this.effectiveTrigger();
2804
- const trigger = document.createElement("button");
2805
- trigger.className = `mushi-trigger ${pos}${effectiveTrigger === "edge-tab" ? " edge-tab" : ""}${this.triggerShrunk ? " shrunk" : ""}`;
2806
- trigger.textContent = this.config.triggerText;
2807
- trigger.setAttribute("aria-label", t.widget.trigger);
2808
- trigger.setAttribute("aria-haspopup", "dialog");
2809
- trigger.setAttribute("aria-expanded", String(this.isOpen));
2810
- trigger.style.zIndex = String(this.config.zIndex);
2811
- this.applyInsetVars(trigger);
2812
- if (this.fabPos) {
2813
- trigger.style.setProperty("--mushi-drag-x", `${this.fabPos.x}px`);
2814
- trigger.style.setProperty("--mushi-drag-y", `${this.fabPos.y}px`);
2815
- trigger.style.setProperty("--mushi-drag-active", "1");
2816
- }
2817
- trigger.addEventListener("click", () => {
2818
- this.removeNudge();
2819
- if (this.isOpen) this.close();
2820
- else this.open();
2821
- });
2822
- trigger.addEventListener("mouseenter", () => {
2823
- const onPageMs = this.mountedAt ? Date.now() - this.mountedAt : 0;
2824
- if (!this.nudgeShown && !this.isOpen && onPageMs >= 3e4) {
2825
- this.showNudge();
2826
- }
2827
- });
2828
- trigger.addEventListener("mouseleave", () => {
2829
- if (this.nudgeEl) {
2830
- if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
2831
- this.nudgeTimer = setTimeout(() => this.removeNudge(), 2e3);
2832
- }
2833
- });
2834
- trigger.addEventListener("keydown", (e) => {
2835
- const draggableConfig = this.config.draggable;
2836
- if (!draggableConfig) return;
2837
- const STEP = 8;
2838
- const axis = typeof draggableConfig === "object" ? draggableConfig.axis ?? "both" : "both";
2839
- let dx = 0, dy = 0;
2840
- if (axis !== "y") {
2841
- if (e.key === "ArrowLeft") dx = -STEP;
2842
- else if (e.key === "ArrowRight") dx = STEP;
2843
- }
2844
- if (axis !== "x") {
2845
- if (e.key === "ArrowUp") dy = -STEP;
2846
- else if (e.key === "ArrowDown") dy = STEP;
2847
- }
2848
- if (dx !== 0 || dy !== 0) {
2849
- e.preventDefault();
2850
- const cur = this.fabPos ?? { x: 0, y: 0 };
2851
- this.moveFab(trigger, cur.x + dx, cur.y + dy, false);
3020
+ this.step = "assistant";
3021
+ this.assistantError = null;
3022
+ this.render();
3023
+ setTimeout(() => {
3024
+ this.shadow.querySelector(".mushi-assistant-input")?.focus();
3025
+ }, 0);
3026
+ }
3027
+ /** Send one assistant turn and re-render as the reply streams back. */
3028
+ async sendAssistantMessage(message) {
3029
+ const text = message.trim();
3030
+ if (!text || this.assistantSending || !this.callbacks.onAssistantAsk) return;
3031
+ this.assistantSending = true;
3032
+ this.assistantError = null;
3033
+ this.assistantTurns.push({ role: "user", text });
3034
+ this.render();
3035
+ try {
3036
+ const reply = await this.callbacks.onAssistantAsk(text, this.assistantThreadId);
3037
+ if (reply) {
3038
+ if (reply.threadId) this.assistantThreadId = reply.threadId;
3039
+ if (reply.kind === "clarify") {
3040
+ this.assistantTurns.push({
3041
+ role: "assistant",
3042
+ text: reply.question ?? "Could you tell me a bit more?",
3043
+ ...reply.options && reply.options.length ? { options: reply.options } : {}
3044
+ });
3045
+ } else {
3046
+ this.assistantTurns.push({ role: "assistant", text: reply.text ?? "\u2026" });
2852
3047
  }
2853
- });
2854
- if (this.config.draggable) {
2855
- this.attachDragHandlers(trigger);
3048
+ } else {
3049
+ this.assistantError = "No response \u2014 please try again.";
2856
3050
  }
2857
- this.shadow.appendChild(trigger);
2858
- }
2859
- const panel = document.createElement("div");
2860
- panel.className = `mushi-panel ${pos}${this.isOpen ? " open" : " closed"}`;
2861
- panel.setAttribute("role", "dialog");
2862
- panel.setAttribute("aria-modal", "true");
2863
- panel.setAttribute("aria-label", t.widget.title);
2864
- panel.style.zIndex = String(this.config.zIndex + 1);
2865
- this.applyInsetVars(panel);
2866
- if (this.isOpen) {
2867
- panel.innerHTML = `${this.renderOutdatedBanner()}${this.renderStep()}${this.renderBrandFooter()}`;
2868
- this.shadow.appendChild(panel);
2869
- this.attachHandlers(panel);
2870
- this.trapFocus(panel);
2871
- this.attachViewportHandlers(panel);
2872
- } else {
2873
- this.teardownViewportHandlers();
3051
+ } catch {
3052
+ this.assistantError = "Something went wrong. Please try again.";
3053
+ } finally {
3054
+ this.assistantSending = false;
3055
+ this.render();
3056
+ setTimeout(() => {
3057
+ const log = this.shadow.querySelector(".mushi-assistant-log");
3058
+ if (log) log.scrollTop = log.scrollHeight;
3059
+ }, 0);
2874
3060
  }
2875
3061
  }
2876
3062
  /**
2877
- * Queries each `avoidSelectors` element in the host document and returns
2878
- * the minimum top-offset in px so that a top-anchored element clears all
2879
- * of them by `gap` pixels. Returns `null` when no selectors are provided
2880
- * or no matching elements have a non-zero bounding rect.
2881
- *
2882
- * Runs in the host document (not shadow DOM) so it can reach fixed headers,
2883
- * sticky nav bars, and sign-in CTAs.
3063
+ * Briefly highlight the trigger button (a soft pulse + tooltip) without
3064
+ * opening the full reporter panel. Use for first-session welcome nudges
3065
+ * and other "by the way, this exists" prompts where forcing the panel
3066
+ * open would feel aggressive. Honours `position: 'none'` (no-op when
3067
+ * the trigger button is hidden).
2884
3068
  */
2885
- computeAvoidTopPx(gap = 8) {
2886
- const sels = this.config.avoidSelectors;
2887
- if (!sels?.length) return null;
2888
- let maxBottom = 0;
2889
- for (const sel of sels) {
2890
- try {
2891
- const el = document.querySelector(sel);
2892
- if (!el) continue;
2893
- const r = el.getBoundingClientRect();
2894
- if (r.bottom > maxBottom && r.width > 0 && r.height > 0) {
2895
- maxBottom = r.bottom;
2896
- }
2897
- } catch {
2898
- }
2899
- }
2900
- return maxBottom > 0 ? Math.ceil(maxBottom) + gap : null;
3069
+ pulseTrigger() {
3070
+ if (this.isOpen) return;
3071
+ const trigger = this.shadow.querySelector(".mushi-trigger");
3072
+ if (!trigger) return;
3073
+ trigger.classList.add("mushi-trigger-pulse");
3074
+ window.setTimeout(() => {
3075
+ trigger.classList.remove("mushi-trigger-pulse");
3076
+ }, 2400);
2901
3077
  }
2902
- applyInsetVars(el) {
2903
- const { anchor } = this.config;
2904
- if (anchor && Object.keys(anchor).length > 0) {
2905
- ["top", "right", "bottom", "left"].forEach((edge) => {
2906
- const value = anchor[edge];
2907
- if (value !== void 0) el.style.setProperty(`--mushi-${edge}`, value);
2908
- });
2909
- el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
3078
+ getIsOpen() {
3079
+ return this.isOpen;
3080
+ }
3081
+ showTrigger() {
3082
+ this.triggerVisible = true;
3083
+ this.render();
3084
+ }
3085
+ hideTrigger() {
3086
+ this.triggerVisible = false;
3087
+ this.render();
3088
+ }
3089
+ setTrigger(trigger) {
3090
+ this.updateConfig({ trigger });
3091
+ }
3092
+ attachTo(selectorOrElement, options = {}) {
3093
+ const elements = typeof selectorOrElement === "string" ? Array.from(document.querySelectorAll(selectorOrElement)) : [selectorOrElement];
3094
+ const cleanups = elements.map((el) => {
3095
+ const onClick = (event) => {
3096
+ event.preventDefault();
3097
+ this.updateConfig(options);
3098
+ this.open();
3099
+ };
3100
+ el.addEventListener("click", onClick);
3101
+ return () => el.removeEventListener("click", onClick);
3102
+ });
3103
+ return () => cleanups.forEach((cleanup) => cleanup());
3104
+ }
3105
+ setScreenshotAttached(attached) {
3106
+ this.screenshotAttached = attached;
3107
+ if (this.isOpen) this.render();
3108
+ }
3109
+ setAllowScreenshotRemove(allow) {
3110
+ this.allowScreenshotRemove = allow;
3111
+ if (this.isOpen) this.render();
3112
+ }
3113
+ setElementSelected(selected) {
3114
+ this.elementSelected = selected;
3115
+ this.elementCapturing = false;
3116
+ this.removeSelectorHint();
3117
+ if (this.isOpen) this.render();
3118
+ }
3119
+ setScreenshotCapturing(capturing) {
3120
+ this.screenshotCapturing = capturing;
3121
+ this.screenshotError = false;
3122
+ if (this.isOpen) this.render();
3123
+ }
3124
+ setScreenshotError(failed) {
3125
+ this.screenshotError = failed;
3126
+ this.screenshotCapturing = false;
3127
+ if (this.isOpen) this.render();
3128
+ }
3129
+ setElementCapturing(capturing) {
3130
+ this.elementCapturing = capturing;
3131
+ if (capturing) {
3132
+ this.showSelectorHint();
2910
3133
  } else {
2911
- const { inset } = this.config;
2912
- if (!this.config.respectSafeArea) {
2913
- ["top", "right", "bottom", "left"].forEach((edge) => {
2914
- if (inset[edge] === void 0) el.style.setProperty(`--mushi-${edge}`, "24px");
2915
- });
2916
- }
2917
- ["top", "right", "bottom", "left"].forEach((edge) => {
2918
- const value = inset[edge];
2919
- if (value === void 0) return;
2920
- el.style.setProperty(`--mushi-${edge}`, value === "auto" ? "auto" : `${value}px`);
2921
- });
2922
- el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
2923
- }
2924
- const isTopAnchored = anchor?.top !== void 0 || this.config.position?.startsWith("top") || !this.config.position && !anchor?.bottom;
2925
- if (isTopAnchored) {
2926
- const avoidPx = this.computeAvoidTopPx();
2927
- if (avoidPx !== null) {
2928
- el.style.setProperty("--mushi-top", `${avoidPx}px`);
2929
- }
3134
+ this.removeSelectorHint();
2930
3135
  }
3136
+ if (this.isOpen) this.render();
3137
+ }
3138
+ /** Hide the widget panel (but keep the host element) during element selection
3139
+ * so the user can click any element on the page without the panel
3140
+ * intercepting the event. */
3141
+ hidePanel() {
3142
+ const panel = this.shadow.querySelector(".mushi-panel");
3143
+ if (panel) panel.style.display = "none";
3144
+ }
3145
+ showPanel() {
3146
+ const panel = this.shadow.querySelector(".mushi-panel");
3147
+ if (panel) panel.style.display = "";
3148
+ }
3149
+ showSelectorHint() {
3150
+ this.removeSelectorHint();
3151
+ const hint = document.createElement("div");
3152
+ hint.id = "mushi-selector-hint";
3153
+ hint.setAttribute("role", "status");
3154
+ hint.setAttribute("aria-live", "polite");
3155
+ hint.style.cssText = `
3156
+ position: fixed;
3157
+ bottom: 24px;
3158
+ left: 50%;
3159
+ transform: translateX(-50%);
3160
+ z-index: 2147483646;
3161
+ background: rgba(17,17,17,0.92);
3162
+ color: #fff;
3163
+ font-family: ui-monospace, SFMono-Regular, monospace;
3164
+ font-size: 12px;
3165
+ letter-spacing: 0.04em;
3166
+ padding: 8px 16px;
3167
+ border-radius: 20px;
3168
+ pointer-events: none;
3169
+ white-space: nowrap;
3170
+ backdrop-filter: blur(4px);
3171
+ box-shadow: 0 2px 12px rgba(0,0,0,0.35);
3172
+ `;
3173
+ hint.textContent = this.locale.step3.elementSelectorHint;
3174
+ document.body.appendChild(hint);
3175
+ this.selectorHint = hint;
2931
3176
  }
2932
- // ─── Draggable FAB ──────────────────────────────────────────────────────────
2933
- /** Storage key for the FAB position, scoped to projectId when available. */
2934
- fabStorageKey() {
2935
- const id = this.config["projectId"] ?? "";
2936
- return `mushi_fab_pos${id ? `_${id}` : ""}`;
3177
+ removeSelectorHint() {
3178
+ this.selectorHint?.remove();
3179
+ this.selectorHint = null;
3180
+ document.getElementById("mushi-selector-hint")?.remove();
2937
3181
  }
2938
- /** Move the FAB to the given translated offset (relative to the inset origin),
2939
- * clamping inside viewport safe area, and optionally snap to nearest edge.
2940
- *
2941
- * The FAB's CSS anchor can be any corner (bottom-right, bottom-left, …) so we
2942
- * must derive the *base* position (CSS anchor with zero drag offset) to compute
2943
- * correct clamp bounds and snap targets. We do this by subtracting the
2944
- * already-applied drag offset from the live getBoundingClientRect() value. */
2945
- moveFab(trigger, x, y, snap) {
2946
- const axis = (() => {
2947
- const d2 = this.config.draggable;
2948
- if (!d2) return "both";
2949
- return typeof d2 === "object" ? d2.axis ?? "both" : "both";
2950
- })();
2951
- const W = window.innerWidth;
2952
- const H = window.innerHeight;
2953
- const btnW = trigger.offsetWidth || 52;
2954
- const btnH = trigger.offsetHeight || 52;
2955
- const safeL = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-left") || "0") || 0;
2956
- const safeR = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-right") || "0") || 0;
2957
- const safeT = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-top") || "0") || 0;
2958
- const safeB = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-bottom") || "0") || 0;
2959
- const margin = 8;
2960
- const rect = trigger.getBoundingClientRect();
2961
- const prevDragX = this.fabPos?.x ?? 0;
2962
- const prevDragY = this.fabPos?.y ?? 0;
2963
- const baseLeft = rect.left - prevDragX;
2964
- const baseTop = rect.top - prevDragY;
2965
- const minX = safeL + margin - baseLeft;
2966
- const maxX = W - safeR - margin - btnW - baseLeft;
2967
- const minY = safeT + margin - baseTop;
2968
- const maxY = H - safeB - margin - btnH - baseTop;
2969
- const newX = axis === "y" ? 0 : Math.max(minX, Math.min(maxX, x));
2970
- const newY = axis === "x" ? 0 : Math.max(minY, Math.min(maxY, y));
2971
- let finalX = newX;
2972
- if (snap) {
2973
- const d2 = this.config.draggable;
2974
- const shouldSnap = d2 === true || typeof d2 === "object" && (d2.snapToEdge ?? true);
2975
- if (shouldSnap && axis !== "y") {
2976
- const center = rect.left + btnW / 2;
2977
- finalX = center < W / 2 ? safeL + margin - baseLeft : W - safeR - margin - btnW - baseLeft;
2978
- }
2979
- }
2980
- this.fabPos = { x: finalX, y: newY };
2981
- trigger.style.setProperty("--mushi-drag-x", `${finalX}px`);
2982
- trigger.style.setProperty("--mushi-drag-y", `${newY}px`);
2983
- trigger.style.setProperty("--mushi-drag-active", "1");
2984
- const d = this.config.draggable;
2985
- const shouldPersist = d === true || typeof d === "object" && (d.persist ?? true);
2986
- if (shouldPersist) {
2987
- try {
2988
- localStorage.setItem(this.fabStorageKey(), JSON.stringify(this.fabPos));
2989
- } catch {
2990
- }
2991
- }
3182
+ showNudge() {
3183
+ if (this.nudgeShown || this.nudgeEl) return;
3184
+ this.nudgeShown = true;
3185
+ const trigger = this.shadow.querySelector(".mushi-trigger");
3186
+ const rect = trigger?.getBoundingClientRect();
3187
+ const nudge = document.createElement("div");
3188
+ nudge.id = "mushi-nudge-bubble";
3189
+ nudge.setAttribute("role", "tooltip");
3190
+ const isRight = this.config.position.includes("right");
3191
+ nudge.style.cssText = `
3192
+ position: fixed;
3193
+ z-index: 2147483645;
3194
+ ${rect ? `bottom: ${window.innerHeight - rect.top + 8}px; ${isRight ? `right: ${window.innerWidth - rect.right}px;` : `left: ${rect.left}px;`}` : "bottom: 80px; right: 24px;"}
3195
+ background: rgba(17,17,17,0.92);
3196
+ color: #fff;
3197
+ font-family: ui-sans-serif, system-ui, sans-serif;
3198
+ font-size: 12px;
3199
+ line-height: 1.4;
3200
+ padding: 8px 12px;
3201
+ border-radius: 8px;
3202
+ max-width: 200px;
3203
+ pointer-events: none;
3204
+ backdrop-filter: blur(4px);
3205
+ box-shadow: 0 2px 12px rgba(0,0,0,0.35);
3206
+ animation: mushi-fade-in 0.15s ease forwards;
3207
+ `;
3208
+ nudge.textContent = this.locale.step3.tooShort.startsWith("A bit") ? "Found a bug? One sentence is enough \u{1F41B}" : "\u30D0\u30B0\u3092\u898B\u3064\u3051\u305F\uFF1F\u4E00\u884C\u3067\u5927\u4E08\u592B\u3067\u3059 \u{1F41B}";
3209
+ document.body.appendChild(nudge);
3210
+ this.nudgeEl = nudge;
3211
+ if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
3212
+ this.nudgeTimer = setTimeout(() => this.removeNudge(), 5e3);
2992
3213
  }
2993
- /** Load previously persisted FAB position. */
2994
- loadFabPos() {
2995
- const d = this.config.draggable;
2996
- if (!d) return;
2997
- const shouldPersist = d === true || typeof d === "object" && (d.persist ?? true);
2998
- if (!shouldPersist) return;
2999
- try {
3000
- const raw = localStorage.getItem(this.fabStorageKey());
3001
- if (raw) {
3002
- const parsed = JSON.parse(raw);
3003
- if (typeof parsed?.x === "number" && typeof parsed?.y === "number") {
3004
- this.fabPos = parsed;
3005
- }
3006
- }
3007
- } catch {
3214
+ removeNudge() {
3215
+ if (this.nudgeTimer !== null) {
3216
+ clearTimeout(this.nudgeTimer);
3217
+ this.nudgeTimer = null;
3008
3218
  }
3219
+ this.nudgeEl?.remove();
3220
+ this.nudgeEl = null;
3221
+ document.getElementById("mushi-nudge-bubble")?.remove();
3009
3222
  }
3010
- /** Attach Pointer Events-based drag to the trigger element. */
3011
- attachDragHandlers(trigger) {
3012
- if (this.fabPos === null) this.loadFabPos();
3013
- let startX = 0, startY = 0;
3014
- let originX = 0, originY = 0;
3015
- let dragging = false;
3016
- let moved = false;
3017
- const onPointerDown = (e) => {
3018
- if (e.button !== 0 && e.pointerType !== "touch") return;
3019
- trigger.setPointerCapture(e.pointerId);
3020
- startX = e.clientX;
3021
- startY = e.clientY;
3022
- const cur = this.fabPos ?? { x: 0, y: 0 };
3023
- originX = cur.x;
3024
- originY = cur.y;
3025
- dragging = true;
3026
- moved = false;
3027
- };
3028
- const DRAG_THRESHOLD = 6;
3029
- const onPointerMove = (e) => {
3030
- if (!dragging) return;
3031
- const dx = e.clientX - startX;
3032
- const dy = e.clientY - startY;
3033
- if (!moved && Math.hypot(dx, dy) > DRAG_THRESHOLD) {
3034
- moved = true;
3035
- trigger.classList.add("dragging");
3036
- trigger.setAttribute("aria-grabbed", "true");
3037
- }
3038
- if (moved) {
3039
- e.preventDefault();
3040
- this.moveFab(trigger, originX + dx, originY + dy, false);
3041
- }
3042
- };
3043
- const onPointerUp = (e) => {
3044
- if (!dragging) return;
3045
- dragging = false;
3046
- trigger.classList.remove("dragging");
3047
- trigger.removeAttribute("aria-grabbed");
3048
- if (moved) {
3049
- const dx = e.clientX - startX;
3050
- const dy = e.clientY - startY;
3051
- this.moveFab(trigger, originX + dx, originY + dy, true);
3052
- const suppressClick = (ev) => {
3053
- ev.stopImmediatePropagation();
3054
- trigger.removeEventListener("click", suppressClick, { capture: true });
3055
- };
3056
- trigger.addEventListener("click", suppressClick, { capture: true });
3057
- }
3058
- moved = false;
3059
- };
3060
- trigger.addEventListener("pointerdown", onPointerDown);
3061
- trigger.addEventListener("pointermove", onPointerMove);
3062
- trigger.addEventListener("pointerup", onPointerUp);
3063
- trigger.addEventListener("pointercancel", onPointerUp);
3223
+ setSdkFreshness(info) {
3224
+ this.sdkFreshness = info;
3225
+ if (this.isOpen) this.render();
3064
3226
  }
3065
- // ─── Keyboard / visualViewport ──────────────────────────────────────────────
3066
- /** Lift the panel above the software keyboard using visualViewport. */
3067
- attachViewportHandlers(panel) {
3068
- this.teardownViewportHandlers();
3069
- const vv = window.visualViewport;
3070
- if (!vv) return;
3071
- const update = () => {
3072
- const keyboardInset = window.innerHeight - vv.height - vv.offsetTop;
3073
- if (keyboardInset > 50) {
3074
- panel.style.setProperty("--mushi-keyboard-inset", `${Math.round(keyboardInset)}px`);
3075
- panel.classList.add("keyboard-open");
3076
- const ta = panel.querySelector('textarea, input[type="text"]');
3077
- ta?.scrollIntoView({ block: "nearest", behavior: "smooth" });
3078
- } else {
3079
- panel.style.setProperty("--mushi-keyboard-inset", "0px");
3080
- panel.classList.remove("keyboard-open");
3081
- }
3082
- };
3083
- vv.addEventListener("resize", update, { passive: true });
3084
- vv.addEventListener("scroll", update, { passive: true });
3085
- const onFocus = () => requestAnimationFrame(update);
3086
- panel.addEventListener("focusin", onFocus);
3087
- this.vvCleanup = () => {
3088
- vv.removeEventListener("resize", update);
3089
- vv.removeEventListener("scroll", update);
3090
- panel.removeEventListener("focusin", onFocus);
3091
- };
3227
+ setRewardsState(state) {
3228
+ this.rewardsState = state;
3229
+ if (this.isOpen) this.render();
3092
3230
  }
3093
- teardownViewportHandlers() {
3094
- this.vvCleanup?.();
3095
- this.vvCleanup = null;
3231
+ setLeaderboard(entries, loading = false) {
3232
+ this.leaderboardEntries = entries;
3233
+ this.leaderboardLoading = loading;
3234
+ if (this.isOpen && this.step === "leaderboard") this.render();
3096
3235
  }
3097
- renderStep() {
3098
- switch (this.step) {
3099
- case "category":
3100
- return this.renderCategoryStep();
3101
- case "intent":
3102
- return this.renderIntentStep();
3103
- case "details":
3104
- return this.renderDetailsStep();
3105
- case "success":
3106
- return this.renderSuccessStep();
3107
- case "reports":
3108
- return this.renderReportsStep();
3109
- case "report-detail":
3110
- return this.renderReportDetailStep();
3111
- case "leaderboard":
3112
- return this.renderLeaderboardStep();
3113
- case "roadmap":
3114
- return this.renderRoadmapStep();
3115
- case "account":
3116
- return this.renderAccountStep();
3117
- case "cross-app-reports":
3118
- return this.renderCrossAppReportsStep();
3119
- }
3120
- }
3121
- renderOutdatedBanner() {
3122
- if (!this.sdkFreshness) return "";
3123
- if (this.config.outdatedBanner === "off" || this.config.outdatedBanner === "console-only") return "";
3124
- const { latest, current, deprecated, message } = this.sdkFreshness;
3125
- if (!latest && !deprecated) return "";
3126
- return `
3127
- <div class="mushi-outdated" role="status">
3128
- <strong>Mushi SDK ${escapeHtml(current)}</strong>
3129
- ${latest ? `latest is ${escapeHtml(latest)}.` : "needs attention."}
3130
- ${message ? `<span>${escapeHtml(message)}</span>` : ""}
3131
- </div>
3132
- `;
3236
+ // ── Community public setters (called by mushi.ts after API calls) ──────────
3237
+ setTesterSession(jwt, info) {
3238
+ this.testerJwt = jwt;
3239
+ this.testerInfo = info;
3240
+ if (this.isOpen) this.render();
3241
+ }
3242
+ setGlobalLeaderboard(entries, loading = false) {
3243
+ this.globalLeaderboard = entries;
3244
+ this.globalLeaderboardLoading = loading;
3245
+ if (this.isOpen && (this.step === "leaderboard" || this.step === "account")) this.render();
3246
+ }
3247
+ setCrossAppReports(reports, loading = false) {
3248
+ this.crossAppReports = reports;
3249
+ this.crossAppLoading = loading;
3250
+ if (this.isOpen && this.step === "cross-app-reports") this.render();
3251
+ }
3252
+ setTesterReputation(rep) {
3253
+ this.testerReputation = rep;
3254
+ if (this.isOpen && (this.step === "account" || this.step === "leaderboard")) this.render();
3133
3255
  }
3134
- renderBrandFooter() {
3135
- if (this.config.brandFooter === false) return "";
3136
- return `<div class="mushi-brand-footer">Powered by Mushi v${escapeHtml(this.sdkVersion)}</div>`;
3256
+ destroy() {
3257
+ if (this.successTimer !== null) {
3258
+ clearTimeout(this.successTimer);
3259
+ this.successTimer = null;
3260
+ }
3261
+ if (this.autoCloseTimer !== null) {
3262
+ clearTimeout(this.autoCloseTimer);
3263
+ this.autoCloseTimer = null;
3264
+ }
3265
+ if (this.smartHideTimer !== null) {
3266
+ clearTimeout(this.smartHideTimer);
3267
+ this.smartHideTimer = null;
3268
+ }
3269
+ this.smartHideCleanup?.();
3270
+ this.smartHideCleanup = null;
3271
+ this.teardownViewportHandlers();
3272
+ this.attachedLaunchers.forEach((cleanup) => cleanup());
3273
+ this.attachedLaunchers = [];
3274
+ this.removeSelectorHint();
3275
+ this.removeNudge();
3276
+ this.removeBodyNudge();
3277
+ this.host.remove();
3137
3278
  }
3279
+ /* ── Host chrome contract ────────────────────────────────────────────────
3280
+ The host element must never create an invisible full-screen touch blocker.
3281
+ We own these inline styles — consumer CSS can only win with `!important`,
3282
+ which is explicitly banned by the SDK contract. Calling this at mount()
3283
+ and after every zIndex update is the only safe invariant. */
3138
3284
  /**
3139
- * Editorial masthead. Always carries:
3140
- * • the brand mark (虫 kanji on vermillion, "MUSHI" in mono above)
3141
- * • the page title (serif display)
3142
- * • the close affordance
3143
- *
3144
- * On sub-steps it additionally renders a back button (replacing the
3145
- * "MUSHI" eyebrow with a "← BACK" mono link) and a step counter
3146
- * ledger ("02 / 03") on the far right.
3285
+ * Apply the SDK-owned pass-through layout to the host element so it is
3286
+ * always zero-sized and click/touch-transparent. Only the shadow-root
3287
+ * internals (`.mushi-trigger`, `.mushi-banner`, `.mushi-panel`) opt back
3288
+ * into pointer events. This is idempotent and safe to call repeatedly.
3147
3289
  */
3148
- renderHeader(opts) {
3149
- const t = this.locale;
3150
- const { title, showBack = false, step, eyebrow } = opts;
3151
- const eyebrowHtml = showBack ? `<button type="button" class="mushi-back" data-action="back" aria-label="${t.widget.back}">\u2190</button>` : `<span class="mushi-header-eyebrow">${eyebrow ?? "Mushi \xB7 Report"}</span>`;
3152
- const counterHtml = step ? `<span class="mushi-step-counter" aria-label="Step ${step} of ${TOTAL_STEPS}"><b>${pad2(step)}</b> / ${pad2(TOTAL_STEPS)}</span>` : "";
3153
- return `
3154
- <div class="mushi-header">
3155
- <div class="mushi-header-mark" aria-hidden="true">\u866B</div>
3156
- <div class="mushi-header-titles">
3157
- ${eyebrowHtml}
3158
- <h3>${title}</h3>
3159
- </div>
3160
- <div class="mushi-header-meta">
3161
- ${counterHtml}
3162
- <button type="button" class="mushi-close" data-action="close" aria-label="${t.widget.close}">\u2715</button>
3163
- </div>
3164
- </div>
3165
- `;
3290
+ syncHostChromeState() {
3291
+ const s = this.host.style;
3292
+ s.setProperty("position", "fixed");
3293
+ s.setProperty("top", "0");
3294
+ s.setProperty("left", "0");
3295
+ s.setProperty("width", "0");
3296
+ s.setProperty("height", "0");
3297
+ s.setProperty("overflow", "visible");
3298
+ s.setProperty("pointer-events", "none");
3299
+ s.setProperty("z-index", String(this.config.zIndex));
3300
+ s.setProperty("margin", "0");
3301
+ s.setProperty("padding", "0");
3302
+ s.setProperty("border", "none");
3303
+ s.setProperty("background", "none");
3166
3304
  }
3167
3305
  /**
3168
- * Numeral step indicator: "01 — 02 — 03", with the active step in
3169
- * vermillion serif and completed steps struck through in mono.
3170
- * Replaces the original three-dot indicator (a generic SaaS pattern).
3306
+ * Returns true when a DOM element matching `hideOnSelector` is currently
3307
+ * present in the host document. Used by both the trigger and the banner
3308
+ * so a single selector consistently hides ALL SDK-injected launcher
3309
+ * surfaces. Invalid selectors are swallowed silently (non-fatal).
3171
3310
  */
3172
- renderStepIndicator(currentStep) {
3173
- const segments = [];
3174
- for (let i = 1; i <= TOTAL_STEPS; i++) {
3175
- const cls = i < currentStep ? "mushi-step-num done" : i === currentStep ? "mushi-step-num active" : "mushi-step-num";
3176
- segments.push(`<span class="${cls}">${pad2(i)}</span>`);
3177
- if (i < TOTAL_STEPS) segments.push('<span class="mushi-step-sep" aria-hidden="true"></span>');
3311
+ isSuppressedByHost() {
3312
+ if (!this.config.hideOnSelector || typeof document === "undefined") return false;
3313
+ try {
3314
+ return Boolean(document.querySelector(this.config.hideOnSelector));
3315
+ } catch {
3316
+ return false;
3178
3317
  }
3179
- return `<div class="mushi-step-indicator" aria-hidden="true">${segments.join("")}</div>`;
3180
- }
3181
- renderCategoryStep() {
3182
- const t = this.locale;
3183
- const categoryEntries = this.config.categories && this.config.categories.length > 0 ? this.config.categories.map((c) => ({
3184
- id: c.id,
3185
- icon: c.icon ?? "\u{1F4AC}",
3186
- label: c.label,
3187
- desc: c.description ?? ""
3188
- })) : ["bug", "slow", "visual", "confusing", "other"].map((id) => ({
3189
- id,
3190
- icon: CATEGORY_ICONS[id],
3191
- label: t.step1.categories[id],
3192
- desc: t.step1.categoryDescriptions[id]
3193
- }));
3194
- const categories = categoryEntries.map(({ id, icon, label, desc }) => `
3195
- <button type="button" class="mushi-option-btn" data-category="${escapeHtml(id)}" role="radio" aria-checked="false">
3196
- <span class="mushi-option-icon" aria-hidden="true">${escapeHtml(icon)}</span>
3197
- <div class="mushi-option-text">
3198
- <span class="mushi-option-label">${escapeHtml(label)}</span>
3199
- ${desc ? `<span class="mushi-option-desc">${escapeHtml(desc)}</span>` : ""}
3200
- </div>
3201
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
3202
- </button>
3203
- `).join("");
3204
- return `
3205
- ${this.renderHeader({ title: t.step1.heading, step: STEP_NUMBER.category })}
3206
- ${this.config.betaMode?.enabled ? this.renderBetaStrip() : ""}
3207
- <div class="mushi-body" role="radiogroup" aria-label="${t.step1.heading}">
3208
- <button type="button" class="mushi-option-btn mushi-reports-entry" data-action="reports">
3209
- <span class="mushi-option-icon" aria-hidden="true">\u{1F4EC}</span>
3210
- <div class="mushi-option-text">
3211
- <span class="mushi-option-label">Your reports${this.unreadCount() ? ` (${this.unreadCount()} new)` : ""}</span>
3212
- <span class="mushi-option-desc">See status, developer replies, and respond</span>
3213
- </div>
3214
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
3215
- </button>
3216
- ${this.renderFeatureRequestEntry()}
3217
- ${this.callbacks.onFeatureBoardRequest ? `
3218
- <button type="button" class="mushi-option-btn" data-action="roadmap">
3219
- <span class="mushi-option-icon" aria-hidden="true">\u{1F5F3}\uFE0F</span>
3220
- <div class="mushi-option-text">
3221
- <span class="mushi-option-label">Community ideas</span>
3222
- <span class="mushi-option-desc">Vote on features and see what shipped</span>
3223
- </div>
3224
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
3225
- </button>` : ""}
3226
- ${categories}
3227
- ${this.rewardsState ? this.renderRewardsNudge() : ""}
3228
- <div class="mushi-community-footer">
3229
- <button type="button" class="mushi-link-btn mushi-community-btn" data-action="open-account">
3230
- ${this.testerInfo ? `\u{1F464} ${escapeHtml(this.testerInfo.public_handle ?? this.testerInfo.display_name ?? "My account")}` : "\u{1F310} Join community \xB7 Track reports across apps"}
3231
- </button>
3232
- ${this.rewardsState ? `<button type="button" class="mushi-link-btn" data-action="open-leaderboard">\u{1F3C6} Leaderboard</button>` : ""}
3233
- </div>
3234
- </div>
3235
- ${this.renderStepIndicator(STEP_NUMBER.category)}
3236
- `;
3237
3318
  }
3238
3319
  /**
3239
- * First-class "Feature request" entry rendered at the top of the
3240
- * category step. Beta apps consistently get more useful signal when
3241
- * the user has a no-friction path to say "I wish this did X" — burying
3242
- * it as an intent under the "Other" category drops feature submissions
3243
- * by ~40% in industry studies (Userpilot, Usersnap 2025).
3244
- *
3245
- * Wire format: still routes through the standard `other` category with
3246
- * a `user_category = 'Feature request'` stamp, so we don't need a DB
3247
- * migration. The admin console filters on that string to surface the
3248
- * Feature-request swimlane.
3320
+ * Returns a snapshot of the widget's host-layer health for use in
3321
+ * `Mushi.diagnose()`. Callers check this to know whether the widget
3322
+ * could ever block host-app UI without opening a browser devtools.
3249
3323
  */
3250
- renderFeatureRequestEntry() {
3251
- const enabled = this.config.featureRequestCard !== false;
3252
- if (!enabled) return "";
3253
- const label = this.config.featureRequestLabel ?? "Feature request";
3254
- const desc = this.config.featureRequestDescription ?? "Suggest something new \u2014 even rough ideas help us prioritise";
3255
- return `
3256
- <button
3257
- type="button"
3258
- class="mushi-option-btn mushi-feature-entry"
3259
- data-action="feature-request"
3260
- aria-label="${escapeHtml(label)}"
3261
- >
3262
- <span class="mushi-option-icon" aria-hidden="true">\u2728</span>
3263
- <div class="mushi-option-text">
3264
- <span class="mushi-option-label">${escapeHtml(label)}</span>
3265
- <span class="mushi-option-desc">${escapeHtml(desc)}</span>
3266
- </div>
3267
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
3268
- </button>
3269
- `;
3270
- }
3271
- /** Collapsible "What's new" changelog row. Closes the reporter feedback loop. */
3272
- renderBetaChangelog() {
3273
- const entries = this.config.betaMode?.changelogItems;
3274
- if (!entries?.length) return "";
3275
- const latest = entries[0];
3276
- const items = latest.items.map((item) => `<li>\u2022 ${escapeHtml(item)}</li>`).join("");
3277
- const label = latest.date ? `What\u2019s new in ${escapeHtml(latest.version)} \xB7 ${escapeHtml(latest.date)}` : `What\u2019s new in ${escapeHtml(latest.version)}`;
3278
- return `
3279
- <details class="mushi-changelog">
3280
- <summary class="mushi-changelog-summary">${label}</summary>
3281
- <ul class="mushi-changelog-list">${items}</ul>
3282
- </details>
3283
- `;
3324
+ getWidgetDiagnostics() {
3325
+ const s = this.host.style;
3326
+ const widgetHostPointerSafe = s.pointerEvents === "none" && (s.width === "0" || s.width === "0px") && (s.height === "0" || s.height === "0px");
3327
+ const widgetHostBounds = this.host.isConnected ? { width: this.host.offsetWidth, height: this.host.offsetHeight } : null;
3328
+ const widgetSuppressed = this.isSuppressedByHost() || this.isRouteHidden() || !this.triggerVisible;
3329
+ const bannerRendered = this.config.trigger === "banner" && !this.bannerDismissed && !this.isSuppressedByHost() && !this.isRouteHidden() && this.triggerVisible;
3330
+ return { widgetHostPointerSafe, widgetHostBounds, widgetSuppressed, bannerRendered };
3284
3331
  }
3285
- /**
3286
- * Discreet beta status strip: communicates "work in progress", invites
3287
- * feedback, and sets expectations — reducing user frustration while
3288
- * nudging the reciprocity instinct ("your reports help us build this").
3289
- */
3290
- renderBetaStrip() {
3291
- const beta = this.config.betaMode;
3292
- const appName = escapeHtml(beta.appName ?? "This app");
3293
- const message = beta.message ? escapeHtml(beta.message) : `${appName} is in early development \u2014 updates ship weekly`;
3294
- const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
3295
- const perks = beta.perks ?? [];
3296
- return `
3297
- <div class="mushi-beta-strip" role="note" aria-label="Beta status">
3298
- <div class="mushi-beta-strip-row">
3299
- <span class="mushi-beta-tag" aria-hidden="true">BETA</span>
3300
- <span class="mushi-beta-msg">${message}</span>
3301
- </div>
3302
- ${email ? `<div class="mushi-beta-contact-hint">Reports go to ${email} \xB7 reviewed by the team</div>` : ""}
3303
- ${perks.length > 0 ? `
3304
- <ul class="mushi-beta-perks" aria-label="Beta tester perks">
3305
- ${perks.map((p) => `<li>\u2713 ${escapeHtml(p)}</li>`).join("")}
3306
- </ul>
3307
- ` : ""}
3308
- ${this.renderBetaChangelog()}
3309
- </div>
3310
- `;
3332
+ syncAttachedLaunchers() {
3333
+ this.attachedLaunchers.forEach((cleanup) => cleanup());
3334
+ this.attachedLaunchers = [];
3335
+ if (this.config.trigger !== "attach" || !this.config.attachToSelector) return;
3336
+ if (typeof document === "undefined") return;
3337
+ this.attachedLaunchers.push(this.attachTo(this.config.attachToSelector));
3311
3338
  }
3312
- renderReportsStep() {
3313
- const reports = this.reporterReports.map((report) => {
3314
- const title = report.summary ?? report.description ?? `Report ${report.id.slice(0, 8)}`;
3315
- const tone = reporterStatusTone(report.status);
3316
- const when = formatRelativeTime(report.created_at);
3317
- const unread = report.unread_count && report.unread_count > 0 ? `<span class="mushi-unread-badge" aria-label="${report.unread_count} unread">${report.unread_count}</span>` : "";
3318
- return `
3319
- <button type="button" class="mushi-report-row" data-report-id="${escapeHtml(report.id)}" aria-label="View report: ${escapeHtml(title)}">
3320
- <div class="mushi-report-main">
3321
- <span class="mushi-report-title">${escapeHtml(title)}</span>
3322
- <span class="mushi-report-meta">
3323
- <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusShort(report.status))}</span>
3324
- ${when ? `<span class="mushi-report-when">${escapeHtml(when)}</span>` : ""}
3325
- ${unread}
3326
- </span>
3327
- </div>
3328
- <span class="mushi-report-chevron" aria-hidden="true">\u203A</span>
3329
- </button>`;
3330
- }).join("");
3331
- const leaderboardBtn = this.rewardsState ? `<button type="button" class="mushi-leaderboard-link" data-action="open-leaderboard">\u{1F3C6} Leaderboard</button>` : "";
3332
- return `
3333
- ${this.renderHeader({ title: "Your reports", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
3334
- <div class="mushi-body">
3335
- ${this.reporterLoading ? '<p class="mushi-muted">Loading reports\u2026</p>' : ""}
3336
- ${this.reporterError ? `<p class="mushi-error-inline">${escapeHtml(this.reporterError)}</p>` : ""}
3337
- ${reports || (!this.reporterLoading ? '<p class="mushi-muted">No reports from this browser yet.</p>' : "")}
3338
- ${leaderboardBtn}
3339
- </div>
3340
- `;
3339
+ syncSmartHide() {
3340
+ this.smartHideCleanup?.();
3341
+ this.smartHideCleanup = null;
3342
+ this.triggerShrunk = false;
3343
+ this.triggerHiddenByScroll = false;
3344
+ if (!this.config.smartHide || typeof window === "undefined") return;
3345
+ const smart = this.config.smartHide === true ? { onScroll: "shrink", onIdleMs: 900 } : this.config.smartHide;
3346
+ if (!smart.onScroll) return;
3347
+ const onScroll = () => {
3348
+ if (smart.onScroll === "hide") {
3349
+ this.triggerHiddenByScroll = true;
3350
+ } else {
3351
+ this.triggerShrunk = true;
3352
+ }
3353
+ this.render();
3354
+ if (this.smartHideTimer !== null) clearTimeout(this.smartHideTimer);
3355
+ this.smartHideTimer = setTimeout(() => {
3356
+ this.triggerHiddenByScroll = false;
3357
+ this.triggerShrunk = false;
3358
+ this.render();
3359
+ }, smart.onIdleMs ?? 900);
3360
+ };
3361
+ window.addEventListener("scroll", onScroll, { passive: true });
3362
+ this.smartHideCleanup = () => window.removeEventListener("scroll", onScroll);
3341
3363
  }
3342
- renderRoadmapStep() {
3343
- const rows = this.featureBoard.map((ticket) => {
3344
- const id = String(ticket.id ?? "");
3345
- const subject = escapeHtml(String(ticket.subject ?? "Untitled idea"));
3346
- const votes = Number(ticket.vote_count ?? 0);
3347
- const shipped = Boolean(ticket.shipped_at);
3348
- const voted = Boolean(ticket.my_vote);
3349
- const status = shipped ? "Shipped" : String(ticket.status_label ?? ticket.status ?? "open");
3350
- return `
3351
- <div class="mushi-report-row mushi-roadmap-row">
3352
- <div class="mushi-report-main">
3353
- <span class="mushi-report-title">${subject}</span>
3354
- <span class="mushi-report-meta">
3355
- <span class="mushi-report-status">${escapeHtml(status)}</span>
3356
- <span class="mushi-report-when">${votes} vote${votes === 1 ? "" : "s"}</span>
3357
- </span>
3358
- </div>
3359
- ${this.callbacks.onFeatureBoardVote ? `
3360
- <button type="button" class="mushi-vote-btn" data-vote-id="${escapeHtml(id)}" aria-pressed="${voted}">
3361
- ${voted ? "Voted" : "Vote"}
3362
- </button>` : ""}
3363
- </div>`;
3364
- }).join("");
3365
- return `
3366
- ${this.renderHeader({ title: "Community ideas", showBack: true, eyebrow: "Mushi \xB7 Roadmap" })}
3367
- <div class="mushi-body">
3368
- ${this.reporterLoading ? '<p class="mushi-muted">Loading ideas\u2026</p>' : ""}
3369
- ${this.reporterError ? `<p class="mushi-error-inline">${escapeHtml(this.reporterError)}</p>` : ""}
3370
- ${rows || (!this.reporterLoading ? '<p class="mushi-muted">No community ideas yet. Be the first to suggest one.</p>' : "")}
3371
- </div>
3372
- `;
3364
+ shouldRenderTrigger() {
3365
+ if (!this.triggerVisible) return false;
3366
+ if (this.triggerHiddenByScroll) return false;
3367
+ if (this.config.trigger === "manual" || this.config.trigger === "hidden" || this.config.trigger === "attach" || this.config.trigger === "banner") {
3368
+ return false;
3369
+ }
3370
+ if (this.isMobileSmartHidden()) return false;
3371
+ if (this.isRouteHidden()) return false;
3372
+ if (this.isSuppressedByHost()) return false;
3373
+ const action = this.config.environments[this.detectEnvironment()];
3374
+ return action !== "never" && action !== "manual";
3373
3375
  }
3374
- renderLeaderboardStep() {
3375
- const isGlobal = this.globalLeaderboard !== null || this.globalLeaderboardLoading;
3376
- const entries = isGlobal ? this.globalLeaderboard ?? [] : (this.leaderboardEntries ?? []).map((e) => ({
3377
- tester_id: "",
3378
- public_handle: null,
3379
- display_name: e.display_name,
3380
- rank: 0,
3381
- points_30d: e.points_30d,
3382
- total_points: e.total_points
3383
- }));
3384
- const loading = isGlobal ? this.globalLeaderboardLoading : this.leaderboardLoading;
3385
- const myRank = this.testerReputation?.rank ?? null;
3386
- const rows = entries.map((e, i) => {
3387
- const rank = e.rank || i + 1;
3388
- const isMe = this.testerReputation && e.tester_id === this.testerReputation.tester_id;
3389
- return `
3390
- <div class="mushi-lb-row ${rank === 1 ? "mushi-lb-top" : ""}${isMe ? " mushi-lb-me" : ""}">
3391
- <span class="mushi-lb-rank">#${rank}</span>
3392
- <span class="mushi-lb-name">${escapeHtml(e.public_handle ?? e.display_name ?? "Anon")}</span>
3393
- <span class="mushi-lb-pts">${(e.points_30d ?? e.total_points).toLocaleString()} pts</span>
3394
- </div>
3395
- `;
3396
- }).join("");
3397
- const myRankBadge = myRank ? `<div class="mushi-lb-myrank">You are ranked <strong>#${myRank}</strong> this month</div>` : !this.testerJwt ? `<button type="button" class="mushi-link-btn" data-action="open-account">Sign in to see your rank \u2192</button>` : "";
3398
- return `
3399
- ${this.renderHeader({ title: "\u{1F3C6} Global Leaderboard", showBack: true, eyebrow: "Mushi \xB7 Community" })}
3400
- <div class="mushi-body">
3401
- ${loading ? '<p class="mushi-muted">Loading leaderboard\u2026</p>' : ""}
3402
- ${!loading && !entries.length ? '<p class="mushi-muted">No contributors yet \u2014 be the first!</p>' : ""}
3403
- <div class="mushi-lb-list">${rows}</div>
3404
- ${myRankBadge}
3405
- <p class="mushi-lb-note">Global contributors this month \xB7 Points refresh monthly</p>
3406
- </div>
3407
- `;
3376
+ /** Height of the banner in px — kept in sync with the CSS `.mushi-banner` height (36px). */
3377
+ static BANNER_HEIGHT = 36;
3378
+ /** CSS property applied to document.body so host-app content doesn't slide under the banner. */
3379
+ static BODY_NUDGE_PROP = "--mushi-banner-offset";
3380
+ applyBodyNudge(position) {
3381
+ const h = `${_MushiWidget.BANNER_HEIGHT}px`;
3382
+ if (position === "top") {
3383
+ document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
3384
+ if (!document.body.style.paddingTop) {
3385
+ document.body.style.paddingTop = h;
3386
+ document.body.dataset.mushiBannerNudged = "top";
3387
+ }
3388
+ } else {
3389
+ document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
3390
+ if (!document.body.style.paddingBottom) {
3391
+ document.body.style.paddingBottom = h;
3392
+ document.body.dataset.mushiBannerNudged = "bottom";
3393
+ }
3394
+ }
3408
3395
  }
3409
- renderAccountStep() {
3410
- const tester = this.testerInfo;
3411
- if (tester) {
3412
- const handle = tester.public_handle ?? tester.display_name ?? "Tester";
3413
- const rep = this.testerReputation;
3414
- return `
3415
- ${this.renderHeader({ title: "\u866B Mushi Account", showBack: true, eyebrow: "Mushi \xB7 Identity" })}
3416
- <div class="mushi-body">
3417
- <div class="mushi-account-card">
3418
- <div class="mushi-account-avatar">${escapeHtml(handle.charAt(0).toUpperCase())}</div>
3419
- <div class="mushi-account-info">
3420
- <strong>${escapeHtml(handle)}</strong>
3421
- ${rep ? `<span class="mushi-account-rank">Rank #${rep.rank ?? "\u2014"} \xB7 ${(rep.points_30d ?? 0).toLocaleString()} pts this month</span>` : ""}
3422
- </div>
3423
- </div>
3424
- <button type="button" class="mushi-nav-item" data-action="open-cross-app-reports">
3425
- My reports across all apps \u2192
3426
- </button>
3427
- <button type="button" class="mushi-nav-item" data-action="open-global-leaderboard">
3428
- View global leaderboard \u2192
3429
- </button>
3430
- <button type="button" class="mushi-link-btn" data-action="sign-out-tester">Sign out</button>
3431
- </div>
3432
- `;
3396
+ removeBodyNudge() {
3397
+ document.documentElement.style.removeProperty(_MushiWidget.BODY_NUDGE_PROP);
3398
+ const nudged = document.body.dataset.mushiBannerNudged;
3399
+ if (nudged === "top") {
3400
+ document.body.style.paddingTop = "";
3401
+ delete document.body.dataset.mushiBannerNudged;
3402
+ } else if (nudged === "bottom") {
3403
+ document.body.style.paddingBottom = "";
3404
+ delete document.body.dataset.mushiBannerNudged;
3433
3405
  }
3434
- if (this.magicLinkSent) {
3435
- return `
3436
- ${this.renderHeader({ title: "\u866B Check your email", showBack: true, eyebrow: "Mushi \xB7 Sign in" })}
3437
- <div class="mushi-body">
3438
- <p class="mushi-muted">We sent a sign-in link to <strong>${escapeHtml(this.magicLinkEmail)}</strong>. Click it to connect your reports across apps and join the community.</p>
3439
- <button type="button" class="mushi-link-btn" data-action="resend-magic-link">Resend email</button>
3440
- ${this.magicLinkError ? `<p class="mushi-error">${escapeHtml(this.magicLinkError)}</p>` : ""}
3441
- </div>
3442
- `;
3406
+ }
3407
+ renderBanner() {
3408
+ if (this.config.trigger !== "banner") return;
3409
+ if (this.bannerDismissed) {
3410
+ this.removeBodyNudge();
3411
+ return;
3443
3412
  }
3444
- return `
3445
- ${this.renderHeader({ title: "\u866B Join the community", showBack: true, eyebrow: "Mushi \xB7 Sign in" })}
3446
- <div class="mushi-body">
3447
- <p class="mushi-muted">Sign in to see your reports across all apps and climb the global leaderboard. No password needed.</p>
3448
- <label class="mushi-label" for="mushi-email-input">Email address</label>
3449
- <input
3450
- id="mushi-email-input"
3451
- type="email"
3452
- class="mushi-textarea"
3453
- data-role="magic-link-email"
3454
- placeholder="you@example.com"
3455
- autocomplete="email"
3456
- value="${escapeHtml(this.magicLinkEmail)}"
3457
- style="padding: 10px 12px; height: auto; resize: none;"
3458
- />
3459
- ${this.magicLinkError ? `<p class="mushi-error">${escapeHtml(this.magicLinkError)}</p>` : ""}
3460
- <button type="button" class="mushi-submit" data-action="send-magic-link">
3461
- <span>Send sign-in link</span><span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
3462
- </button>
3463
- </div>
3464
- `;
3413
+ if (!this.triggerVisible) {
3414
+ this.removeBodyNudge();
3415
+ return;
3416
+ }
3417
+ if (this.isRouteHidden()) {
3418
+ this.removeBodyNudge();
3419
+ return;
3420
+ }
3421
+ if (this.isSuppressedByHost()) {
3422
+ this.removeBodyNudge();
3423
+ return;
3424
+ }
3425
+ const bc = this.config.bannerConfig ?? {};
3426
+ const variant = bc.variant ?? "brand";
3427
+ const position = bc.position ?? "top";
3428
+ const message = bc.message?.trim() ?? "";
3429
+ const richLayout = message.length > 0;
3430
+ const bugLabel = bc.bugCta ?? "\u{1F41B} Report a bug";
3431
+ const showFeat = bc.featureCta !== false;
3432
+ const featLabel = bc.featureCtaLabel ?? "Request feature";
3433
+ const zIdx = bc.zIndex ?? (this.config.zIndex ?? 99999) - 1;
3434
+ const banner = document.createElement("div");
3435
+ banner.className = `mushi-banner ${variant} ${position}${richLayout ? " mushi-banner--rich" : ""}`;
3436
+ banner.style.setProperty("--mushi-banner-z", String(zIdx));
3437
+ banner.setAttribute("role", "banner");
3438
+ const dismissBtn = document.createElement("button");
3439
+ dismissBtn.className = "mushi-banner-dismiss";
3440
+ dismissBtn.textContent = "\u2715";
3441
+ dismissBtn.setAttribute("aria-label", "Dismiss feedback banner");
3442
+ dismissBtn.addEventListener("click", () => {
3443
+ this.bannerDismissed = true;
3444
+ this.removeBodyNudge();
3445
+ this.render();
3446
+ });
3447
+ if (richLayout) {
3448
+ const body = document.createElement("div");
3449
+ body.className = "mushi-banner-body";
3450
+ const labelText = bc.label === false ? null : bc.label ?? "Beta";
3451
+ if (labelText) {
3452
+ const pill = document.createElement("span");
3453
+ pill.className = "mushi-banner-pill";
3454
+ pill.textContent = labelText;
3455
+ body.appendChild(pill);
3456
+ }
3457
+ const msg = document.createElement("span");
3458
+ msg.className = "mushi-banner-message";
3459
+ msg.textContent = message;
3460
+ body.appendChild(msg);
3461
+ banner.appendChild(body);
3462
+ const nav = document.createElement("nav");
3463
+ nav.className = "mushi-banner-actions";
3464
+ nav.setAttribute("aria-label", "Feedback banner actions");
3465
+ const appendDivider = (extra = false) => {
3466
+ const sep = document.createElement("span");
3467
+ sep.className = `mushi-banner-divider${extra ? " mushi-banner-extra" : ""}`;
3468
+ sep.setAttribute("aria-hidden", "true");
3469
+ sep.textContent = "|";
3470
+ nav.appendChild(sep);
3471
+ };
3472
+ const appendAction = (label, onClick, extra = false) => {
3473
+ const btn = document.createElement("button");
3474
+ btn.type = "button";
3475
+ btn.className = `mushi-banner-link${extra ? " mushi-banner-extra" : ""}`;
3476
+ btn.textContent = label;
3477
+ btn.addEventListener("click", onClick);
3478
+ nav.appendChild(btn);
3479
+ };
3480
+ appendAction(bugLabel, () => this.open());
3481
+ if (showFeat) {
3482
+ appendDivider(true);
3483
+ appendAction(featLabel, () => this.open({ featureRequest: true }), true);
3484
+ }
3485
+ for (const link of bc.links ?? []) {
3486
+ const linkLabel = link.label?.trim();
3487
+ if (!linkLabel) continue;
3488
+ const href = link.href && (/^https?:\/\//i.test(link.href) || link.href.startsWith("/")) ? link.href : void 0;
3489
+ appendDivider(true);
3490
+ if (href) {
3491
+ const anchor = document.createElement("a");
3492
+ anchor.className = "mushi-banner-link mushi-banner-extra";
3493
+ anchor.href = href;
3494
+ anchor.textContent = linkLabel;
3495
+ anchor.target = "_blank";
3496
+ anchor.rel = "noopener noreferrer";
3497
+ nav.appendChild(anchor);
3498
+ } else {
3499
+ appendAction(linkLabel, () => {
3500
+ if (link.featureRequest) this.open({ featureRequest: true });
3501
+ else this.open();
3502
+ }, true);
3503
+ }
3504
+ }
3505
+ banner.appendChild(nav);
3506
+ banner.appendChild(dismissBtn);
3507
+ } else {
3508
+ const bugBtn = document.createElement("button");
3509
+ bugBtn.className = "mushi-banner-btn";
3510
+ bugBtn.textContent = bugLabel;
3511
+ bugBtn.addEventListener("click", () => this.open());
3512
+ banner.appendChild(bugBtn);
3513
+ if (showFeat) {
3514
+ const featBtn = document.createElement("button");
3515
+ featBtn.className = "mushi-banner-btn";
3516
+ featBtn.textContent = featLabel;
3517
+ featBtn.addEventListener("click", () => this.open({ featureRequest: true }));
3518
+ banner.appendChild(featBtn);
3519
+ }
3520
+ banner.appendChild(dismissBtn);
3521
+ }
3522
+ this.shadow.appendChild(banner);
3523
+ this.applyBodyNudge(position);
3465
3524
  }
3466
- renderCrossAppReportsStep() {
3467
- const reports = this.crossAppReports ?? [];
3468
- const grouped = /* @__PURE__ */ new Map();
3469
- for (const r of reports) {
3470
- const key = r.project_id ?? "unknown";
3471
- if (!grouped.has(key)) grouped.set(key, { name: r.app_name ?? "Unknown App", reports: [] });
3472
- grouped.get(key).reports.push(r);
3525
+ effectiveTrigger() {
3526
+ if (!this.config.smartHide || typeof window === "undefined") return this.config.trigger;
3527
+ const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
3528
+ if (window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "edge-tab") {
3529
+ return "edge-tab";
3473
3530
  }
3474
- const rows = [...grouped.entries()].map(([, group]) => `
3475
- <div class="mushi-xapp-group">
3476
- <h4 class="mushi-xapp-app-name">${escapeHtml(group.name)}</h4>
3477
- ${group.reports.map((r) => {
3478
- const tone = reporterStatusTone(r.status);
3479
- return `
3480
- <div class="mushi-report-row" data-report-id="${escapeHtml(r.id)}" tabindex="0" role="button">
3481
- <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusShort(r.status))}</span>
3482
- <span class="mushi-report-title">${escapeHtml(r.title ?? r.category)}</span>
3483
- <span class="mushi-report-when">${escapeHtml(formatRelativeTime(r.created_at))}</span>
3484
- </div>
3485
- `;
3486
- }).join("")}
3487
- </div>
3488
- `).join("");
3489
- return `
3490
- ${this.renderHeader({ title: "My reports", showBack: true, eyebrow: "Mushi \xB7 All apps" })}
3491
- <div class="mushi-body">
3492
- ${this.crossAppLoading ? '<p class="mushi-muted">Loading your reports\u2026</p>' : ""}
3493
- ${!this.crossAppLoading && !reports.length ? '<p class="mushi-muted">No reports filed yet.</p>' : ""}
3494
- ${rows}
3495
- </div>
3496
- `;
3531
+ return this.config.trigger;
3497
3532
  }
3498
- renderReportDetailStep() {
3499
- const report = this.reporterReports.find((r) => r.id === this.selectedReportId);
3500
- const status = report?.status ?? "unknown";
3501
- const tone = reporterStatusTone(status);
3502
- const when = report?.created_at ? formatRelativeTime(report.created_at) : "";
3503
- const comments = this.reporterComments.map((comment) => `
3504
- <div class="mushi-thread-comment ${comment.author_kind}">
3505
- <strong>${escapeHtml(comment.author_kind === "reporter" ? "You" : comment.author_name ?? "Developer")}</strong>
3506
- <p>${escapeHtml(comment.body)}</p>
3507
- </div>
3508
- `).join("");
3509
- return `
3510
- ${this.renderHeader({ title: "Report thread", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
3511
- <div class="mushi-body">
3512
- <div class="mushi-thread-summary">
3513
- <div class="mushi-thread-summary-meta">
3514
- <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusLabel(status))}</span>
3515
- ${when ? `<span class="mushi-report-when">Reported ${escapeHtml(when)}</span>` : ""}
3516
- </div>
3517
- <p>${escapeHtml(report?.summary ?? report?.description ?? "Report details")}</p>
3518
- </div>
3519
- <div class="mushi-thread">
3520
- ${this.reporterLoading ? '<p class="mushi-muted">Loading thread\u2026</p>' : comments || '<p class="mushi-muted">No developer replies yet.</p>'}
3521
- </div>
3522
- ${["fixed", "resolved", "verified"].includes(status) ? `
3523
- <div class="mushi-verify-actions" role="group" aria-label="Fix verification">
3524
- <button type="button" class="mushi-intent-btn" data-action="reporter-confirms">Yes, fixed for me</button>
3525
- <button type="button" class="mushi-intent-btn" data-action="reporter-not-fixed">Not fixed yet</button>
3526
- </div>
3527
- ` : ""}
3528
- <textarea class="mushi-textarea" data-role="reporter-reply" rows="3" placeholder="Reply to the developer\u2026"></textarea>
3529
- <button type="button" class="mushi-submit" data-action="reporter-reply">
3530
- <span>Reply</span><span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
3531
- </button>
3532
- </div>
3533
- `;
3533
+ isMobileSmartHidden() {
3534
+ if (!this.config.smartHide || typeof window === "undefined") return false;
3535
+ const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
3536
+ return window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "hide";
3534
3537
  }
3535
- renderIntentStep() {
3536
- const t = this.locale;
3537
- const catId = this.selectedCategory;
3538
- const customEntry = this.resolveCustomCategory(catId);
3539
- const intents = customEntry?.intents ?? (t.step2.intents[catId] || []);
3540
- const options = intents.map((intent) => `
3541
- <button type="button" class="mushi-intent-btn" data-intent="${escapeHtml(intent)}">
3542
- ${escapeHtml(intent)}
3543
- </button>
3544
- `).join("");
3545
- const icon = this.categoryIcon(catId);
3546
- const label = this.categoryLabel(catId);
3547
- return `
3548
- ${this.renderHeader({ title: t.step2.heading, showBack: true, step: STEP_NUMBER.intent })}
3549
- <div class="mushi-body">
3550
- <div class="mushi-selected-category">
3551
- <span aria-hidden="true">${escapeHtml(icon)}</span>
3552
- <span>${escapeHtml(label)}</span>
3553
- </div>
3554
- <div class="mushi-intents">
3555
- ${options}
3556
- </div>
3557
- </div>
3558
- ${this.renderStepIndicator(STEP_NUMBER.intent)}
3559
- `;
3538
+ detectEnvironment() {
3539
+ const host = typeof location !== "undefined" ? location.hostname : "";
3540
+ if (host === "localhost" || host === "127.0.0.1" || host.endsWith(".local")) return "development";
3541
+ if (/\b(staging|stage|preview|dev)\b/i.test(host)) return "staging";
3542
+ return "production";
3560
3543
  }
3561
- effectiveMinLength() {
3562
- const base = this.config.minDescriptionLength ?? 20;
3563
- const lang = this.config.locale === "auto" ? typeof navigator !== "undefined" ? navigator.language ?? "" : "" : this.config.locale ?? "";
3564
- const isCjk = /^(ja|zh|ko)/i.test(lang);
3565
- return isCjk ? Math.max(4, Math.floor(base / 2)) : base;
3544
+ isRouteHidden() {
3545
+ if (!this.config.hideOnRoutes.length || typeof location === "undefined") return false;
3546
+ return this.config.hideOnRoutes.some((route) => location.pathname.includes(route));
3547
+ }
3548
+ getTheme() {
3549
+ const t = this.config.theme;
3550
+ if (t === "light" || t === "dark") return t;
3551
+ if (t === "inherit") {
3552
+ const root = document.documentElement;
3553
+ const colorScheme = root.getAttribute("data-color-scheme") || root.getAttribute("data-theme") || root.getAttribute("color-scheme") || "";
3554
+ if (/dark/i.test(colorScheme)) return "dark";
3555
+ if (/light/i.test(colorScheme)) return "light";
3556
+ if (root.classList.contains("dark")) return "dark";
3557
+ if (root.classList.contains("light")) return "light";
3558
+ try {
3559
+ const bg = getComputedStyle(root).backgroundColor;
3560
+ const m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
3561
+ if (m) {
3562
+ const L = 0.299 * +m[1] + 0.587 * +m[2] + 0.114 * +m[3];
3563
+ return L < 128 ? "dark" : "light";
3564
+ }
3565
+ } catch {
3566
+ }
3567
+ }
3568
+ if (typeof window !== "undefined" && window.matchMedia("(prefers-color-scheme: dark)").matches) {
3569
+ return "dark";
3570
+ }
3571
+ return "light";
3566
3572
  }
3567
- renderDetailsStep() {
3573
+ render() {
3574
+ const theme = this.getTheme();
3575
+ const pos = this.config.position;
3568
3576
  const t = this.locale;
3569
- const minLen = this.effectiveMinLength();
3570
- const screenshotLabel = this.screenshotCapturing ? t.step3.screenshotCapturing : this.screenshotError ? t.step3.screenshotFailed : this.screenshotAttached ? t.step3.screenshotAttached : t.step3.screenshotButton;
3571
- const screenshotClass = [
3572
- "mushi-attach-btn",
3573
- this.screenshotAttached ? "active" : "",
3574
- this.screenshotError ? "error" : "",
3575
- this.screenshotCapturing ? "loading" : ""
3576
- ].filter(Boolean).join(" ");
3577
- const elementLabel = this.elementCapturing ? t.step3.elementCapturing : this.elementSelected ? t.step3.elementSelected : t.step3.elementButton;
3578
- const elementClass = [
3579
- "mushi-attach-btn",
3580
- this.elementSelected ? "active" : "",
3581
- this.elementCapturing ? "loading" : ""
3582
- ].filter(Boolean).join(" ");
3583
- const exampleChips = t.step3.examplePrompts.map((p) => `<button type="button" class="mushi-example-chip" data-example="${escapeHtml(p)}">${escapeHtml(p)}</button>`).join("");
3584
- return `
3585
- ${this.renderHeader({ title: t.step3.heading, showBack: true, step: STEP_NUMBER.details })}
3586
- <div class="mushi-body">
3587
- <div class="mushi-example-chips" aria-label="Example prompts">${exampleChips}</div>
3588
- <div class="mushi-textarea-wrap">
3589
- <textarea
3590
- class="mushi-textarea"
3591
- placeholder="${t.step3.descriptionPlaceholder}"
3592
- rows="4"
3593
- aria-label="${t.step3.heading}"
3594
- autofocus
3595
- ></textarea>
3596
- <div class="mushi-char-counter" data-role="char-counter" aria-hidden="true">
3597
- <span data-role="char-current">0</span>/<span data-role="char-min">${minLen}</span>
3598
- </div>
3599
- </div>
3600
- <div class="mushi-attachments">
3601
- <button type="button" class="${screenshotClass}"
3602
- data-action="screenshot"
3603
- ${this.screenshotCapturing ? "disabled" : ""}
3604
- aria-label="${escapeHtml(screenshotLabel)}"
3605
- >
3606
- ${this.screenshotCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F4F8}"}
3607
- ${escapeHtml(screenshotLabel)}
3608
- </button>
3609
- ${this.screenshotAttached && this.allowScreenshotRemove ? '<button type="button" class="mushi-attach-btn danger" data-action="remove-screenshot" aria-label="Remove screenshot">\u2715 Remove</button>' : ""}
3610
- ${this.screenshotAttached ? '<button type="button" class="mushi-attach-btn" data-action="annotate-screenshot" aria-label="Mark up screenshot">\u270F Mark up</button><div class="mushi-annotate-host" data-role="annotate-host"></div>' : ""}
3611
- <button type="button" class="${elementClass}"
3612
- data-action="element"
3613
- ${this.elementCapturing ? "disabled" : ""}
3614
- aria-label="${escapeHtml(elementLabel)}"
3615
- >
3616
- ${this.elementCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F3AF}"}
3617
- ${escapeHtml(elementLabel)}
3618
- </button>
3619
- </div>
3620
- <div class="mushi-error" style="display:none" role="alert"></div>
3621
- </div>
3622
- <div class="mushi-footer">
3623
- <span class="mushi-footer-hint" aria-hidden="true">\u2318 + ENTER \u2192 send</span>
3624
- <button type="button" class="mushi-submit" data-action="submit"${this.submitting ? " disabled" : ""}>
3625
- <span>${this.submitting ? t.widget.submitting : t.widget.submit}</span>
3626
- <span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
3627
- </button>
3628
- </div>
3629
- ${this.renderStepIndicator(STEP_NUMBER.details)}
3630
- `;
3577
+ this.shadow.innerHTML = "";
3578
+ const style = document.createElement("style");
3579
+ style.textContent = getWidgetStyles(theme, this.config.accent ?? "", this.config.accentText ?? "");
3580
+ this.shadow.appendChild(style);
3581
+ this.renderBanner();
3582
+ if (this.shouldRenderTrigger()) {
3583
+ const effectiveTrigger = this.effectiveTrigger();
3584
+ const trigger = document.createElement("button");
3585
+ trigger.className = `mushi-trigger ${pos}${effectiveTrigger === "edge-tab" ? " edge-tab" : ""}${this.triggerShrunk ? " shrunk" : ""}`;
3586
+ trigger.textContent = this.config.triggerText;
3587
+ trigger.setAttribute("aria-label", t.widget.trigger);
3588
+ trigger.setAttribute("aria-haspopup", "dialog");
3589
+ trigger.setAttribute("aria-expanded", String(this.isOpen));
3590
+ trigger.style.zIndex = String(this.config.zIndex);
3591
+ this.applyInsetVars(trigger);
3592
+ trigger.addEventListener("click", () => {
3593
+ this.removeNudge();
3594
+ if (this.isOpen) this.close();
3595
+ else this.open();
3596
+ });
3597
+ trigger.addEventListener("mouseenter", () => {
3598
+ const onPageMs = this.mountedAt ? Date.now() - this.mountedAt : 0;
3599
+ if (!this.nudgeShown && !this.isOpen && onPageMs >= 3e4) {
3600
+ this.showNudge();
3601
+ }
3602
+ });
3603
+ trigger.addEventListener("mouseleave", () => {
3604
+ if (this.nudgeEl) {
3605
+ if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
3606
+ this.nudgeTimer = setTimeout(() => this.removeNudge(), 2e3);
3607
+ }
3608
+ });
3609
+ trigger.addEventListener("keydown", (e) => {
3610
+ const draggableConfig = this.config.draggable;
3611
+ if (!draggableConfig) return;
3612
+ const STEP = 8;
3613
+ const axis = typeof draggableConfig === "object" ? draggableConfig.axis ?? "both" : "both";
3614
+ let dx = 0, dy = 0;
3615
+ if (axis !== "y") {
3616
+ if (e.key === "ArrowLeft") dx = -STEP;
3617
+ else if (e.key === "ArrowRight") dx = STEP;
3618
+ }
3619
+ if (axis !== "x") {
3620
+ if (e.key === "ArrowUp") dy = -STEP;
3621
+ else if (e.key === "ArrowDown") dy = STEP;
3622
+ }
3623
+ if (dx !== 0 || dy !== 0) {
3624
+ e.preventDefault();
3625
+ const cur = this.fabPos ?? { x: 0, y: 0 };
3626
+ this.moveFab(trigger, cur.x + dx, cur.y + dy, false);
3627
+ }
3628
+ });
3629
+ if (this.config.draggable) {
3630
+ this.attachDragHandlers(trigger);
3631
+ }
3632
+ this.shadow.appendChild(trigger);
3633
+ if (this.fabPos && this.config.draggable) {
3634
+ const savedPos = this.fabPos;
3635
+ this.fabPos = { x: 0, y: 0 };
3636
+ this.moveFab(trigger, savedPos.x, savedPos.y, false);
3637
+ }
3638
+ }
3639
+ const panel = document.createElement("div");
3640
+ panel.className = `mushi-panel ${pos}${this.isOpen ? " open" : " closed"}`;
3641
+ panel.setAttribute("role", "dialog");
3642
+ panel.setAttribute("aria-modal", "true");
3643
+ panel.setAttribute("aria-label", t.widget.title);
3644
+ panel.style.zIndex = String(this.config.zIndex + 1);
3645
+ this.applyInsetVars(panel);
3646
+ if (this.isOpen) {
3647
+ const ctx = this.renderCtx();
3648
+ panel.innerHTML = `${renderOutdatedBanner(ctx)}${renderStep(ctx)}${renderBrandFooter(ctx)}`;
3649
+ this.shadow.appendChild(panel);
3650
+ this.attachHandlers(panel);
3651
+ this.trapFocus(panel);
3652
+ this.attachViewportHandlers(panel);
3653
+ } else {
3654
+ this.teardownViewportHandlers();
3655
+ }
3631
3656
  }
3632
3657
  /**
3633
- * Editorial success state: 朱印-style red stamp ring with the kanji
3634
- * 受 ("received") at its centre, the localised "thank you" string
3635
- * in serif below, and a mono ledger receipt ("REPORT · HH:MM:SS").
3636
- * The ring + label animations are defined in styles.ts so this stays
3637
- * pure markup and `prefers-reduced-motion` flips them to the final
3638
- * frame instantly.
3658
+ * Queries each `avoidSelectors` element in the host document and returns
3659
+ * the minimum top-offset in px so that a top-anchored element clears all
3660
+ * of them by `gap` pixels. Returns `null` when no selectors are provided
3661
+ * or no matching elements have a non-zero bounding rect.
3662
+ *
3663
+ * Runs in the host document (not shadow DOM) so it can reach fixed headers,
3664
+ * sticky nav bars, and sign-in CTAs.
3639
3665
  */
3640
- renderSuccessStep() {
3641
- const t = this.locale;
3642
- const stamp = this.submittedAt ?? /* @__PURE__ */ new Date();
3643
- const time = stamp.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
3644
- return `
3645
- ${this.renderHeader({ title: t.widget.title, eyebrow: "Mushi \xB7 Receipt" })}
3646
- <div class="mushi-body">
3647
- <div class="mushi-success">
3648
- <div class="mushi-success-stamp" aria-hidden="true">
3649
- <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"><circle cx="50" cy="50" r="44"/></svg>
3650
- <span class="mushi-success-stamp-label">\u53D7</span>
3651
- </div>
3652
- <div class="mushi-success-headline">${t.widget.submitted}</div>
3653
- <div class="mushi-success-meta">REPORT \xB7 ${time}</div>
3654
- ${this.renderSuccessReceipt()}
3655
- ${this.rewardsState ? this.renderSuccessRewards() : ""}
3656
- ${this.config.betaMode?.enabled ? this.renderBetaSuccessFooter() : ""}
3657
- </div>
3658
- </div>
3659
- `;
3666
+ computeAvoidTopPx(gap = 8) {
3667
+ const sels = this.config.avoidSelectors;
3668
+ if (!sels?.length) return null;
3669
+ let maxBottom = 0;
3670
+ for (const sel of sels) {
3671
+ try {
3672
+ const el = document.querySelector(sel);
3673
+ if (!el) continue;
3674
+ const r = el.getBoundingClientRect();
3675
+ if (r.bottom > maxBottom && r.width > 0 && r.height > 0) {
3676
+ maxBottom = r.bottom;
3677
+ }
3678
+ } catch {
3679
+ }
3680
+ }
3681
+ return maxBottom > 0 ? Math.ceil(maxBottom) + gap : null;
3660
3682
  }
3661
3683
  /**
3662
- * Two-way receipt block. Until the host's `onSubmit` resolves with a
3663
- * server-confirmed report id, we show a discreet "delivering..." pill so
3664
- * the user knows their submission is still in flight. Once we have the
3665
- * id, we surface a short monospaced id + a copy button + an optional
3666
- * "Track on Mushi" deep link to `dashboardUrl/reports/<id>` so the user
3667
- * can watch the status walk through queued -> classified -> fixed in
3668
- * real time (Peak-End rule: the last impression sticks). If we never
3669
- * get an id (offline retry queue), we say so explicitly rather than
3670
- * pretending everything is fine.
3684
+ * Minimum bottom-offset in px so a bottom-anchored trigger clears avoided
3685
+ * elements (tab bars, fixed CTAs). Mirrors {@link computeAvoidTopPx}.
3671
3686
  */
3672
- renderSuccessReceipt() {
3673
- if (this.lastSubmitQueuedOffline) {
3674
- return `
3675
- <div class="mushi-success-receipt" role="status">
3676
- <div class="mushi-success-receipt-row mushi-success-receipt-warn">
3677
- <span class="mushi-success-receipt-label">Queued offline</span>
3678
- <span class="mushi-success-receipt-hint">We&rsquo;ll send it the moment you&rsquo;re back online.</span>
3679
- </div>
3680
- </div>
3681
- `;
3687
+ computeAvoidBottomPx(gap = 8) {
3688
+ const sels = this.config.avoidSelectors;
3689
+ if (!sels?.length) return null;
3690
+ let maxClearance = 0;
3691
+ for (const sel of sels) {
3692
+ try {
3693
+ const el = document.querySelector(sel);
3694
+ if (!el) continue;
3695
+ const r = el.getBoundingClientRect();
3696
+ if (r.width > 0 && r.height > 0) {
3697
+ const clearance = window.innerHeight - r.top + gap;
3698
+ if (clearance > maxClearance) maxClearance = clearance;
3699
+ }
3700
+ } catch {
3701
+ }
3702
+ }
3703
+ return maxClearance > 0 ? Math.ceil(maxClearance) : null;
3704
+ }
3705
+ applyInsetVars(el) {
3706
+ const { anchor } = this.config;
3707
+ if (anchor && Object.keys(anchor).length > 0) {
3708
+ ["top", "right", "bottom", "left"].forEach((edge) => {
3709
+ const value = anchor[edge];
3710
+ if (value !== void 0) el.style.setProperty(`--mushi-${edge}`, value);
3711
+ });
3712
+ el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
3713
+ } else {
3714
+ const { inset } = this.config;
3715
+ if (!this.config.respectSafeArea) {
3716
+ ["top", "right", "bottom", "left"].forEach((edge) => {
3717
+ if (inset[edge] === void 0) el.style.setProperty(`--mushi-${edge}`, "24px");
3718
+ });
3719
+ }
3720
+ ["top", "right", "bottom", "left"].forEach((edge) => {
3721
+ const value = inset[edge];
3722
+ if (value === void 0) return;
3723
+ el.style.setProperty(`--mushi-${edge}`, value === "auto" ? "auto" : `${value}px`);
3724
+ });
3725
+ el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
3726
+ }
3727
+ const isTopAnchored = anchor?.top !== void 0 || this.config.position?.startsWith("top");
3728
+ const isBottomAnchored = anchor?.bottom !== void 0 || this.config.position?.startsWith("bottom") || !this.config.position;
3729
+ if (isTopAnchored) {
3730
+ const avoidPx = this.computeAvoidTopPx();
3731
+ if (avoidPx !== null) {
3732
+ el.style.setProperty("--mushi-top", `${avoidPx}px`);
3733
+ }
3734
+ }
3735
+ if (isBottomAnchored) {
3736
+ const avoidBottomPx = this.computeAvoidBottomPx();
3737
+ if (avoidBottomPx !== null) {
3738
+ el.style.setProperty("--mushi-bottom", `${avoidBottomPx}px`);
3739
+ }
3740
+ }
3741
+ }
3742
+ // ─── Draggable FAB ──────────────────────────────────────────────────────────
3743
+ /** Storage key for the FAB position, scoped to projectId when available. */
3744
+ fabStorageKey() {
3745
+ const id = this.config["projectId"] ?? "";
3746
+ return `mushi_fab_pos${id ? `_${id}` : ""}`;
3747
+ }
3748
+ /** Move the FAB to the given translated offset (relative to the inset origin),
3749
+ * clamping inside viewport safe area, and optionally snap to nearest edge.
3750
+ *
3751
+ * The FAB's CSS anchor can be any corner (bottom-right, bottom-left, …) so we
3752
+ * must derive the *base* position (CSS anchor with zero drag offset) to compute
3753
+ * correct clamp bounds and snap targets. We do this by subtracting the
3754
+ * already-applied drag offset from the live getBoundingClientRect() value. */
3755
+ moveFab(trigger, x, y, snap) {
3756
+ const axis = (() => {
3757
+ const d2 = this.config.draggable;
3758
+ if (!d2) return "both";
3759
+ return typeof d2 === "object" ? d2.axis ?? "both" : "both";
3760
+ })();
3761
+ const W = window.innerWidth;
3762
+ const H = window.innerHeight;
3763
+ const btnW = trigger.offsetWidth || 52;
3764
+ const btnH = trigger.offsetHeight || 52;
3765
+ const safeL = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-left") || "0") || 0;
3766
+ const safeR = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-right") || "0") || 0;
3767
+ const safeT = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-top") || "0") || 0;
3768
+ const safeB = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-bottom") || "0") || 0;
3769
+ const margin = 8;
3770
+ const rect = trigger.getBoundingClientRect();
3771
+ const prevDragX = this.fabPos?.x ?? 0;
3772
+ const prevDragY = this.fabPos?.y ?? 0;
3773
+ const baseLeft = rect.left - prevDragX;
3774
+ const baseTop = rect.top - prevDragY;
3775
+ const minX = safeL + margin - baseLeft;
3776
+ const maxX = W - safeR - margin - btnW - baseLeft;
3777
+ const minY = safeT + margin - baseTop;
3778
+ const maxY = H - safeB - margin - btnH - baseTop;
3779
+ const newX = axis === "y" ? 0 : Math.max(minX, Math.min(maxX, x));
3780
+ const newY = axis === "x" ? 0 : Math.max(minY, Math.min(maxY, y));
3781
+ let finalX = newX;
3782
+ if (snap) {
3783
+ const d2 = this.config.draggable;
3784
+ const shouldSnap = d2 === true || typeof d2 === "object" && (d2.snapToEdge ?? true);
3785
+ if (shouldSnap && axis !== "y") {
3786
+ const center = rect.left + btnW / 2;
3787
+ finalX = center < W / 2 ? safeL + margin - baseLeft : W - safeR - margin - btnW - baseLeft;
3788
+ }
3682
3789
  }
3683
- if (!this.lastReportId) {
3684
- return `
3685
- <div class="mushi-success-receipt" role="status">
3686
- <div class="mushi-success-receipt-row">
3687
- <span class="mushi-success-receipt-spinner" aria-hidden="true"></span>
3688
- <span class="mushi-success-receipt-hint">Delivering to the team\u2026</span>
3689
- </div>
3690
- ${this.renderSlaLine()}
3691
- </div>
3692
- `;
3790
+ this.fabPos = { x: finalX, y: newY };
3791
+ trigger.style.setProperty("--mushi-drag-x", `${finalX}px`);
3792
+ trigger.style.setProperty("--mushi-drag-y", `${newY}px`);
3793
+ trigger.style.setProperty("--mushi-drag-active", "1");
3794
+ const d = this.config.draggable;
3795
+ const shouldPersist = d === true || typeof d === "object" && (d.persist ?? true);
3796
+ if (shouldPersist) {
3797
+ try {
3798
+ localStorage.setItem(this.fabStorageKey(), JSON.stringify(this.fabPos));
3799
+ } catch {
3800
+ }
3693
3801
  }
3694
- const idShort = `#${this.lastReportId.slice(0, 8)}`;
3695
- const dashboard = (this.config.dashboardUrl ?? "").replace(/\/$/, "");
3696
- const trackHref = dashboard ? `${dashboard}/reports/${encodeURIComponent(this.lastReportId)}` : "";
3697
- return `
3698
- <div class="mushi-success-receipt" role="status">
3699
- <div class="mushi-success-receipt-row">
3700
- <span class="mushi-success-receipt-label">Receipt</span>
3701
- <button
3702
- type="button"
3703
- class="mushi-success-receipt-id"
3704
- data-action="copy-report-id"
3705
- data-copy-id="${escapeHtml(this.lastReportId)}"
3706
- title="Copy report id ${escapeHtml(this.lastReportId)}"
3707
- aria-label="Copy report id ${escapeHtml(this.lastReportId)}"
3708
- >${escapeHtml(idShort)}<span class="mushi-success-receipt-copy" aria-hidden="true">\u2398</span></button>
3709
- </div>
3710
- ${trackHref ? `
3711
- <a
3712
- class="mushi-success-receipt-track"
3713
- href="${escapeHtml(trackHref)}"
3714
- target="_blank"
3715
- rel="noopener noreferrer"
3716
- >Track on Mushi <span aria-hidden="true">\u2197</span></a>
3717
- ` : ""}
3718
- ${this.renderSlaLine()}
3719
- </div>
3720
- `;
3721
3802
  }
3722
- renderSlaLine() {
3723
- const sla = (this.config.responseSlaLabel ?? "").trim();
3724
- if (sla) {
3725
- return `<div class="mushi-success-sla">${escapeHtml(sla)}</div>`;
3803
+ /** Load previously persisted FAB position. */
3804
+ loadFabPos() {
3805
+ const d = this.config.draggable;
3806
+ if (!d) return;
3807
+ const shouldPersist = d === true || typeof d === "object" && (d.persist ?? true);
3808
+ if (!shouldPersist) return;
3809
+ try {
3810
+ const raw = localStorage.getItem(this.fabStorageKey());
3811
+ if (raw) {
3812
+ const parsed = JSON.parse(raw);
3813
+ if (typeof parsed?.x === "number" && typeof parsed?.y === "number") {
3814
+ this.fabPos = parsed;
3815
+ }
3816
+ }
3817
+ } catch {
3726
3818
  }
3727
- return `<div class="mushi-success-sla mushi-success-sla-default">A human will look at this within a working day.</div>`;
3819
+ }
3820
+ /** Attach Pointer Events-based drag to the trigger element. */
3821
+ attachDragHandlers(trigger) {
3822
+ if (this.fabPos === null) this.loadFabPos();
3823
+ let startX = 0, startY = 0;
3824
+ let originX = 0, originY = 0;
3825
+ let dragging = false;
3826
+ let moved = false;
3827
+ const onPointerDown = (e) => {
3828
+ if (e.button !== 0 && e.pointerType !== "touch") return;
3829
+ trigger.setPointerCapture(e.pointerId);
3830
+ startX = e.clientX;
3831
+ startY = e.clientY;
3832
+ const cur = this.fabPos ?? { x: 0, y: 0 };
3833
+ originX = cur.x;
3834
+ originY = cur.y;
3835
+ dragging = true;
3836
+ moved = false;
3837
+ };
3838
+ const DRAG_THRESHOLD = 6;
3839
+ const onPointerMove = (e) => {
3840
+ if (!dragging) return;
3841
+ const dx = e.clientX - startX;
3842
+ const dy = e.clientY - startY;
3843
+ if (!moved && Math.hypot(dx, dy) > DRAG_THRESHOLD) {
3844
+ moved = true;
3845
+ trigger.classList.add("dragging");
3846
+ trigger.setAttribute("aria-grabbed", "true");
3847
+ }
3848
+ if (moved) {
3849
+ e.preventDefault();
3850
+ this.moveFab(trigger, originX + dx, originY + dy, false);
3851
+ }
3852
+ };
3853
+ const onPointerUp = (e) => {
3854
+ if (!dragging) return;
3855
+ dragging = false;
3856
+ trigger.classList.remove("dragging");
3857
+ trigger.removeAttribute("aria-grabbed");
3858
+ if (moved) {
3859
+ const dx = e.clientX - startX;
3860
+ const dy = e.clientY - startY;
3861
+ this.moveFab(trigger, originX + dx, originY + dy, true);
3862
+ const suppressClick = (ev) => {
3863
+ ev.stopImmediatePropagation();
3864
+ trigger.removeEventListener("click", suppressClick, { capture: true });
3865
+ };
3866
+ trigger.addEventListener("click", suppressClick, { capture: true });
3867
+ }
3868
+ moved = false;
3869
+ };
3870
+ trigger.addEventListener("pointerdown", onPointerDown);
3871
+ trigger.addEventListener("pointermove", onPointerMove);
3872
+ trigger.addEventListener("pointerup", onPointerUp);
3873
+ trigger.addEventListener("pointercancel", onPointerUp);
3874
+ }
3875
+ // ─── Keyboard / visualViewport ──────────────────────────────────────────────
3876
+ /** Lift the panel above the software keyboard using visualViewport. */
3877
+ attachViewportHandlers(panel) {
3878
+ this.teardownViewportHandlers();
3879
+ const vv = window.visualViewport;
3880
+ if (!vv) return;
3881
+ const update = () => {
3882
+ const keyboardInset = window.innerHeight - vv.height - vv.offsetTop;
3883
+ if (keyboardInset > 50) {
3884
+ panel.style.setProperty("--mushi-keyboard-inset", `${Math.round(keyboardInset)}px`);
3885
+ panel.classList.add("keyboard-open");
3886
+ const ta = panel.querySelector('textarea, input[type="text"]');
3887
+ ta?.scrollIntoView({ block: "nearest", behavior: "smooth" });
3888
+ } else {
3889
+ panel.style.setProperty("--mushi-keyboard-inset", "0px");
3890
+ panel.classList.remove("keyboard-open");
3891
+ }
3892
+ };
3893
+ vv.addEventListener("resize", update, { passive: true });
3894
+ vv.addEventListener("scroll", update, { passive: true });
3895
+ const onFocus = () => requestAnimationFrame(update);
3896
+ panel.addEventListener("focusin", onFocus);
3897
+ this.vvCleanup = () => {
3898
+ vv.removeEventListener("resize", update);
3899
+ vv.removeEventListener("scroll", update);
3900
+ panel.removeEventListener("focusin", onFocus);
3901
+ };
3902
+ }
3903
+ teardownViewportHandlers() {
3904
+ this.vvCleanup?.();
3905
+ this.vvCleanup = null;
3728
3906
  }
3729
3907
  /**
3730
- * Reciprocity footer on the success step: closes the feedback loop by
3731
- * attributing where the report goes, sets a response expectation, and
3732
- * reinforces the "beta tester" identity (Peak-End Rule — the last thing
3733
- * the user sees shapes their entire impression of the interaction).
3908
+ * Minimum description length, lowered for CJK locales where each character
3909
+ * carries more meaning. Used by both the view layer (via renderCtx) and the
3910
+ * details-step input validation in attachHandlers.
3734
3911
  */
3735
- renderBetaSuccessFooter() {
3736
- const beta = this.config.betaMode;
3737
- const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
3738
- const appName = escapeHtml(beta.appName ?? "the team");
3739
- return `
3740
- <div class="mushi-beta-success-footer" role="note" aria-label="Beta feedback acknowledgement">
3741
- ${email ? `<div class="mushi-beta-success-line">\u{1F4EC} Sent to ${email}</div>` : `<div class="mushi-beta-success-line">\u{1F4EC} Sent to ${appName}</div>`}
3742
- <div class="mushi-beta-success-line mushi-beta-success-dim">We aim to review within 48h \xB7 thank you for helping build this</div>
3743
- </div>
3744
- `;
3912
+ effectiveMinLength() {
3913
+ const base = this.config.minDescriptionLength ?? 20;
3914
+ const lang = this.config.locale === "auto" ? typeof navigator !== "undefined" ? navigator.language ?? "" : "" : this.config.locale ?? "";
3915
+ const isCjk = /^(ja|zh|ko)/i.test(lang);
3916
+ return isCjk ? Math.max(4, Math.floor(base / 2)) : base;
3745
3917
  }
3918
+ /** Tier accent colour for the rewards UI. */
3746
3919
  tierColor(slug) {
3747
3920
  const colors = {
3748
3921
  free: "#6b7280",
@@ -3752,62 +3925,60 @@ var MushiWidget = class _MushiWidget {
3752
3925
  };
3753
3926
  return colors[slug] ?? "#6c47ff";
3754
3927
  }
3755
- /** Compact rewards nudge rendered at the bottom of the category-step body. */
3756
- renderRewardsNudge() {
3757
- const { tier, nextTier, totalPoints, pointsForReport } = this.rewardsState;
3758
- const tierName = tier?.displayName ?? "Free";
3759
- const tierSlug = tier?.slug ?? "free";
3760
- const color = this.tierColor(tierSlug);
3761
- let pct = 100;
3762
- let nextLabel = "";
3763
- if (nextTier) {
3764
- const base = tier?.pointsThreshold ?? 0;
3765
- const ceiling = nextTier.pointsThreshold;
3766
- pct = ceiling > base ? Math.round(Math.min(1, (totalPoints - base) / (ceiling - base)) * 100) : 100;
3767
- const remaining = Math.max(0, ceiling - totalPoints);
3768
- nextLabel = `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}`;
3769
- }
3770
- return `
3771
- <div class="mushi-rewards-nudge" aria-label="Rewards progress">
3772
- <div class="mushi-rewards-row">
3773
- <span class="mushi-tier-pip" style="background:${color}" aria-hidden="true"></span>
3774
- <span class="mushi-rewards-tier-name">${escapeHtml(tierName)}</span>
3775
- <span class="mushi-rewards-pts-count">${totalPoints.toLocaleString()} pts</span>
3776
- <span class="mushi-rewards-pts-earn">+${pointsForReport} pts for a report</span>
3777
- </div>
3778
- ${nextTier ? `
3779
- <div class="mushi-tier-bar-track" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="Progress to ${escapeHtml(nextTier.displayName)}">
3780
- <div class="mushi-tier-bar-fill" style="width:${pct}%"></div>
3781
- </div>
3782
- <div class="mushi-rewards-next-label">${nextLabel}</div>
3783
- ` : ""}
3784
- </div>
3785
- `;
3786
- }
3787
- /** Points earned + tier progress shown on the success step. */
3788
- renderSuccessRewards() {
3789
- const { tier, nextTier, totalPoints, pointsForReport } = this.rewardsState;
3790
- const projected = totalPoints + pointsForReport;
3791
- let pctAfter = 100;
3792
- let nextLabel = "";
3793
- if (nextTier) {
3794
- const base = tier?.pointsThreshold ?? 0;
3795
- const ceiling = nextTier.pointsThreshold;
3796
- pctAfter = ceiling > base ? Math.round(Math.min(1, (projected - base) / (ceiling - base)) * 100) : 100;
3797
- const remaining = Math.max(0, ceiling - projected);
3798
- nextLabel = remaining > 0 ? `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}` : `\u{1F389} ${escapeHtml(nextTier.displayName)} reached!`;
3799
- }
3800
- return `
3801
- <div class="mushi-success-rewards">
3802
- <div class="mushi-success-pts-award">+${pointsForReport} pts</div>
3803
- ${nextTier ? `
3804
- <div class="mushi-tier-bar-track success-bar" role="progressbar" aria-valuenow="${pctAfter}" aria-valuemin="0" aria-valuemax="100" aria-label="Progress to ${escapeHtml(nextTier.displayName)}">
3805
- <div class="mushi-tier-bar-fill" style="width:${pctAfter}%"></div>
3806
- </div>
3807
- <div class="mushi-rewards-next-label">${nextLabel}</div>
3808
- ` : ""}
3809
- </div>
3810
- `;
3928
+ /**
3929
+ * Build the read-only snapshot + bound helper closures the stateless view
3930
+ * layer (widget-render.ts) renders from. Rebuilt once per render() pass so
3931
+ * the HTML always reflects current state.
3932
+ */
3933
+ renderCtx() {
3934
+ return {
3935
+ config: this.config,
3936
+ rewardsState: this.rewardsState,
3937
+ lastReportId: this.lastReportId,
3938
+ reporterLoading: this.reporterLoading,
3939
+ locale: this.locale,
3940
+ testerReputation: this.testerReputation,
3941
+ testerInfo: this.testerInfo,
3942
+ screenshotCapturing: this.screenshotCapturing,
3943
+ screenshotAttached: this.screenshotAttached,
3944
+ reporterError: this.reporterError,
3945
+ magicLinkError: this.magicLinkError,
3946
+ elementCapturing: this.elementCapturing,
3947
+ submitting: this.submitting,
3948
+ sdkFreshness: this.sdkFreshness,
3949
+ screenshotError: this.screenshotError,
3950
+ reporterReports: this.reporterReports,
3951
+ magicLinkSending: this.magicLinkSending,
3952
+ magicLinkEmail: this.magicLinkEmail,
3953
+ globalLeaderboardLoading: this.globalLeaderboardLoading,
3954
+ globalLeaderboard: this.globalLeaderboard,
3955
+ elementSelected: this.elementSelected,
3956
+ crossAppLoading: this.crossAppLoading,
3957
+ callbacks: this.callbacks,
3958
+ testerJwt: this.testerJwt,
3959
+ submittedAt: this.submittedAt,
3960
+ step: this.step,
3961
+ selectedReportId: this.selectedReportId,
3962
+ selectedCategory: this.selectedCategory,
3963
+ sdkVersion: this.sdkVersion,
3964
+ reporterComments: this.reporterComments,
3965
+ magicLinkSent: this.magicLinkSent,
3966
+ leaderboardLoading: this.leaderboardLoading,
3967
+ leaderboardEntries: this.leaderboardEntries,
3968
+ lastSubmitQueuedOffline: this.lastSubmitQueuedOffline,
3969
+ featureBoard: this.featureBoard,
3970
+ crossAppReports: this.crossAppReports,
3971
+ allowScreenshotRemove: this.allowScreenshotRemove,
3972
+ unreadCount: () => this.unreadCount(),
3973
+ tierColor: (slug) => this.tierColor(slug),
3974
+ resolveCustomCategory: (id) => this.resolveCustomCategory(id),
3975
+ effectiveMinLength: () => this.effectiveMinLength(),
3976
+ categoryLabel: (id) => this.categoryLabel(id),
3977
+ categoryIcon: (id) => this.categoryIcon(id),
3978
+ assistantTurns: this.assistantTurns,
3979
+ assistantSending: this.assistantSending,
3980
+ assistantError: this.assistantError
3981
+ };
3811
3982
  }
3812
3983
  attachHandlers(panel) {
3813
3984
  const t = this.locale;
@@ -3835,9 +4006,38 @@ var MushiWidget = class _MushiWidget {
3835
4006
  this.step = "reports";
3836
4007
  } else if (this.step === "roadmap") {
3837
4008
  this.step = "category";
4009
+ } else if (this.step === "assistant") {
4010
+ this.step = "category";
3838
4011
  }
3839
4012
  this.render();
3840
4013
  });
4014
+ panel.querySelector('[data-action="assistant"]')?.addEventListener("click", () => {
4015
+ this.openAssistantTab();
4016
+ });
4017
+ panel.querySelectorAll('[data-action="assistant-suggest"]').forEach((btn) => {
4018
+ btn.addEventListener("click", () => {
4019
+ const value = btn.dataset.value;
4020
+ if (value) void this.sendAssistantMessage(value);
4021
+ });
4022
+ });
4023
+ {
4024
+ const form = panel.querySelector('[data-action="assistant-send"]');
4025
+ if (form) {
4026
+ const input = form.querySelector(".mushi-assistant-input");
4027
+ form.addEventListener("submit", (e) => {
4028
+ e.preventDefault();
4029
+ const value = input?.value ?? "";
4030
+ if (input) input.value = "";
4031
+ void this.sendAssistantMessage(value);
4032
+ });
4033
+ input?.addEventListener("keydown", (e) => {
4034
+ if (e.key === "Enter" && !e.shiftKey) {
4035
+ e.preventDefault();
4036
+ form.requestSubmit();
4037
+ }
4038
+ });
4039
+ }
4040
+ }
3841
4041
  panel.querySelector('[data-action="reports"]')?.addEventListener("click", () => {
3842
4042
  void this.loadReporterReports();
3843
4043
  });
@@ -3878,12 +4078,26 @@ var MushiWidget = class _MushiWidget {
3878
4078
  this.crossAppLoading = true;
3879
4079
  this.crossAppReports = null;
3880
4080
  this.render();
3881
- this.callbacks.onCrossAppReportsOpen?.();
4081
+ if (this.callbacks.onCrossAppReportsOpen) {
4082
+ this.callbacks.onCrossAppReportsOpen();
4083
+ } else {
4084
+ this.crossAppLoading = false;
4085
+ this.crossAppReports = [];
4086
+ this.render();
4087
+ }
3882
4088
  });
3883
4089
  panel.querySelector('[data-action="open-global-leaderboard"]')?.addEventListener("click", () => {
3884
4090
  this.step = "leaderboard";
3885
- this.callbacks.onGlobalLeaderboardOpen?.();
4091
+ this.globalLeaderboard = null;
4092
+ this.globalLeaderboardLoading = true;
3886
4093
  this.render();
4094
+ if (this.callbacks.onGlobalLeaderboardOpen) {
4095
+ this.callbacks.onGlobalLeaderboardOpen();
4096
+ } else {
4097
+ this.globalLeaderboardLoading = false;
4098
+ this.globalLeaderboard = [];
4099
+ this.render();
4100
+ }
3887
4101
  });
3888
4102
  panel.querySelector('[data-action="send-magic-link"]')?.addEventListener("click", () => {
3889
4103
  void this.handleMagicLinkSend(panel);
@@ -3901,6 +4115,7 @@ var MushiWidget = class _MushiWidget {
3901
4115
  this.magicLinkSent = false;
3902
4116
  this.magicLinkEmail = "";
3903
4117
  this.step = "category";
4118
+ this.callbacks.onTesterSignOut?.();
3904
4119
  this.render();
3905
4120
  });
3906
4121
  panel.querySelector('[data-action="reporter-reply"]')?.addEventListener("click", () => {
@@ -4188,6 +4403,7 @@ var MushiWidget = class _MushiWidget {
4188
4403
  }
4189
4404
  /* ── Community: magic-link sign-in ───────────────────────────────── */
4190
4405
  async handleMagicLinkSend(panel) {
4406
+ if (this.magicLinkSending) return;
4191
4407
  const emailInput = panel.querySelector('[data-role="magic-link-email"]');
4192
4408
  const email = (emailInput?.value ?? this.magicLinkEmail).trim();
4193
4409
  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
@@ -4197,13 +4413,15 @@ var MushiWidget = class _MushiWidget {
4197
4413
  }
4198
4414
  this.magicLinkEmail = email;
4199
4415
  this.magicLinkError = "";
4416
+ this.magicLinkSending = true;
4200
4417
  this.render();
4201
4418
  try {
4202
4419
  await this.callbacks.onMushiSignIn?.(email);
4203
4420
  this.magicLinkSent = true;
4204
- this.render();
4205
4421
  } catch (err) {
4206
4422
  this.magicLinkError = err instanceof Error ? err.message : "Could not send sign-in link. Try again.";
4423
+ } finally {
4424
+ this.magicLinkSending = false;
4207
4425
  this.render();
4208
4426
  }
4209
4427
  }
@@ -4707,16 +4925,10 @@ function matchesUrl(url, matcher) {
4707
4925
  }
4708
4926
  function normalizeUrlPrefix(url) {
4709
4927
  if (!url) return null;
4710
- return normalizeComparableUrl(url).replace(/\/+$/, "");
4711
- }
4712
- function isLocalhostEndpoint(url) {
4713
- if (!url) return false;
4714
- try {
4715
- const parsed = new URL(url);
4716
- return parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "::1" || parsed.hostname.endsWith(".localhost");
4717
- } catch {
4718
- return /\blocalhost\b|127\.0\.0\.1/.test(url);
4719
- }
4928
+ const normalized = normalizeComparableUrl(url);
4929
+ let end = normalized.length;
4930
+ while (end > 0 && normalized.charCodeAt(end - 1) === 47) end--;
4931
+ return normalized.slice(0, end);
4720
4932
  }
4721
4933
  function normalizeComparableUrl(url) {
4722
4934
  try {
@@ -6289,10 +6501,6 @@ function createProactiveManager(config = {}) {
6289
6501
  return { shouldShow, recordDismissal, recordSubmission, reset };
6290
6502
  }
6291
6503
 
6292
- // src/version.ts
6293
- var MUSHI_SDK_PACKAGE = "@mushi-mushi/web";
6294
- var MUSHI_SDK_VERSION = "1.14.0" ;
6295
-
6296
6504
  // src/mushi.ts
6297
6505
  var instance = null;
6298
6506
  var Mushi = class {
@@ -6303,16 +6511,17 @@ var Mushi = class {
6303
6511
  createLogger({ scope: "mushi", level: "warn", format: "pretty" }).warn("Already initialized \u2014 call destroy() first to reinitialize");
6304
6512
  return instance;
6305
6513
  }
6306
- if (!config.projectId) {
6307
- throw new Error("[mushi] projectId is required");
6514
+ const resolved = { ...resolveEnvConfig(), ...config };
6515
+ if (!resolved.projectId) {
6516
+ throw new Error("[mushi] projectId is required \u2014 set NEXT_PUBLIC_MUSHI_PROJECT_ID / VITE_MUSHI_PROJECT_ID / MUSHI_PROJECT_ID or pass it explicitly");
6308
6517
  }
6309
- if (!config.apiKey) {
6310
- throw new Error("[mushi] apiKey is required");
6518
+ if (!resolved.apiKey) {
6519
+ throw new Error("[mushi] apiKey is required \u2014 set NEXT_PUBLIC_MUSHI_API_KEY / VITE_MUSHI_API_KEY / MUSHI_API_KEY or pass it explicitly");
6311
6520
  }
6312
- if (config.enabled === false) {
6521
+ if (resolved.enabled === false) {
6313
6522
  return createNoopInstance();
6314
6523
  }
6315
- instance = createInstance(config);
6524
+ instance = createInstance(resolved);
6316
6525
  return instance;
6317
6526
  }
6318
6527
  static getInstance() {
@@ -6330,10 +6539,13 @@ function createInstance(config) {
6330
6539
  const bootstrapConfig = applyPresetConfig(config);
6331
6540
  let activeConfig = bootstrapConfig;
6332
6541
  const log = config.debug ?? false ? createLogger({ scope: "mushi", level: "debug", format: "pretty" }) : noopLogger;
6542
+ let userToken = null;
6543
+ let currentPageContext = null;
6333
6544
  const apiClient2 = createApiClient({
6334
6545
  projectId: bootstrapConfig.projectId,
6335
6546
  apiKey: bootstrapConfig.apiKey,
6336
- ...bootstrapConfig.apiEndpoint ? { apiEndpoint: bootstrapConfig.apiEndpoint } : {}
6547
+ ...bootstrapConfig.apiEndpoint ? { apiEndpoint: bootstrapConfig.apiEndpoint } : {},
6548
+ getUserToken: () => userToken
6337
6549
  });
6338
6550
  const preFilter = createPreFilter(bootstrapConfig.preFilter);
6339
6551
  const offlineQueue = createOfflineQueue(bootstrapConfig.offline);
@@ -6394,12 +6606,12 @@ function createInstance(config) {
6394
6606
  return;
6395
6607
  }
6396
6608
  const status = statusResult.data;
6397
- if (!status.is_tester) {
6609
+ if (!status.is_tester || !status.tester_id) {
6398
6610
  clearTesterJwt();
6399
6611
  return;
6400
6612
  }
6401
6613
  widget.setTesterSession(jwt, {
6402
- id: jwt.substring(0, 16),
6614
+ id: status.tester_id,
6403
6615
  public_handle: status.public_handle ?? null,
6404
6616
  display_name: status.display_name ?? null
6405
6617
  });
@@ -6711,25 +6923,29 @@ function createInstance(config) {
6711
6923
  },
6712
6924
  async onGlobalLeaderboardOpen() {
6713
6925
  widget.setGlobalLeaderboard(null, true);
6714
- const jwt = readTesterJwt();
6715
- const res = await apiClient2.getPublicLeaderboard(50);
6716
- const rawEntries = res.ok ? res.data?.leaderboard ?? [] : [];
6717
- const entries = rawEntries.map((e) => ({
6718
- tester_id: e.tester_id,
6719
- rank: e.rank,
6720
- public_handle: e.public_handle,
6721
- display_name: e.display_name,
6722
- points_30d: e.points_30d,
6723
- total_points: e.total_points ?? 0,
6724
- badge: e.badge_slug
6725
- }));
6726
- widget.setGlobalLeaderboard(entries, false);
6727
- if (jwt) {
6728
- const repRes = await apiClient2.getMyReputation(jwt);
6729
- if (repRes.ok && repRes.data) {
6730
- const repData = repRes.data;
6731
- if (repData.reputation) widget.setTesterReputation(repData.reputation);
6926
+ try {
6927
+ const jwt = readTesterJwt();
6928
+ const res = await apiClient2.getPublicLeaderboard(50);
6929
+ const rawEntries = res.ok ? res.data?.leaderboard ?? [] : [];
6930
+ const entries = rawEntries.map((e) => ({
6931
+ tester_id: e.tester_id,
6932
+ rank: e.rank,
6933
+ public_handle: e.public_handle,
6934
+ display_name: e.display_name,
6935
+ points_30d: e.points_30d,
6936
+ total_points: e.total_points ?? 0,
6937
+ badge: e.badge_slug
6938
+ }));
6939
+ widget.setGlobalLeaderboard(entries, false);
6940
+ if (jwt) {
6941
+ const repRes = await apiClient2.getMyReputation(jwt);
6942
+ if (repRes.ok && repRes.data) {
6943
+ const repData = repRes.data;
6944
+ if (repData.reputation) widget.setTesterReputation(repData.reputation);
6945
+ }
6732
6946
  }
6947
+ } catch {
6948
+ widget.setGlobalLeaderboard([], false);
6733
6949
  }
6734
6950
  },
6735
6951
  async onCrossAppReportsOpen() {
@@ -6738,9 +6954,29 @@ function createInstance(config) {
6738
6954
  widget.setCrossAppReports([], false);
6739
6955
  return;
6740
6956
  }
6741
- const res = await apiClient2.getCrossAppReports(jwt);
6742
- const reports = res.ok ? res.data?.reports ?? [] : [];
6743
- widget.setCrossAppReports(reports, false);
6957
+ try {
6958
+ const res = await apiClient2.getCrossAppReports(jwt);
6959
+ const reports = res.ok ? res.data?.reports ?? [] : [];
6960
+ widget.setCrossAppReports(reports, false);
6961
+ } catch {
6962
+ widget.setCrossAppReports([], false);
6963
+ }
6964
+ },
6965
+ onTesterSignOut() {
6966
+ clearTesterJwt();
6967
+ },
6968
+ // ── Assistant tab (P5) ───────────────────────────────────────────────
6969
+ assistantEnabled: bootstrapConfig.assistant?.enabled === true,
6970
+ ...bootstrapConfig.assistant?.label ? { assistantLabel: bootstrapConfig.assistant.label } : {},
6971
+ ...bootstrapConfig.assistant?.greeting ? { assistantGreeting: bootstrapConfig.assistant.greeting } : {},
6972
+ ...bootstrapConfig.assistant?.suggestions ? { assistantSuggestions: bootstrapConfig.assistant.suggestions } : {},
6973
+ async onAssistantAsk(message, threadId) {
6974
+ const res = await apiClient2.askAssistant({
6975
+ message,
6976
+ threadId,
6977
+ context: currentPageContext
6978
+ });
6979
+ return res.ok ? res.data ?? null : null;
6744
6980
  }
6745
6981
  }, MUSHI_SDK_VERSION);
6746
6982
  syncCaptureModules();
@@ -6830,8 +7066,8 @@ function createInstance(config) {
6830
7066
  }).catch((err) => {
6831
7067
  log.debug("Runtime SDK config fetch failed", { error: err instanceof Error ? err.message : String(err) });
6832
7068
  });
6833
- } else if (config.runtimeConfig !== false && isLocalhostEndpoint(resolveApiEndpoint(config))) {
6834
- log.debug("Runtime SDK config skipped for localhost apiEndpoint; set runtimeConfig: true to force it");
7069
+ } else {
7070
+ log.debug("Runtime SDK config disabled via runtimeConfig:false; using static bootstrap config");
6835
7071
  }
6836
7072
  void checkSdkFreshness();
6837
7073
  log.info("Initialized", { projectId: config.projectId });
@@ -7286,6 +7522,28 @@ function createInstance(config) {
7286
7522
  }
7287
7523
  }
7288
7524
  },
7525
+ identifyWithToken(token) {
7526
+ userToken = token && typeof token === "string" ? token : null;
7527
+ if (userToken) {
7528
+ const claims = parseIdentityToken(userToken);
7529
+ if (claims?.sub) {
7530
+ userInfo = {
7531
+ id: claims.sub,
7532
+ ...claims.email ? { email: claims.email } : {},
7533
+ ...claims.name ? { name: claims.name } : {}
7534
+ };
7535
+ }
7536
+ breadcrumbs.add({ category: "lifecycle", level: "info", message: "Mushi.identifyWithToken()" });
7537
+ } else {
7538
+ breadcrumbs.add({ category: "lifecycle", level: "info", message: "Mushi.identifyWithToken(null)" });
7539
+ }
7540
+ },
7541
+ publishPageContext(context) {
7542
+ currentPageContext = context && context.route ? context : null;
7543
+ },
7544
+ openAssistant() {
7545
+ widget.openAssistantTab();
7546
+ },
7289
7547
  addBreadcrumb(crumb) {
7290
7548
  breadcrumbs.add(crumb);
7291
7549
  },
@@ -7409,6 +7667,9 @@ function mergeRuntimeConfig(config, runtime) {
7409
7667
  const nativeTrigger = runtime.native?.triggerMode;
7410
7668
  const runtimeLauncher = runtime.widget?.launcher;
7411
7669
  const widgetTrigger = runtimeLauncher ?? runtime.widget?.trigger ?? (nativeTrigger === "none" || nativeTrigger === "shake" ? "manual" : void 0);
7670
+ const explicitHidden = runtimeLauncher === "hidden" || runtime.widget?.trigger === "hidden";
7671
+ const hostTrigger = config.widget?.trigger;
7672
+ const safeWidgetTrigger = widgetTrigger === "hidden" && !explicitHidden && hostTrigger && hostTrigger !== "hidden" ? hostTrigger : widgetTrigger;
7412
7673
  const runtimeWidget = runtime.widget;
7413
7674
  const runtimeBannerVariant = runtimeWidget?.bannerVariant;
7414
7675
  const runtimeBannerPosition = runtimeWidget?.bannerPosition;
@@ -7432,7 +7693,7 @@ function mergeRuntimeConfig(config, runtime) {
7432
7693
  widget: {
7433
7694
  ...config.widget,
7434
7695
  ...runtime.widget,
7435
- ...widgetTrigger ? { trigger: widgetTrigger } : {},
7696
+ ...safeWidgetTrigger ? { trigger: safeWidgetTrigger } : {},
7436
7697
  ...derivedBannerConfig ? { bannerConfig: derivedBannerConfig } : {},
7437
7698
  // betaMode is local-only: set by the host app, not the dashboard.
7438
7699
  // Restore it after the runtime spread so it is never silently cleared.
@@ -7508,9 +7769,7 @@ function resolveApiEndpoint(config) {
7508
7769
  return config.apiEndpoint ?? DEFAULT_API_ENDPOINT;
7509
7770
  }
7510
7771
  function shouldUseRuntimeConfig(config) {
7511
- if (config.runtimeConfig === false) return false;
7512
- if (config.runtimeConfig === true) return true;
7513
- return !isLocalhostEndpoint(resolveApiEndpoint(config));
7772
+ return config.runtimeConfig !== false;
7514
7773
  }
7515
7774
  async function runDiagnostics(options) {
7516
7775
  const endpoint = await probeApiEndpoint(options.apiEndpoint);
@@ -7672,6 +7931,12 @@ function createNoopInstance() {
7672
7931
  captureException: async () => null,
7673
7932
  identify: () => {
7674
7933
  },
7934
+ identifyWithToken: () => {
7935
+ },
7936
+ publishPageContext: () => {
7937
+ },
7938
+ openAssistant: () => {
7939
+ },
7675
7940
  addBreadcrumb: () => {
7676
7941
  },
7677
7942
  getBreadcrumbs: () => [],