@mushi-mushi/web 1.13.0 → 1.14.1

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.cjs CHANGED
@@ -291,17 +291,21 @@ function getAvailableLocales() {
291
291
  }
292
292
 
293
293
  // src/styles.ts
294
- function getWidgetStyles(theme) {
294
+ function getWidgetStyles(theme, accent = "", accentText = "") {
295
295
  const isDark = theme === "dark";
296
+ const safeHex = (v) => /^#[0-9a-fA-F]{3,8}$/.test(v) ? v : "";
297
+ const safeAccent = safeHex(accent);
298
+ const safeAccentText = safeHex(accentText);
296
299
  const paper = isDark ? "#0F0E0C" : "#F8F4ED";
297
300
  const ink = isDark ? "#F2EBDD" : "#0E0D0B";
298
301
  const inkMuted = isDark ? "#928B7E" : "#5C5852";
299
302
  const inkFaint = isDark ? "#5A5650" : "#9A9489";
303
+ const inkDim = isDark ? "#7A7268" : "#6E6760";
300
304
  const rule = isDark ? "rgba(242,235,221,0.10)" : "rgba(14,13,11,0.10)";
301
305
  const ruleStrong = isDark ? "rgba(242,235,221,0.18)" : "rgba(14,13,11,0.16)";
302
- const widgetAccent = isDark ? "#FF5A47" : "#E03C2C";
303
- const widgetAccentWash = isDark ? "rgba(255,90,71,0.12)" : "rgba(224,60,44,0.08)";
304
- const widgetAccentInk = isDark ? "#FFE5E0" : "#7A1F15";
306
+ const widgetAccent = safeAccent || (isDark ? "#FF5A47" : "#E03C2C");
307
+ const widgetAccentWash = isDark ? `${widgetAccent}1F` : `${widgetAccent}14`;
308
+ const widgetAccentInk = safeAccentText || (isDark ? "#FFE5E0" : "#7A1F15");
305
309
  const fontDisplay = `'Iowan Old Style', 'Palatino Linotype', 'Palatino', 'Book Antiqua', 'Cambria', Georgia, 'Times New Roman', serif`;
306
310
  const fontBody = `system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI Variable Display', 'Segoe UI', sans-serif`;
307
311
  const fontMono = `ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, Consolas, 'Liberation Mono', monospace`;
@@ -448,6 +452,33 @@ function getWidgetStyles(theme) {
448
452
  transform: scale(0.92);
449
453
  }
450
454
 
455
+ /* \u2500\u2500 Draggable FAB \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
456
+ When draggable is enabled the trigger uses CSS translate to apply the
457
+ drag offset ON TOP of the existing inset positioning, so snapping and
458
+ safe-area clamp still work correctly via the inset vars.
459
+ --mushi-drag-active 0|1 gates the transform so non-draggable FABs are
460
+ completely unaffected. touch-action: none prevents browser pan/scroll
461
+ from racing the pointer capture. */
462
+ .mushi-trigger {
463
+ touch-action: none;
464
+ translate:
465
+ calc(var(--mushi-drag-active, 0) * var(--mushi-drag-x, 0px))
466
+ calc(var(--mushi-drag-active, 0) * var(--mushi-drag-y, 0px));
467
+ }
468
+ .mushi-trigger.dragging {
469
+ cursor: grabbing !important;
470
+ z-index: calc(var(--z, 99999) + 2);
471
+ transition: none !important;
472
+ box-shadow:
473
+ 0 1px 0 ${rule},
474
+ 0 20px 40px -12px rgba(14,13,11,0.55),
475
+ inset 0 -3px 0 ${widgetAccent};
476
+ opacity: 0.92;
477
+ }
478
+ @media (prefers-reduced-motion: reduce) {
479
+ .mushi-trigger { transition: none !important; }
480
+ }
481
+
451
482
  @keyframes mushi-pulse {
452
483
  0% { box-shadow: 0 0 0 0 ${widgetAccent}; opacity: 1; }
453
484
  70% { box-shadow: 0 0 0 8px rgba(224,60,44,0); opacity: 0.5; }
@@ -458,7 +489,7 @@ function getWidgetStyles(theme) {
458
489
  position: fixed;
459
490
  width: 384px;
460
491
  max-width: calc(100vw - 32px);
461
- max-height: min(640px, calc(100vh - 120px));
492
+ max-height: min(640px, calc(100dvh - 120px - var(--mushi-keyboard-inset, 0px)));
462
493
  background: ${paper};
463
494
  border: 1px solid ${ruleStrong};
464
495
  border-radius: 6px;
@@ -470,6 +501,26 @@ function getWidgetStyles(theme) {
470
501
  display: flex;
471
502
  flex-direction: column;
472
503
  transform-origin: var(--mushi-origin, bottom right);
504
+ transition: bottom 120ms ease, top 120ms ease, max-height 120ms ease;
505
+ }
506
+ /* Keyboard-safe: on narrow viewports lift above the keyboard */
507
+ .mushi-panel.keyboard-open {
508
+ bottom: calc(var(--mushi-keyboard-inset, 0px) + 8px) !important;
509
+ }
510
+ /* On narrow mobile, fill the width as a bottom sheet */
511
+ @media (max-width: 480px) {
512
+ .mushi-panel {
513
+ left: 0 !important;
514
+ right: 0 !important;
515
+ width: 100% !important;
516
+ max-width: 100% !important;
517
+ border-bottom-left-radius: 0;
518
+ border-bottom-right-radius: 0;
519
+ bottom: var(--mushi-keyboard-inset, 0px) !important;
520
+ }
521
+ .mushi-panel.keyboard-open {
522
+ bottom: calc(var(--mushi-keyboard-inset, 0px) + 4px) !important;
523
+ }
473
524
  }
474
525
  .mushi-panel.open { animation: mushi-stamp-in 320ms ${easeStamp} both; }
475
526
  .mushi-panel.closed { display: none; }
@@ -1498,7 +1549,7 @@ function getWidgetStyles(theme) {
1498
1549
  }
1499
1550
 
1500
1551
  .mushi-beta-perks li {
1501
- font-size: 10.5px;
1552
+ font-size: 12px;
1502
1553
  color: ${widgetAccentInk};
1503
1554
  font-weight: 500;
1504
1555
  }
@@ -1510,8 +1561,8 @@ function getWidgetStyles(theme) {
1510
1561
  }
1511
1562
 
1512
1563
  .mushi-changelog-summary {
1513
- font-size: 10.5px;
1514
- color: var(--mushi-text-dim);
1564
+ font-size: 11px;
1565
+ color: ${inkDim};
1515
1566
  cursor: pointer;
1516
1567
  list-style: none;
1517
1568
  display: flex;
@@ -1541,8 +1592,8 @@ function getWidgetStyles(theme) {
1541
1592
  }
1542
1593
 
1543
1594
  .mushi-changelog-list li {
1544
- font-size: 10.5px;
1545
- color: var(--mushi-text-dim);
1595
+ font-size: 11px;
1596
+ color: ${inkDim};
1546
1597
  line-height: 1.5;
1547
1598
  }
1548
1599
 
@@ -1561,14 +1612,14 @@ function getWidgetStyles(theme) {
1561
1612
  }
1562
1613
 
1563
1614
  .mushi-beta-success-line {
1564
- font-size: 11px;
1565
- color: var(--mushi-text-dim);
1615
+ font-size: 12px;
1616
+ color: ${widgetAccentInk};
1566
1617
  line-height: 1.5;
1567
1618
  }
1568
1619
 
1569
1620
  .mushi-beta-success-dim {
1570
1621
  opacity: 0.65;
1571
- font-size: 10.5px;
1622
+ font-size: 12px;
1572
1623
  }
1573
1624
 
1574
1625
  /* \u2500\u2500\u2500 Banner launcher (trigger: 'banner') \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 */
@@ -1584,7 +1635,7 @@ function getWidgetStyles(theme) {
1584
1635
  gap: 10px;
1585
1636
  padding: 0 16px;
1586
1637
  font-family: ${fontMono};
1587
- font-size: 11.5px;
1638
+ font-size: 12px;
1588
1639
  letter-spacing: 0.04em;
1589
1640
  white-space: nowrap;
1590
1641
  overflow: hidden;
@@ -1712,7 +1763,7 @@ function getWidgetStyles(theme) {
1712
1763
  overflow: hidden;
1713
1764
  text-overflow: ellipsis;
1714
1765
  white-space: nowrap;
1715
- font-size: 11.5px;
1766
+ font-size: 12px;
1716
1767
  font-weight: 500;
1717
1768
  line-height: 1.3;
1718
1769
  opacity: 0.9;
@@ -1828,10 +1879,31 @@ function getWidgetStyles(theme) {
1828
1879
  .mushi-success-stamp-label { opacity: 1; }
1829
1880
  .mushi-success-pts-award { opacity: 1; }
1830
1881
  }
1882
+
1883
+ .mushi-community-footer{display:flex;align-items:center;gap:8px;padding:10px 0 2px;border-top:1px solid ${isDark ? "rgba(255,255,255,0.07)" : "rgba(0,0,0,0.07)"};margin-top:8px;flex-wrap:wrap}
1884
+ .mushi-community-btn{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1885
+ .mushi-link-btn{background:none;border:none;padding:4px 2px;cursor:pointer;color:${widgetAccent};font-size:12px;font-family:${fontMono};text-decoration:underline;text-underline-offset:2px}
1886
+ .mushi-link-btn:hover{opacity:0.8}
1887
+ .mushi-link-btn:focus-visible,.mushi-nav-item:focus-visible{outline:2px solid ${widgetAccent};outline-offset:2px;border-radius:2px}
1888
+ .mushi-nav-item{display:block;width:100%;text-align:left;background:${isDark ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.04)"};border:1px solid ${isDark ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.08)"};border-radius:8px;padding:10px 14px;margin-bottom:8px;cursor:pointer;font-size:13px;color:${ink};transition:background .15s,border-color .15s}
1889
+ .mushi-nav-item:hover{background:${isDark ? "rgba(255,255,255,0.09)" : "rgba(0,0,0,0.07)"}}
1890
+ .mushi-account-card{display:flex;align-items:center;gap:12px;background:${isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.04)"};border-radius:10px;padding:12px 14px;margin-bottom:14px}
1891
+ .mushi-account-avatar{width:40px;height:40px;border-radius:50%;background:${widgetAccentWash};color:${widgetAccentInk};display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:700;flex-shrink:0}
1892
+ .mushi-account-info{display:flex;flex-direction:column;gap:2px;min-width:0}
1893
+ .mushi-account-info strong{font:700 14px/1.3 inherit;color:${ink}}
1894
+ .mushi-account-rank,.mushi-xapp-app-name,.mushi-label{font-size:12px;color:${inkDim};font-family:${fontMono}}
1895
+ .mushi-account-rank{display:block}
1896
+ .mushi-xapp-app-name{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;margin:0 0 6px}
1897
+ .mushi-xapp-group{margin-bottom:14px}
1898
+ .mushi-label{display:block;font-weight:600;margin-bottom:6px}
1831
1899
  `;
1832
1900
  }
1833
1901
 
1834
- // src/widget.ts
1902
+ // src/version.ts
1903
+ var MUSHI_SDK_PACKAGE = "@mushi-mushi/web";
1904
+ var MUSHI_SDK_VERSION = "1.14.1" ;
1905
+
1906
+ // src/widget-helpers.ts
1835
1907
  var CATEGORY_ICONS = {
1836
1908
  bug: "\u26A0\uFE0F",
1837
1909
  slow: "\u{1F40C}",
@@ -1951,1365 +2023,1745 @@ function isSubmitShortcut(e) {
1951
2023
  function escapeHtml(value) {
1952
2024
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1953
2025
  }
1954
- var MushiWidget = class _MushiWidget {
1955
- constructor(config = {}, callbacks, sdkVersion = "0.7.0") {
1956
- this.sdkVersion = sdkVersion;
1957
- this.config = {
1958
- position: config.position ?? "bottom-right",
1959
- anchor: config.anchor ?? {},
1960
- theme: config.theme ?? "auto",
1961
- // Falsy-OR (NOT `??`) on purpose: `triggerText: ''` is semantically
1962
- // nonsense — it would render a labelless, glyphless trigger button
1963
- // that users can't see or aim at. Treat empty string the same as
1964
- // omitted so any caller that wires this to a cleared form input or
1965
- // pastes a legacy snippet that emitted `triggerText: ""` (see
1966
- // apps/admin/src/lib/sdkSnippets.ts widgetLines history) still gets
1967
- // the default 🐛 and a visible button.
1968
- triggerText: config.triggerText || "\u{1F41B}",
1969
- expandedTitle: config.expandedTitle ?? "",
1970
- mode: config.mode ?? "conversational",
1971
- locale: config.locale ?? "auto",
1972
- zIndex: config.zIndex ?? 99999,
1973
- trigger: config.trigger ?? "auto",
1974
- bannerConfig: config.bannerConfig ?? {},
1975
- attachToSelector: config.attachToSelector ?? "",
1976
- inset: config.inset ?? {},
1977
- respectSafeArea: config.respectSafeArea ?? true,
1978
- hideOnSelector: config.hideOnSelector ?? "",
1979
- hideOnRoutes: config.hideOnRoutes ?? [],
1980
- environments: config.environments ?? {},
1981
- smartHide: config.smartHide ?? false,
1982
- draggable: config.draggable ?? false,
1983
- brandFooter: config.brandFooter ?? true,
1984
- outdatedBanner: config.outdatedBanner ?? "auto",
1985
- betaMode: config.betaMode ?? {},
1986
- minDescriptionLength: config.minDescriptionLength ?? 20,
1987
- dashboardUrl: config.dashboardUrl ?? "",
1988
- responseSlaLabel: config.responseSlaLabel ?? "",
1989
- featureRequestCard: config.featureRequestCard ?? true,
1990
- featureRequestLabel: config.featureRequestLabel ?? "",
1991
- featureRequestDescription: config.featureRequestDescription ?? "",
1992
- avoidSelectors: config.avoidSelectors ?? [],
1993
- categories: config.categories ?? []
1994
- };
1995
- this.callbacks = callbacks;
1996
- this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
1997
- this.host = document.createElement("div");
1998
- this.host.id = "mushi-mushi-widget";
1999
- this.shadow = this.host.attachShadow({ mode: "closed" });
2000
- }
2001
- sdkVersion;
2002
- host;
2003
- shadow;
2004
- config;
2005
- callbacks;
2006
- locale;
2007
- isOpen = false;
2008
- step = "category";
2009
- /**
2010
- * The selected category id. May be a built-in `MushiReportCategory` or a
2011
- * custom id from `config.categories`. Cast to `MushiReportCategory` only
2012
- * after resolving through `resolveBaseCategory()`.
2013
- */
2014
- selectedCategory = null;
2015
- selectedIntent = null;
2016
- /**
2017
- * True when the user took the "Feature request" shortcut. We track this
2018
- * separately from `selectedCategory='other'` so the Back button on the
2019
- * details step jumps straight back to the category picker instead of
2020
- * landing on the intent picker the user explicitly skipped.
2021
- */
2022
- viaFeatureRequest = false;
2023
- screenshotAttached = false;
2024
- screenshotCapturing = false;
2025
- screenshotError = false;
2026
- allowScreenshotRemove = true;
2027
- elementSelected = false;
2028
- elementCapturing = false;
2029
- submitting = false;
2030
- /** Hint element injected outside the shadow DOM during element selection. */
2031
- selectorHint = null;
2032
- triggerVisible = true;
2033
- triggerShrunk = false;
2034
- triggerHiddenByScroll = false;
2035
- /** Milliseconds since mount — used for the 30s first-time nudge gate. */
2036
- mountedAt = null;
2037
- nudgeShown = false;
2038
- nudgeEl = null;
2039
- nudgeTimer = null;
2040
- sdkFreshness = null;
2041
- reporterReports = [];
2042
- featureBoard = [];
2043
- reporterComments = [];
2044
- selectedReportId = null;
2045
- reporterLoading = false;
2046
- reporterError = null;
2047
- attachedLaunchers = [];
2048
- smartHideCleanup = null;
2049
- smartHideTimer = null;
2050
- /** Captured at the moment of submit so the success ledger metadata
2051
- * ("REPORT · 14:23:07 JST") doesn't drift while the success step
2052
- * is on screen. */
2053
- submittedAt = null;
2054
- /** Pending success-state + auto-close timers. Tracked so destroy()
2055
- * can clear them — otherwise a host that unmounts mid-submit leaks
2056
- * this MushiWidget reference (and re-renders into a detached shadow
2057
- * root) for up to ~3.3s after destroy. */
2058
- successTimer = null;
2059
- autoCloseTimer = null;
2060
- rewardsState = null;
2061
- leaderboardEntries = null;
2062
- leaderboardLoading = false;
2063
- /** Server-confirmed id for the just-submitted report. Surfaces in
2064
- * the success step as a copyable receipt + optional deep link to
2065
- * the Mushi console (when `dashboardUrl` is configured). Cleared
2066
- * on every new `open()` so a re-opened widget never reuses a
2067
- * stale id from the previous session. */
2068
- lastReportId = null;
2069
- /** True when the just-submitted report was queued offline (no
2070
- * network, or the API errored and went into the retry queue).
2071
- * Drives a different success copy so the user knows the report
2072
- * hasn't actually reached the console yet. */
2073
- lastSubmitQueuedOffline = false;
2074
- /** Whether the user has clicked ✕ on the header banner this session. */
2075
- bannerDismissed = false;
2076
- mount() {
2077
- if (this.host.isConnected) return;
2078
- this.syncHostChromeState();
2079
- document.body.appendChild(this.host);
2080
- this.syncAttachedLaunchers();
2081
- this.syncSmartHide();
2082
- this.render();
2083
- this.mountedAt = Date.now();
2084
- }
2085
- getIsMounted() {
2086
- return this.host.isConnected;
2087
- }
2088
- updateConfig(config = {}) {
2089
- this.config = {
2090
- ...this.config,
2091
- ...config.position ? { position: config.position } : {},
2092
- ...config.anchor !== void 0 ? { anchor: config.anchor } : {},
2093
- ...config.theme ? { theme: config.theme } : {},
2094
- ...config.triggerText !== void 0 ? { triggerText: config.triggerText || "\u{1F41B}" } : {},
2095
- ...config.expandedTitle !== void 0 ? { expandedTitle: config.expandedTitle } : {},
2096
- ...config.mode ? { mode: config.mode } : {},
2097
- ...config.locale ? { locale: config.locale } : {},
2098
- ...config.zIndex !== void 0 ? { zIndex: config.zIndex } : {},
2099
- ...config.trigger ? { trigger: config.trigger } : {},
2100
- ...config.attachToSelector !== void 0 ? { attachToSelector: config.attachToSelector } : {},
2101
- ...config.inset !== void 0 ? { inset: config.inset } : {},
2102
- ...config.respectSafeArea !== void 0 ? { respectSafeArea: config.respectSafeArea } : {},
2103
- ...config.hideOnSelector !== void 0 ? { hideOnSelector: config.hideOnSelector } : {},
2104
- ...config.hideOnRoutes !== void 0 ? { hideOnRoutes: config.hideOnRoutes } : {},
2105
- ...config.environments !== void 0 ? { environments: config.environments } : {},
2106
- ...config.smartHide !== void 0 ? { smartHide: config.smartHide } : {},
2107
- ...config.draggable !== void 0 ? { draggable: config.draggable } : {},
2108
- ...config.brandFooter !== void 0 ? { brandFooter: config.brandFooter } : {},
2109
- ...config.outdatedBanner !== void 0 ? { outdatedBanner: config.outdatedBanner } : {},
2110
- ...config.betaMode !== void 0 ? { betaMode: config.betaMode } : {},
2111
- ...config.minDescriptionLength !== void 0 ? { minDescriptionLength: config.minDescriptionLength } : {},
2112
- ...config.dashboardUrl !== void 0 ? { dashboardUrl: config.dashboardUrl } : {},
2113
- ...config.responseSlaLabel !== void 0 ? { responseSlaLabel: config.responseSlaLabel } : {},
2114
- ...config.featureRequestCard !== void 0 ? { featureRequestCard: config.featureRequestCard } : {},
2115
- ...config.featureRequestLabel !== void 0 ? { featureRequestLabel: config.featureRequestLabel } : {},
2116
- ...config.featureRequestDescription !== void 0 ? { featureRequestDescription: config.featureRequestDescription } : {},
2117
- // Runtime/dashboard config delivers bannerMessage/bannerLabel via
2118
- // mergeRuntimeConfig → bannerConfig. The widget is constructed before
2119
- // that fetch resolves, so this pass-through is what makes server-driven
2120
- // banner copy actually render.
2121
- ...config.bannerConfig !== void 0 ? { bannerConfig: config.bannerConfig } : {},
2122
- ...config.categories !== void 0 ? { categories: config.categories } : {}
2123
- };
2124
- this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
2125
- if (this.host.isConnected) this.syncHostChromeState();
2126
- this.syncAttachedLaunchers();
2127
- this.syncSmartHide();
2128
- this.render();
2129
- }
2130
- // ─── Custom category helpers ──────────────────────────────────────────────
2131
- /** Find a custom category entry by id. Returns undefined for built-in ids. */
2132
- resolveCustomCategory(id) {
2133
- return this.config.categories?.find((c) => c.id === id);
2134
- }
2135
- /**
2136
- * Map a (possibly custom) category id to the built-in `MushiReportCategory`
2137
- * used for the report wire format. Falls back to `'other'`.
2138
- */
2139
- resolveBaseCategory(id) {
2140
- const BUILTIN = ["bug", "slow", "visual", "confusing", "other"];
2141
- if (BUILTIN.includes(id)) return id;
2142
- const custom = this.resolveCustomCategory(id);
2143
- return custom?.baseCategory ?? "other";
2144
- }
2145
- /** Icon for the selected category — custom entry's icon or built-in emoji. */
2146
- categoryIcon(id) {
2147
- const custom = this.resolveCustomCategory(id);
2148
- if (custom?.icon) return custom.icon;
2149
- return CATEGORY_ICONS[id] ?? "\u{1F4AC}";
2150
- }
2151
- /** Label for the selected category — custom entry label or built-in i18n string. */
2152
- categoryLabel(id) {
2153
- const custom = this.resolveCustomCategory(id);
2154
- if (custom) return custom.label;
2155
- const t = this.locale;
2156
- return t.step1.categories[id] ?? id;
2026
+
2027
+ // src/widget-render.ts
2028
+ function renderStep(ctx) {
2029
+ switch (ctx.step) {
2030
+ case "category":
2031
+ return renderCategoryStep(ctx);
2032
+ case "intent":
2033
+ return renderIntentStep(ctx);
2034
+ case "details":
2035
+ return renderDetailsStep(ctx);
2036
+ case "success":
2037
+ return renderSuccessStep(ctx);
2038
+ case "reports":
2039
+ return renderReportsStep(ctx);
2040
+ case "report-detail":
2041
+ return renderReportDetailStep(ctx);
2042
+ case "leaderboard":
2043
+ return renderLeaderboardStep(ctx);
2044
+ case "roadmap":
2045
+ return renderRoadmapStep(ctx);
2046
+ case "account":
2047
+ return renderAccountStep(ctx);
2048
+ case "cross-app-reports":
2049
+ return renderCrossAppReportsStep(ctx);
2157
2050
  }
2158
- // ─── Open / close ─────────────────────────────────────────────────────────
2159
- open(options) {
2160
- if (this.isOpen) return;
2161
- this.isOpen = true;
2162
- this.screenshotAttached = false;
2163
- this.screenshotCapturing = false;
2164
- this.screenshotError = false;
2165
- this.elementSelected = false;
2166
- this.elementCapturing = false;
2167
- this.submitting = false;
2168
- this.submittedAt = null;
2169
- this.removeSelectorHint();
2170
- this.lastReportId = null;
2171
- this.lastSubmitQueuedOffline = false;
2172
- this.viaFeatureRequest = false;
2173
- if (options?.featureRequest) {
2174
- this.selectedCategory = "other";
2175
- this.selectedIntent = FEATURE_REQUEST_INTENT;
2176
- this.viaFeatureRequest = true;
2177
- this.step = "details";
2178
- } else if (options?.category) {
2179
- this.selectedCategory = options.category;
2180
- this.selectedIntent = null;
2181
- const custom = this.resolveCustomCategory(options.category);
2182
- this.step = custom && (!custom.intents || custom.intents.length === 0) ? "details" : "intent";
2183
- } else {
2184
- this.selectedCategory = null;
2185
- this.selectedIntent = null;
2186
- this.step = "category";
2187
- }
2188
- this.render();
2189
- this.callbacks.onOpen();
2190
- }
2191
- close() {
2192
- if (!this.isOpen) return;
2193
- this.isOpen = false;
2194
- this.render();
2195
- this.callbacks.onClose();
2196
- }
2197
- /**
2198
- * Briefly highlight the trigger button (a soft pulse + tooltip) without
2199
- * opening the full reporter panel. Use for first-session welcome nudges
2200
- * and other "by the way, this exists" prompts where forcing the panel
2201
- * open would feel aggressive. Honours `position: 'none'` (no-op when
2202
- * the trigger button is hidden).
2203
- */
2204
- pulseTrigger() {
2205
- if (this.isOpen) return;
2206
- const trigger = this.shadow.querySelector(".mushi-trigger");
2207
- if (!trigger) return;
2208
- trigger.classList.add("mushi-trigger-pulse");
2209
- window.setTimeout(() => {
2210
- trigger.classList.remove("mushi-trigger-pulse");
2211
- }, 2400);
2212
- }
2213
- getIsOpen() {
2214
- return this.isOpen;
2215
- }
2216
- showTrigger() {
2217
- this.triggerVisible = true;
2218
- this.render();
2219
- }
2220
- hideTrigger() {
2221
- this.triggerVisible = false;
2222
- this.render();
2223
- }
2224
- setTrigger(trigger) {
2225
- this.updateConfig({ trigger });
2226
- }
2227
- attachTo(selectorOrElement, options = {}) {
2228
- const elements = typeof selectorOrElement === "string" ? Array.from(document.querySelectorAll(selectorOrElement)) : [selectorOrElement];
2229
- const cleanups = elements.map((el) => {
2230
- const onClick = (event) => {
2231
- event.preventDefault();
2232
- this.updateConfig(options);
2233
- this.open();
2234
- };
2235
- el.addEventListener("click", onClick);
2236
- return () => el.removeEventListener("click", onClick);
2237
- });
2238
- return () => cleanups.forEach((cleanup) => cleanup());
2239
- }
2240
- setScreenshotAttached(attached) {
2241
- this.screenshotAttached = attached;
2242
- if (this.isOpen) this.render();
2243
- }
2244
- setAllowScreenshotRemove(allow) {
2245
- this.allowScreenshotRemove = allow;
2246
- if (this.isOpen) this.render();
2247
- }
2248
- setElementSelected(selected) {
2249
- this.elementSelected = selected;
2250
- this.elementCapturing = false;
2251
- this.removeSelectorHint();
2252
- if (this.isOpen) this.render();
2253
- }
2254
- setScreenshotCapturing(capturing) {
2255
- this.screenshotCapturing = capturing;
2256
- this.screenshotError = false;
2257
- if (this.isOpen) this.render();
2258
- }
2259
- setScreenshotError(failed) {
2260
- this.screenshotError = failed;
2261
- this.screenshotCapturing = false;
2262
- if (this.isOpen) this.render();
2051
+ }
2052
+ function renderOutdatedBanner(ctx) {
2053
+ if (!ctx.sdkFreshness) return "";
2054
+ if (ctx.config.outdatedBanner === "off" || ctx.config.outdatedBanner === "console-only") return "";
2055
+ const { latest, current, deprecated, message } = ctx.sdkFreshness;
2056
+ if (!latest && !deprecated) return "";
2057
+ return `
2058
+ <div class="mushi-outdated" role="status">
2059
+ <strong>Mushi SDK ${escapeHtml(current)}</strong>
2060
+ ${latest ? `latest is ${escapeHtml(latest)}.` : "needs attention."}
2061
+ ${message ? `<span>${escapeHtml(message)}</span>` : ""}
2062
+ </div>
2063
+ `;
2064
+ }
2065
+ function renderBrandFooter(ctx) {
2066
+ if (ctx.config.brandFooter === false) return "";
2067
+ return `<div class="mushi-brand-footer">Powered by Mushi v${escapeHtml(ctx.sdkVersion)}</div>`;
2068
+ }
2069
+ function renderHeader(ctx, opts) {
2070
+ const t = ctx.locale;
2071
+ const { title, showBack = false, step, eyebrow } = opts;
2072
+ 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>`;
2073
+ const counterHtml = step ? `<span class="mushi-step-counter" aria-label="Step ${step} of ${TOTAL_STEPS}"><b>${pad2(step)}</b> / ${pad2(TOTAL_STEPS)}</span>` : "";
2074
+ return `
2075
+ <div class="mushi-header">
2076
+ <div class="mushi-header-mark" aria-hidden="true">\u866B</div>
2077
+ <div class="mushi-header-titles">
2078
+ ${eyebrowHtml}
2079
+ <h3>${title}</h3>
2080
+ </div>
2081
+ <div class="mushi-header-meta">
2082
+ ${counterHtml}
2083
+ <button type="button" class="mushi-close" data-action="close" aria-label="${t.widget.close}">\u2715</button>
2084
+ </div>
2085
+ </div>
2086
+ `;
2087
+ }
2088
+ function renderStepIndicator(_ctx, currentStep) {
2089
+ const segments = [];
2090
+ for (let i = 1; i <= TOTAL_STEPS; i++) {
2091
+ const cls = i < currentStep ? "mushi-step-num done" : i === currentStep ? "mushi-step-num active" : "mushi-step-num";
2092
+ segments.push(`<span class="${cls}">${pad2(i)}</span>`);
2093
+ if (i < TOTAL_STEPS) segments.push('<span class="mushi-step-sep" aria-hidden="true"></span>');
2094
+ }
2095
+ return `<div class="mushi-step-indicator" aria-hidden="true">${segments.join("")}</div>`;
2096
+ }
2097
+ function renderCategoryStep(ctx) {
2098
+ const t = ctx.locale;
2099
+ const categoryEntries = ctx.config.categories && ctx.config.categories.length > 0 ? ctx.config.categories.map((c) => ({
2100
+ id: c.id,
2101
+ icon: c.icon ?? "\u{1F4AC}",
2102
+ label: c.label,
2103
+ desc: c.description ?? ""
2104
+ })) : ["bug", "slow", "visual", "confusing", "other"].map((id) => ({
2105
+ id,
2106
+ icon: CATEGORY_ICONS[id],
2107
+ label: t.step1.categories[id],
2108
+ desc: t.step1.categoryDescriptions[id]
2109
+ }));
2110
+ const categories = categoryEntries.map(({ id, icon, label, desc }) => `
2111
+ <button type="button" class="mushi-option-btn" data-category="${escapeHtml(id)}" role="radio" aria-checked="false">
2112
+ <span class="mushi-option-icon" aria-hidden="true">${escapeHtml(icon)}</span>
2113
+ <div class="mushi-option-text">
2114
+ <span class="mushi-option-label">${escapeHtml(label)}</span>
2115
+ ${desc ? `<span class="mushi-option-desc">${escapeHtml(desc)}</span>` : ""}
2116
+ </div>
2117
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2118
+ </button>
2119
+ `).join("");
2120
+ return `
2121
+ ${renderHeader(ctx, { title: t.step1.heading, step: STEP_NUMBER.category })}
2122
+ ${ctx.config.betaMode?.enabled ? renderBetaStrip(ctx) : ""}
2123
+ <div class="mushi-body" role="radiogroup" aria-label="${t.step1.heading}">
2124
+ <button type="button" class="mushi-option-btn mushi-reports-entry" data-action="reports">
2125
+ <span class="mushi-option-icon" aria-hidden="true">\u{1F4EC}</span>
2126
+ <div class="mushi-option-text">
2127
+ <span class="mushi-option-label">Your reports${ctx.unreadCount() ? ` (${ctx.unreadCount()} new)` : ""}</span>
2128
+ <span class="mushi-option-desc">See status, developer replies, and respond</span>
2129
+ </div>
2130
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2131
+ </button>
2132
+ ${renderFeatureRequestEntry(ctx)}
2133
+ ${ctx.callbacks.onFeatureBoardRequest ? `
2134
+ <button type="button" class="mushi-option-btn" data-action="roadmap">
2135
+ <span class="mushi-option-icon" aria-hidden="true">\u{1F5F3}\uFE0F</span>
2136
+ <div class="mushi-option-text">
2137
+ <span class="mushi-option-label">Community ideas</span>
2138
+ <span class="mushi-option-desc">Vote on features and see what shipped</span>
2139
+ </div>
2140
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2141
+ </button>` : ""}
2142
+ ${categories}
2143
+ ${ctx.rewardsState ? renderRewardsNudge(ctx) : ""}
2144
+ <div class="mushi-community-footer">
2145
+ <button type="button" class="mushi-link-btn mushi-community-btn" data-action="open-account">
2146
+ ${ctx.testerInfo ? `\u{1F464} ${escapeHtml(ctx.testerInfo.public_handle ?? ctx.testerInfo.display_name ?? "My account")}` : "\u{1F310} Join community \xB7 Track reports across apps"}
2147
+ </button>
2148
+ ${ctx.rewardsState ? `<button type="button" class="mushi-link-btn" data-action="open-leaderboard">\u{1F3C6} Leaderboard</button>` : ""}
2149
+ </div>
2150
+ </div>
2151
+ ${renderStepIndicator(ctx, STEP_NUMBER.category)}
2152
+ `;
2153
+ }
2154
+ function renderFeatureRequestEntry(ctx) {
2155
+ const enabled = ctx.config.featureRequestCard !== false;
2156
+ if (!enabled) return "";
2157
+ const label = ctx.config.featureRequestLabel || "Feature request";
2158
+ const desc = ctx.config.featureRequestDescription || "Suggest something new \u2014 even rough ideas help us prioritise";
2159
+ return `
2160
+ <button
2161
+ type="button"
2162
+ class="mushi-option-btn mushi-feature-entry"
2163
+ data-action="feature-request"
2164
+ aria-label="${escapeHtml(label)}"
2165
+ >
2166
+ <span class="mushi-option-icon" aria-hidden="true">\u2728</span>
2167
+ <div class="mushi-option-text">
2168
+ <span class="mushi-option-label">${escapeHtml(label)}</span>
2169
+ <span class="mushi-option-desc">${escapeHtml(desc)}</span>
2170
+ </div>
2171
+ <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2172
+ </button>
2173
+ `;
2174
+ }
2175
+ function renderBetaChangelog(ctx) {
2176
+ const entries = ctx.config.betaMode?.changelogItems;
2177
+ if (!entries?.length) return "";
2178
+ const latest = entries[0];
2179
+ const items = latest.items.map((item) => `<li>\u2022 ${escapeHtml(item)}</li>`).join("");
2180
+ const label = latest.date ? `What\u2019s new in ${escapeHtml(latest.version)} \xB7 ${escapeHtml(latest.date)}` : `What\u2019s new in ${escapeHtml(latest.version)}`;
2181
+ return `
2182
+ <details class="mushi-changelog">
2183
+ <summary class="mushi-changelog-summary">${label}</summary>
2184
+ <ul class="mushi-changelog-list">${items}</ul>
2185
+ </details>
2186
+ `;
2187
+ }
2188
+ function renderBetaStrip(ctx) {
2189
+ const beta = ctx.config.betaMode;
2190
+ const appName = escapeHtml(beta.appName ?? "This app");
2191
+ const message = beta.message ? escapeHtml(beta.message) : `${appName} is in early development \u2014 updates ship weekly`;
2192
+ const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
2193
+ const perks = beta.perks ?? [];
2194
+ return `
2195
+ <div class="mushi-beta-strip" role="note" aria-label="Beta status">
2196
+ <div class="mushi-beta-strip-row">
2197
+ <span class="mushi-beta-tag" aria-hidden="true">BETA</span>
2198
+ <span class="mushi-beta-msg">${message}</span>
2199
+ </div>
2200
+ ${email ? `<div class="mushi-beta-contact-hint">Reports go to ${email} \xB7 reviewed by the team</div>` : ""}
2201
+ ${perks.length > 0 ? `
2202
+ <ul class="mushi-beta-perks" aria-label="Beta tester perks">
2203
+ ${perks.map((p) => `<li>\u2713 ${escapeHtml(p)}</li>`).join("")}
2204
+ </ul>
2205
+ ` : ""}
2206
+ ${renderBetaChangelog(ctx)}
2207
+ </div>
2208
+ `;
2209
+ }
2210
+ function renderReportsStep(ctx) {
2211
+ const reports = ctx.reporterReports.map((report) => {
2212
+ const title = report.summary ?? report.description ?? `Report ${report.id.slice(0, 8)}`;
2213
+ const tone = reporterStatusTone(report.status);
2214
+ const when = formatRelativeTime(report.created_at);
2215
+ const unread = report.unread_count && report.unread_count > 0 ? `<span class="mushi-unread-badge" aria-label="${report.unread_count} unread">${report.unread_count}</span>` : "";
2216
+ return `
2217
+ <button type="button" class="mushi-report-row" data-report-id="${escapeHtml(report.id)}" aria-label="View report: ${escapeHtml(title)}">
2218
+ <div class="mushi-report-main">
2219
+ <span class="mushi-report-title">${escapeHtml(title)}</span>
2220
+ <span class="mushi-report-meta">
2221
+ <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusShort(report.status))}</span>
2222
+ ${when ? `<span class="mushi-report-when">${escapeHtml(when)}</span>` : ""}
2223
+ ${unread}
2224
+ </span>
2225
+ </div>
2226
+ <span class="mushi-report-chevron" aria-hidden="true">\u203A</span>
2227
+ </button>`;
2228
+ }).join("");
2229
+ const leaderboardBtn = ctx.rewardsState ? `<button type="button" class="mushi-leaderboard-link" data-action="open-leaderboard">\u{1F3C6} Leaderboard</button>` : "";
2230
+ return `
2231
+ ${renderHeader(ctx, { title: "Your reports", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
2232
+ <div class="mushi-body">
2233
+ ${ctx.reporterLoading ? '<p class="mushi-muted">Loading reports\u2026</p>' : ""}
2234
+ ${ctx.reporterError ? `<p class="mushi-error-inline">${escapeHtml(ctx.reporterError)}</p>` : ""}
2235
+ ${reports || (!ctx.reporterLoading ? '<p class="mushi-muted">No reports from this browser yet.</p>' : "")}
2236
+ ${leaderboardBtn}
2237
+ </div>
2238
+ `;
2239
+ }
2240
+ function renderRoadmapStep(ctx) {
2241
+ const rows = ctx.featureBoard.map((ticket) => {
2242
+ const id = String(ticket.id ?? "");
2243
+ const subject = escapeHtml(String(ticket.subject ?? "Untitled idea"));
2244
+ const votes = Number(ticket.vote_count ?? 0);
2245
+ const shipped = Boolean(ticket.shipped_at);
2246
+ const voted = Boolean(ticket.my_vote);
2247
+ const status = shipped ? "Shipped" : String(ticket.status_label ?? ticket.status ?? "open");
2248
+ return `
2249
+ <div class="mushi-report-row mushi-roadmap-row">
2250
+ <div class="mushi-report-main">
2251
+ <span class="mushi-report-title">${subject}</span>
2252
+ <span class="mushi-report-meta">
2253
+ <span class="mushi-report-status">${escapeHtml(status)}</span>
2254
+ <span class="mushi-report-when">${votes} vote${votes === 1 ? "" : "s"}</span>
2255
+ </span>
2256
+ </div>
2257
+ ${ctx.callbacks.onFeatureBoardVote ? `
2258
+ <button type="button" class="mushi-vote-btn" data-vote-id="${escapeHtml(id)}" aria-pressed="${voted}">
2259
+ ${voted ? "Voted" : "Vote"}
2260
+ </button>` : ""}
2261
+ </div>`;
2262
+ }).join("");
2263
+ return `
2264
+ ${renderHeader(ctx, { title: "Community ideas", showBack: true, eyebrow: "Mushi \xB7 Roadmap" })}
2265
+ <div class="mushi-body">
2266
+ ${ctx.reporterLoading ? '<p class="mushi-muted">Loading ideas\u2026</p>' : ""}
2267
+ ${ctx.reporterError ? `<p class="mushi-error-inline">${escapeHtml(ctx.reporterError)}</p>` : ""}
2268
+ ${rows || (!ctx.reporterLoading ? '<p class="mushi-muted">No community ideas yet. Be the first to suggest one.</p>' : "")}
2269
+ </div>
2270
+ `;
2271
+ }
2272
+ function renderLeaderboardStep(ctx) {
2273
+ const isGlobal = ctx.globalLeaderboard !== null || ctx.globalLeaderboardLoading;
2274
+ const entries = isGlobal ? ctx.globalLeaderboard ?? [] : (ctx.leaderboardEntries ?? []).map((e) => ({
2275
+ tester_id: "",
2276
+ public_handle: null,
2277
+ display_name: e.display_name,
2278
+ rank: 0,
2279
+ points_30d: e.points_30d,
2280
+ total_points: e.total_points
2281
+ }));
2282
+ const loading = isGlobal ? ctx.globalLeaderboardLoading : ctx.leaderboardLoading;
2283
+ const myRank = ctx.testerReputation?.rank ?? null;
2284
+ const rows = entries.map((e, i) => {
2285
+ const rank = e.rank || i + 1;
2286
+ const isMe = ctx.testerReputation && e.tester_id === ctx.testerReputation.tester_id;
2287
+ return `
2288
+ <div class="mushi-lb-row ${rank === 1 ? "mushi-lb-top" : ""}${isMe ? " mushi-lb-me" : ""}">
2289
+ <span class="mushi-lb-rank">#${rank}</span>
2290
+ <span class="mushi-lb-name">${escapeHtml(e.public_handle ?? e.display_name ?? "Anon")}</span>
2291
+ <span class="mushi-lb-pts">${(e.points_30d ?? e.total_points).toLocaleString()} pts</span>
2292
+ </div>
2293
+ `;
2294
+ }).join("");
2295
+ 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>` : "";
2296
+ return `
2297
+ ${renderHeader(ctx, { title: "\u{1F3C6} Global Leaderboard", showBack: true, eyebrow: "Mushi \xB7 Community" })}
2298
+ <div class="mushi-body">
2299
+ ${loading ? '<p class="mushi-muted">Loading leaderboard\u2026</p>' : ""}
2300
+ ${!loading && !entries.length ? '<p class="mushi-muted">No contributors yet \u2014 be the first!</p>' : ""}
2301
+ <div class="mushi-lb-list">${rows}</div>
2302
+ ${myRankBadge}
2303
+ <p class="mushi-lb-note">Global contributors this month \xB7 Points refresh monthly</p>
2304
+ </div>
2305
+ `;
2306
+ }
2307
+ function renderAccountStep(ctx) {
2308
+ const tester = ctx.testerInfo;
2309
+ if (tester) {
2310
+ const handle = tester.public_handle ?? tester.display_name ?? "Tester";
2311
+ const rep = ctx.testerReputation;
2312
+ return `
2313
+ ${renderHeader(ctx, { title: "\u866B Mushi Account", showBack: true, eyebrow: "Mushi \xB7 Identity" })}
2314
+ <div class="mushi-body">
2315
+ <div class="mushi-account-card">
2316
+ <div class="mushi-account-avatar">${escapeHtml(handle.charAt(0).toUpperCase())}</div>
2317
+ <div class="mushi-account-info">
2318
+ <strong>${escapeHtml(handle)}</strong>
2319
+ ${rep ? `<span class="mushi-account-rank">Rank #${rep.rank ?? "\u2014"} \xB7 ${(rep.points_30d ?? 0).toLocaleString()} pts this month</span>` : ""}
2320
+ </div>
2321
+ </div>
2322
+ <button type="button" class="mushi-nav-item" data-action="open-cross-app-reports">
2323
+ My reports across all apps \u2192
2324
+ </button>
2325
+ <button type="button" class="mushi-nav-item" data-action="open-global-leaderboard">
2326
+ View global leaderboard \u2192
2327
+ </button>
2328
+ <button type="button" class="mushi-link-btn" data-action="sign-out-tester">Sign out</button>
2329
+ </div>
2330
+ `;
2263
2331
  }
2264
- setElementCapturing(capturing) {
2265
- this.elementCapturing = capturing;
2266
- if (capturing) {
2267
- this.showSelectorHint();
2268
- } else {
2269
- this.removeSelectorHint();
2270
- }
2271
- if (this.isOpen) this.render();
2332
+ if (ctx.magicLinkSent) {
2333
+ return `
2334
+ ${renderHeader(ctx, { title: "\u866B Check your email", showBack: true, eyebrow: "Mushi \xB7 Sign in" })}
2335
+ <div class="mushi-body">
2336
+ <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>
2337
+ <button type="button" class="mushi-link-btn" data-action="resend-magic-link">Resend email</button>
2338
+ ${ctx.magicLinkError ? `<p class="mushi-error">${escapeHtml(ctx.magicLinkError)}</p>` : ""}
2339
+ </div>
2340
+ `;
2272
2341
  }
2273
- /** Hide the widget panel (but keep the host element) during element selection
2274
- * so the user can click any element on the page without the panel
2275
- * intercepting the event. */
2276
- hidePanel() {
2277
- const panel = this.shadow.querySelector(".mushi-panel");
2278
- if (panel) panel.style.display = "none";
2342
+ return `
2343
+ ${renderHeader(ctx, { title: "\u866B Join the community", showBack: true, eyebrow: "Mushi \xB7 Sign in" })}
2344
+ <div class="mushi-body">
2345
+ <p class="mushi-muted">Sign in to see your reports across all apps and climb the global leaderboard. No password needed.</p>
2346
+ <label class="mushi-label" for="mushi-email-input">Email address</label>
2347
+ <input
2348
+ id="mushi-email-input"
2349
+ type="email"
2350
+ class="mushi-textarea"
2351
+ data-role="magic-link-email"
2352
+ placeholder="you@example.com"
2353
+ autocomplete="email"
2354
+ value="${escapeHtml(ctx.magicLinkEmail)}"
2355
+ style="padding: 10px 12px; height: auto; resize: none;"
2356
+ />
2357
+ ${ctx.magicLinkError ? `<p class="mushi-error">${escapeHtml(ctx.magicLinkError)}</p>` : ""}
2358
+ <button type="button" class="mushi-submit" data-action="send-magic-link"${ctx.magicLinkSending ? ' disabled aria-disabled="true"' : ""}>
2359
+ <span>${ctx.magicLinkSending ? "Sending\u2026" : "Send sign-in link"}</span><span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
2360
+ </button>
2361
+ </div>
2362
+ `;
2363
+ }
2364
+ function renderCrossAppReportsStep(ctx) {
2365
+ const reports = ctx.crossAppReports ?? [];
2366
+ const grouped = /* @__PURE__ */ new Map();
2367
+ for (const r of reports) {
2368
+ const key = r.project_id ?? "unknown";
2369
+ if (!grouped.has(key)) grouped.set(key, { name: r.app_name ?? "Unknown App", reports: [] });
2370
+ grouped.get(key).reports.push(r);
2371
+ }
2372
+ const rows = [...grouped.entries()].map(([, group]) => `
2373
+ <div class="mushi-xapp-group">
2374
+ <h4 class="mushi-xapp-app-name">${escapeHtml(group.name)}</h4>
2375
+ ${group.reports.map((r) => {
2376
+ const tone = reporterStatusTone(r.status);
2377
+ return `
2378
+ <div class="mushi-report-row" data-report-id="${escapeHtml(r.id)}" tabindex="0" role="button">
2379
+ <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusShort(r.status))}</span>
2380
+ <span class="mushi-report-title">${escapeHtml(r.title ?? r.category)}</span>
2381
+ <span class="mushi-report-when">${escapeHtml(formatRelativeTime(r.created_at))}</span>
2382
+ </div>
2383
+ `;
2384
+ }).join("")}
2385
+ </div>
2386
+ `).join("");
2387
+ return `
2388
+ ${renderHeader(ctx, { title: "My reports", showBack: true, eyebrow: "Mushi \xB7 All apps" })}
2389
+ <div class="mushi-body">
2390
+ ${ctx.crossAppLoading ? '<p class="mushi-muted">Loading your reports\u2026</p>' : ""}
2391
+ ${!ctx.crossAppLoading && !reports.length ? '<p class="mushi-muted">No reports filed yet.</p>' : ""}
2392
+ ${rows}
2393
+ </div>
2394
+ `;
2395
+ }
2396
+ function renderReportDetailStep(ctx) {
2397
+ const report = ctx.reporterReports.find((r) => r.id === ctx.selectedReportId);
2398
+ const status = report?.status ?? "unknown";
2399
+ const tone = reporterStatusTone(status);
2400
+ const when = report?.created_at ? formatRelativeTime(report.created_at) : "";
2401
+ const comments = ctx.reporterComments.map((comment) => `
2402
+ <div class="mushi-thread-comment ${comment.author_kind}">
2403
+ <strong>${escapeHtml(comment.author_kind === "reporter" ? "You" : comment.author_name ?? "Developer")}</strong>
2404
+ <p>${escapeHtml(comment.body)}</p>
2405
+ </div>
2406
+ `).join("");
2407
+ return `
2408
+ ${renderHeader(ctx, { title: "Report thread", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
2409
+ <div class="mushi-body">
2410
+ <div class="mushi-thread-summary">
2411
+ <div class="mushi-thread-summary-meta">
2412
+ <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusLabel(status))}</span>
2413
+ ${when ? `<span class="mushi-report-when">Reported ${escapeHtml(when)}</span>` : ""}
2414
+ </div>
2415
+ <p>${escapeHtml(report?.summary ?? report?.description ?? "Report details")}</p>
2416
+ </div>
2417
+ <div class="mushi-thread">
2418
+ ${ctx.reporterLoading ? '<p class="mushi-muted">Loading thread\u2026</p>' : comments || '<p class="mushi-muted">No developer replies yet.</p>'}
2419
+ </div>
2420
+ ${["fixed", "resolved", "verified"].includes(status) ? `
2421
+ <div class="mushi-verify-actions" role="group" aria-label="Fix verification">
2422
+ <button type="button" class="mushi-intent-btn" data-action="reporter-confirms">Yes, fixed for me</button>
2423
+ <button type="button" class="mushi-intent-btn" data-action="reporter-not-fixed">Not fixed yet</button>
2424
+ </div>
2425
+ ` : ""}
2426
+ <textarea class="mushi-textarea" data-role="reporter-reply" rows="3" placeholder="Reply to the developer\u2026"></textarea>
2427
+ <button type="button" class="mushi-submit" data-action="reporter-reply">
2428
+ <span>Reply</span><span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
2429
+ </button>
2430
+ </div>
2431
+ `;
2432
+ }
2433
+ function renderIntentStep(ctx) {
2434
+ const t = ctx.locale;
2435
+ const catId = ctx.selectedCategory;
2436
+ const customEntry = ctx.resolveCustomCategory(catId);
2437
+ const intents = customEntry?.intents ?? (t.step2.intents[catId] || []);
2438
+ const options = intents.map((intent) => `
2439
+ <button type="button" class="mushi-intent-btn" data-intent="${escapeHtml(intent)}">
2440
+ ${escapeHtml(intent)}
2441
+ </button>
2442
+ `).join("");
2443
+ const icon = ctx.categoryIcon(catId);
2444
+ const label = ctx.categoryLabel(catId);
2445
+ return `
2446
+ ${renderHeader(ctx, { title: t.step2.heading, showBack: true, step: STEP_NUMBER.intent })}
2447
+ <div class="mushi-body">
2448
+ <div class="mushi-selected-category">
2449
+ <span aria-hidden="true">${escapeHtml(icon)}</span>
2450
+ <span>${escapeHtml(label)}</span>
2451
+ </div>
2452
+ <div class="mushi-intents">
2453
+ ${options}
2454
+ </div>
2455
+ </div>
2456
+ ${renderStepIndicator(ctx, STEP_NUMBER.intent)}
2457
+ `;
2458
+ }
2459
+ function renderDetailsStep(ctx) {
2460
+ const t = ctx.locale;
2461
+ const minLen = ctx.effectiveMinLength();
2462
+ const screenshotLabel = ctx.screenshotCapturing ? t.step3.screenshotCapturing : ctx.screenshotError ? t.step3.screenshotFailed : ctx.screenshotAttached ? t.step3.screenshotAttached : t.step3.screenshotButton;
2463
+ const screenshotClass = [
2464
+ "mushi-attach-btn",
2465
+ ctx.screenshotAttached ? "active" : "",
2466
+ ctx.screenshotError ? "error" : "",
2467
+ ctx.screenshotCapturing ? "loading" : ""
2468
+ ].filter(Boolean).join(" ");
2469
+ const elementLabel = ctx.elementCapturing ? t.step3.elementCapturing : ctx.elementSelected ? t.step3.elementSelected : t.step3.elementButton;
2470
+ const elementClass = [
2471
+ "mushi-attach-btn",
2472
+ ctx.elementSelected ? "active" : "",
2473
+ ctx.elementCapturing ? "loading" : ""
2474
+ ].filter(Boolean).join(" ");
2475
+ const exampleChips = t.step3.examplePrompts.map((p) => `<button type="button" class="mushi-example-chip" data-example="${escapeHtml(p)}">${escapeHtml(p)}</button>`).join("");
2476
+ return `
2477
+ ${renderHeader(ctx, { title: t.step3.heading, showBack: true, step: STEP_NUMBER.details })}
2478
+ <div class="mushi-body">
2479
+ <div class="mushi-example-chips" aria-label="Example prompts">${exampleChips}</div>
2480
+ <div class="mushi-textarea-wrap">
2481
+ <textarea
2482
+ class="mushi-textarea"
2483
+ placeholder="${t.step3.descriptionPlaceholder}"
2484
+ rows="4"
2485
+ aria-label="${t.step3.heading}"
2486
+ autofocus
2487
+ ></textarea>
2488
+ <div class="mushi-char-counter" data-role="char-counter" aria-hidden="true">
2489
+ <span data-role="char-current">0</span>/<span data-role="char-min">${minLen}</span>
2490
+ </div>
2491
+ </div>
2492
+ <div class="mushi-attachments">
2493
+ <button type="button" class="${screenshotClass}"
2494
+ data-action="screenshot"
2495
+ ${ctx.screenshotCapturing ? "disabled" : ""}
2496
+ aria-label="${escapeHtml(screenshotLabel)}"
2497
+ >
2498
+ ${ctx.screenshotCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F4F8}"}
2499
+ ${escapeHtml(screenshotLabel)}
2500
+ </button>
2501
+ ${ctx.screenshotAttached && ctx.allowScreenshotRemove ? '<button type="button" class="mushi-attach-btn danger" data-action="remove-screenshot" aria-label="Remove screenshot">\u2715 Remove</button>' : ""}
2502
+ ${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>' : ""}
2503
+ <button type="button" class="${elementClass}"
2504
+ data-action="element"
2505
+ ${ctx.elementCapturing ? "disabled" : ""}
2506
+ aria-label="${escapeHtml(elementLabel)}"
2507
+ >
2508
+ ${ctx.elementCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F3AF}"}
2509
+ ${escapeHtml(elementLabel)}
2510
+ </button>
2511
+ </div>
2512
+ <div class="mushi-error" style="display:none" role="alert"></div>
2513
+ </div>
2514
+ <div class="mushi-footer">
2515
+ <span class="mushi-footer-hint" aria-hidden="true">\u2318 + ENTER \u2192 send</span>
2516
+ <button type="button" class="mushi-submit" data-action="submit"${ctx.submitting ? " disabled" : ""}>
2517
+ <span>${ctx.submitting ? t.widget.submitting : t.widget.submit}</span>
2518
+ <span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
2519
+ </button>
2520
+ </div>
2521
+ ${renderStepIndicator(ctx, STEP_NUMBER.details)}
2522
+ `;
2523
+ }
2524
+ function renderSuccessStep(ctx) {
2525
+ const t = ctx.locale;
2526
+ const stamp = ctx.submittedAt ?? /* @__PURE__ */ new Date();
2527
+ const time = stamp.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
2528
+ return `
2529
+ ${renderHeader(ctx, { title: t.widget.title, eyebrow: "Mushi \xB7 Receipt" })}
2530
+ <div class="mushi-body">
2531
+ <div class="mushi-success">
2532
+ <div class="mushi-success-stamp" aria-hidden="true">
2533
+ <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"><circle cx="50" cy="50" r="44"/></svg>
2534
+ <span class="mushi-success-stamp-label">\u53D7</span>
2535
+ </div>
2536
+ <div class="mushi-success-headline">${t.widget.submitted}</div>
2537
+ <div class="mushi-success-meta">REPORT \xB7 ${time}</div>
2538
+ ${renderSuccessReceipt(ctx)}
2539
+ ${ctx.rewardsState ? renderSuccessRewards(ctx) : ""}
2540
+ ${ctx.config.betaMode?.enabled ? renderBetaSuccessFooter(ctx) : ""}
2541
+ </div>
2542
+ </div>
2543
+ `;
2544
+ }
2545
+ function renderSuccessReceipt(ctx) {
2546
+ if (ctx.lastSubmitQueuedOffline) {
2547
+ return `
2548
+ <div class="mushi-success-receipt" role="status">
2549
+ <div class="mushi-success-receipt-row mushi-success-receipt-warn">
2550
+ <span class="mushi-success-receipt-label">Queued offline</span>
2551
+ <span class="mushi-success-receipt-hint">We&rsquo;ll send it the moment you&rsquo;re back online.</span>
2552
+ </div>
2553
+ </div>
2554
+ `;
2279
2555
  }
2280
- showPanel() {
2281
- const panel = this.shadow.querySelector(".mushi-panel");
2282
- if (panel) panel.style.display = "";
2556
+ if (!ctx.lastReportId) {
2557
+ return `
2558
+ <div class="mushi-success-receipt" role="status">
2559
+ <div class="mushi-success-receipt-row">
2560
+ <span class="mushi-success-receipt-spinner" aria-hidden="true"></span>
2561
+ <span class="mushi-success-receipt-hint">Delivering to the team\u2026</span>
2562
+ </div>
2563
+ ${renderSlaLine(ctx)}
2564
+ </div>
2565
+ `;
2283
2566
  }
2284
- showSelectorHint() {
2285
- this.removeSelectorHint();
2286
- const hint = document.createElement("div");
2287
- hint.id = "mushi-selector-hint";
2288
- hint.setAttribute("role", "status");
2289
- hint.setAttribute("aria-live", "polite");
2290
- hint.style.cssText = `
2291
- position: fixed;
2292
- bottom: 24px;
2293
- left: 50%;
2294
- transform: translateX(-50%);
2295
- z-index: 2147483646;
2296
- background: rgba(17,17,17,0.92);
2297
- color: #fff;
2298
- font-family: ui-monospace, SFMono-Regular, monospace;
2299
- font-size: 12px;
2300
- letter-spacing: 0.04em;
2301
- padding: 8px 16px;
2302
- border-radius: 20px;
2303
- pointer-events: none;
2304
- white-space: nowrap;
2305
- backdrop-filter: blur(4px);
2306
- box-shadow: 0 2px 12px rgba(0,0,0,0.35);
2567
+ const idShort = `#${ctx.lastReportId.slice(0, 8)}`;
2568
+ const dashboard = (ctx.config.dashboardUrl ?? "").replace(/\/$/, "");
2569
+ const trackHref = dashboard ? `${dashboard}/reports/${encodeURIComponent(ctx.lastReportId)}` : "";
2570
+ return `
2571
+ <div class="mushi-success-receipt" role="status">
2572
+ <div class="mushi-success-receipt-row">
2573
+ <span class="mushi-success-receipt-label">Receipt</span>
2574
+ <button
2575
+ type="button"
2576
+ class="mushi-success-receipt-id"
2577
+ data-action="copy-report-id"
2578
+ data-copy-id="${escapeHtml(ctx.lastReportId)}"
2579
+ title="Copy report id ${escapeHtml(ctx.lastReportId)}"
2580
+ aria-label="Copy report id ${escapeHtml(ctx.lastReportId)}"
2581
+ >${escapeHtml(idShort)}<span class="mushi-success-receipt-copy" aria-hidden="true">\u2398</span></button>
2582
+ </div>
2583
+ ${trackHref ? `
2584
+ <a
2585
+ class="mushi-success-receipt-track"
2586
+ href="${escapeHtml(trackHref)}"
2587
+ target="_blank"
2588
+ rel="noopener noreferrer"
2589
+ >Track on Mushi <span aria-hidden="true">\u2197</span></a>
2590
+ ` : ""}
2591
+ ${renderSlaLine(ctx)}
2592
+ </div>
2307
2593
  `;
2308
- hint.textContent = this.locale.step3.elementSelectorHint;
2309
- document.body.appendChild(hint);
2310
- this.selectorHint = hint;
2594
+ }
2595
+ function renderSlaLine(ctx) {
2596
+ const sla = (ctx.config.responseSlaLabel ?? "").trim();
2597
+ if (sla) {
2598
+ return `<div class="mushi-success-sla">${escapeHtml(sla)}</div>`;
2311
2599
  }
2312
- removeSelectorHint() {
2313
- this.selectorHint?.remove();
2314
- this.selectorHint = null;
2315
- document.getElementById("mushi-selector-hint")?.remove();
2600
+ return `<div class="mushi-success-sla mushi-success-sla-default">A human will look at this within a working day.</div>`;
2601
+ }
2602
+ function renderBetaSuccessFooter(ctx) {
2603
+ const beta = ctx.config.betaMode;
2604
+ const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
2605
+ const appName = escapeHtml(beta.appName ?? "the team");
2606
+ return `
2607
+ <div class="mushi-beta-success-footer" role="note" aria-label="Beta feedback acknowledgement">
2608
+ ${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>`}
2609
+ <div class="mushi-beta-success-line mushi-beta-success-dim">We aim to review within 48h \xB7 thank you for helping build this</div>
2610
+ </div>
2611
+ `;
2612
+ }
2613
+ function renderRewardsNudge(ctx) {
2614
+ const { tier, nextTier, totalPoints, pointsForReport } = ctx.rewardsState;
2615
+ const tierName = tier?.displayName ?? "Free";
2616
+ const tierSlug = tier?.slug ?? "free";
2617
+ const color = ctx.tierColor(tierSlug);
2618
+ let pct = 100;
2619
+ let nextLabel = "";
2620
+ if (nextTier) {
2621
+ const base = tier?.pointsThreshold ?? 0;
2622
+ const ceiling = nextTier.pointsThreshold;
2623
+ pct = ceiling > base ? Math.round(Math.min(1, (totalPoints - base) / (ceiling - base)) * 100) : 100;
2624
+ const remaining = Math.max(0, ceiling - totalPoints);
2625
+ nextLabel = `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}`;
2316
2626
  }
2317
- showNudge() {
2318
- if (this.nudgeShown || this.nudgeEl) return;
2319
- this.nudgeShown = true;
2320
- const trigger = this.shadow.querySelector(".mushi-trigger");
2321
- const rect = trigger?.getBoundingClientRect();
2322
- const nudge = document.createElement("div");
2323
- nudge.id = "mushi-nudge-bubble";
2324
- nudge.setAttribute("role", "tooltip");
2325
- const isRight = this.config.position.includes("right");
2326
- nudge.style.cssText = `
2327
- position: fixed;
2328
- z-index: 2147483645;
2329
- ${rect ? `bottom: ${window.innerHeight - rect.top + 8}px; ${isRight ? `right: ${window.innerWidth - rect.right}px;` : `left: ${rect.left}px;`}` : "bottom: 80px; right: 24px;"}
2330
- background: rgba(17,17,17,0.92);
2331
- color: #fff;
2332
- font-family: ui-sans-serif, system-ui, sans-serif;
2333
- font-size: 12px;
2334
- line-height: 1.4;
2335
- padding: 8px 12px;
2336
- border-radius: 8px;
2337
- max-width: 200px;
2338
- pointer-events: none;
2339
- backdrop-filter: blur(4px);
2340
- box-shadow: 0 2px 12px rgba(0,0,0,0.35);
2341
- animation: mushi-fade-in 0.15s ease forwards;
2627
+ return `
2628
+ <div class="mushi-rewards-nudge" aria-label="Rewards progress">
2629
+ <div class="mushi-rewards-row">
2630
+ <span class="mushi-tier-pip" style="background:${color}" aria-hidden="true"></span>
2631
+ <span class="mushi-rewards-tier-name">${escapeHtml(tierName)}</span>
2632
+ <span class="mushi-rewards-pts-count">${totalPoints.toLocaleString()} pts</span>
2633
+ <span class="mushi-rewards-pts-earn">+${pointsForReport} pts for a report</span>
2634
+ </div>
2635
+ ${nextTier ? `
2636
+ <div class="mushi-tier-bar-track" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="Progress to ${escapeHtml(nextTier.displayName)}">
2637
+ <div class="mushi-tier-bar-fill" style="width:${pct}%"></div>
2638
+ </div>
2639
+ <div class="mushi-rewards-next-label">${nextLabel}</div>
2640
+ ` : ""}
2641
+ </div>
2342
2642
  `;
2343
- 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}";
2344
- document.body.appendChild(nudge);
2345
- this.nudgeEl = nudge;
2346
- if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
2347
- this.nudgeTimer = setTimeout(() => this.removeNudge(), 5e3);
2643
+ }
2644
+ function renderSuccessRewards(ctx) {
2645
+ const { tier, nextTier, totalPoints, pointsForReport } = ctx.rewardsState;
2646
+ const projected = totalPoints + pointsForReport;
2647
+ let pctAfter = 100;
2648
+ let nextLabel = "";
2649
+ if (nextTier) {
2650
+ const base = tier?.pointsThreshold ?? 0;
2651
+ const ceiling = nextTier.pointsThreshold;
2652
+ pctAfter = ceiling > base ? Math.round(Math.min(1, (projected - base) / (ceiling - base)) * 100) : 100;
2653
+ const remaining = Math.max(0, ceiling - projected);
2654
+ nextLabel = remaining > 0 ? `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}` : `\u{1F389} ${escapeHtml(nextTier.displayName)} reached!`;
2348
2655
  }
2349
- removeNudge() {
2350
- if (this.nudgeTimer !== null) {
2351
- clearTimeout(this.nudgeTimer);
2352
- this.nudgeTimer = null;
2353
- }
2354
- this.nudgeEl?.remove();
2355
- this.nudgeEl = null;
2356
- document.getElementById("mushi-nudge-bubble")?.remove();
2656
+ return `
2657
+ <div class="mushi-success-rewards">
2658
+ <div class="mushi-success-pts-award">+${pointsForReport} pts</div>
2659
+ ${nextTier ? `
2660
+ <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)}">
2661
+ <div class="mushi-tier-bar-fill" style="width:${pctAfter}%"></div>
2662
+ </div>
2663
+ <div class="mushi-rewards-next-label">${nextLabel}</div>
2664
+ ` : ""}
2665
+ </div>
2666
+ `;
2667
+ }
2668
+
2669
+ // src/widget.ts
2670
+ var MushiWidget = class _MushiWidget {
2671
+ // double-submit guard
2672
+ constructor(config = {}, callbacks, sdkVersion = MUSHI_SDK_VERSION) {
2673
+ this.sdkVersion = sdkVersion;
2674
+ this.config = {
2675
+ position: config.position ?? "bottom-right",
2676
+ anchor: config.anchor ?? {},
2677
+ theme: config.theme ?? "auto",
2678
+ // Falsy-OR (NOT `??`) on purpose: `triggerText: ''` is semantically
2679
+ // nonsense — it would render a labelless, glyphless trigger button
2680
+ // that users can't see or aim at. Treat empty string the same as
2681
+ // omitted so any caller that wires this to a cleared form input or
2682
+ // pastes a legacy snippet that emitted `triggerText: ""` (see
2683
+ // apps/admin/src/lib/sdkSnippets.ts widgetLines history) still gets
2684
+ // the default 🐛 and a visible button.
2685
+ triggerText: config.triggerText || "\u{1F41B}",
2686
+ expandedTitle: config.expandedTitle ?? "",
2687
+ mode: config.mode ?? "conversational",
2688
+ locale: config.locale ?? "auto",
2689
+ zIndex: config.zIndex ?? 99999,
2690
+ trigger: config.trigger ?? "auto",
2691
+ bannerConfig: config.bannerConfig ?? {},
2692
+ attachToSelector: config.attachToSelector ?? "",
2693
+ inset: config.inset ?? {},
2694
+ respectSafeArea: config.respectSafeArea ?? true,
2695
+ hideOnSelector: config.hideOnSelector ?? "",
2696
+ hideOnRoutes: config.hideOnRoutes ?? [],
2697
+ environments: config.environments ?? {},
2698
+ smartHide: config.smartHide ?? false,
2699
+ draggable: config.draggable ?? false,
2700
+ brandFooter: config.brandFooter ?? true,
2701
+ outdatedBanner: config.outdatedBanner ?? "auto",
2702
+ betaMode: config.betaMode ?? {},
2703
+ minDescriptionLength: config.minDescriptionLength ?? 20,
2704
+ dashboardUrl: config.dashboardUrl ?? "",
2705
+ responseSlaLabel: config.responseSlaLabel ?? "",
2706
+ featureRequestCard: config.featureRequestCard ?? true,
2707
+ featureRequestLabel: config.featureRequestLabel || "Feature request",
2708
+ featureRequestDescription: config.featureRequestDescription || "Suggest something new \u2014 even rough ideas help us prioritise",
2709
+ avoidSelectors: config.avoidSelectors ?? [],
2710
+ categories: config.categories ?? [],
2711
+ accent: config.accent ?? "",
2712
+ accentText: config.accentText ?? ""
2713
+ };
2714
+ this.callbacks = callbacks;
2715
+ this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
2716
+ this.host = document.createElement("div");
2717
+ this.host.id = "mushi-mushi-widget";
2718
+ this.shadow = this.host.attachShadow({ mode: "closed" });
2357
2719
  }
2358
- setSdkFreshness(info) {
2359
- this.sdkFreshness = info;
2360
- if (this.isOpen) this.render();
2720
+ sdkVersion;
2721
+ host;
2722
+ shadow;
2723
+ config;
2724
+ callbacks;
2725
+ locale;
2726
+ isOpen = false;
2727
+ step = "category";
2728
+ /**
2729
+ * The selected category id. May be a built-in `MushiReportCategory` or a
2730
+ * custom id from `config.categories`. Cast to `MushiReportCategory` only
2731
+ * after resolving through `resolveBaseCategory()`.
2732
+ */
2733
+ selectedCategory = null;
2734
+ selectedIntent = null;
2735
+ /**
2736
+ * True when the user took the "Feature request" shortcut. We track this
2737
+ * separately from `selectedCategory='other'` so the Back button on the
2738
+ * details step jumps straight back to the category picker instead of
2739
+ * landing on the intent picker the user explicitly skipped.
2740
+ */
2741
+ viaFeatureRequest = false;
2742
+ screenshotAttached = false;
2743
+ screenshotCapturing = false;
2744
+ screenshotError = false;
2745
+ allowScreenshotRemove = true;
2746
+ elementSelected = false;
2747
+ elementCapturing = false;
2748
+ submitting = false;
2749
+ /** Hint element injected outside the shadow DOM during element selection. */
2750
+ selectorHint = null;
2751
+ triggerVisible = true;
2752
+ triggerShrunk = false;
2753
+ triggerHiddenByScroll = false;
2754
+ /** Milliseconds since mount — used for the 30s first-time nudge gate. */
2755
+ mountedAt = null;
2756
+ nudgeShown = false;
2757
+ nudgeEl = null;
2758
+ nudgeTimer = null;
2759
+ sdkFreshness = null;
2760
+ reporterReports = [];
2761
+ featureBoard = [];
2762
+ reporterComments = [];
2763
+ selectedReportId = null;
2764
+ reporterLoading = false;
2765
+ reporterError = null;
2766
+ attachedLaunchers = [];
2767
+ smartHideCleanup = null;
2768
+ smartHideTimer = null;
2769
+ /** Captured at the moment of submit so the success ledger metadata
2770
+ * ("REPORT · 14:23:07 JST") doesn't drift while the success step
2771
+ * is on screen. */
2772
+ submittedAt = null;
2773
+ /** Pending success-state + auto-close timers. Tracked so destroy()
2774
+ * can clear them — otherwise a host that unmounts mid-submit leaks
2775
+ * this MushiWidget reference (and re-renders into a detached shadow
2776
+ * root) for up to ~3.3s after destroy. */
2777
+ successTimer = null;
2778
+ autoCloseTimer = null;
2779
+ rewardsState = null;
2780
+ leaderboardEntries = null;
2781
+ leaderboardLoading = false;
2782
+ /** Server-confirmed id for the just-submitted report. Surfaces in
2783
+ * the success step as a copyable receipt + optional deep link to
2784
+ * the Mushi console (when `dashboardUrl` is configured). Cleared
2785
+ * on every new `open()` so a re-opened widget never reuses a
2786
+ * stale id from the previous session. */
2787
+ lastReportId = null;
2788
+ /** True when the just-submitted report was queued offline (no
2789
+ * network, or the API errored and went into the retry queue).
2790
+ * Drives a different success copy so the user knows the report
2791
+ * hasn't actually reached the console yet. */
2792
+ lastSubmitQueuedOffline = false;
2793
+ /** Whether the user has clicked ✕ on the header banner this session. */
2794
+ bannerDismissed = false;
2795
+ /** Persisted FAB position when draggable is enabled. */
2796
+ fabPos = null;
2797
+ /** Cleanup fn for visualViewport keyboard listener. */
2798
+ vvCleanup = null;
2799
+ /** Mushi tester session JWT — set after in-widget sign-in or by mushi.ts. */
2800
+ testerJwt = null;
2801
+ /** Tester identity (public_handle, display_name). */
2802
+ testerInfo = null;
2803
+ /** Cross-app reports for the signed-in tester. */
2804
+ crossAppReports = null;
2805
+ crossAppLoading = false;
2806
+ /** Global leaderboard entries (from mushi_testers, not org-scoped). */
2807
+ globalLeaderboard = null;
2808
+ globalLeaderboardLoading = false;
2809
+ /** Reputation for the signed-in tester. */
2810
+ testerReputation = null;
2811
+ /** Whether an in-widget magic-link email was just sent. */
2812
+ magicLinkSent = false;
2813
+ magicLinkEmail = "";
2814
+ magicLinkError = "";
2815
+ magicLinkSending = false;
2816
+ mount() {
2817
+ if (this.host.isConnected) return;
2818
+ this.syncHostChromeState();
2819
+ document.body.appendChild(this.host);
2820
+ this.syncAttachedLaunchers();
2821
+ this.syncSmartHide();
2822
+ this.render();
2823
+ this.mountedAt = Date.now();
2361
2824
  }
2362
- setRewardsState(state) {
2363
- this.rewardsState = state;
2364
- if (this.isOpen) this.render();
2825
+ getIsMounted() {
2826
+ return this.host.isConnected;
2365
2827
  }
2366
- setLeaderboard(entries, loading = false) {
2367
- this.leaderboardEntries = entries;
2368
- this.leaderboardLoading = loading;
2369
- if (this.isOpen && this.step === "leaderboard") this.render();
2828
+ updateConfig(config = {}) {
2829
+ this.config = {
2830
+ ...this.config,
2831
+ ...config.position ? { position: config.position } : {},
2832
+ ...config.anchor !== void 0 ? { anchor: config.anchor } : {},
2833
+ ...config.theme ? { theme: config.theme } : {},
2834
+ ...config.triggerText !== void 0 ? { triggerText: config.triggerText || "\u{1F41B}" } : {},
2835
+ ...config.expandedTitle !== void 0 ? { expandedTitle: config.expandedTitle } : {},
2836
+ ...config.mode ? { mode: config.mode } : {},
2837
+ ...config.locale ? { locale: config.locale } : {},
2838
+ ...config.zIndex !== void 0 ? { zIndex: config.zIndex } : {},
2839
+ ...config.trigger ? { trigger: config.trigger } : {},
2840
+ ...config.attachToSelector !== void 0 ? { attachToSelector: config.attachToSelector } : {},
2841
+ ...config.inset !== void 0 ? { inset: config.inset } : {},
2842
+ ...config.respectSafeArea !== void 0 ? { respectSafeArea: config.respectSafeArea } : {},
2843
+ ...config.hideOnSelector !== void 0 ? { hideOnSelector: config.hideOnSelector } : {},
2844
+ ...config.hideOnRoutes !== void 0 ? { hideOnRoutes: config.hideOnRoutes } : {},
2845
+ ...config.environments !== void 0 ? { environments: config.environments } : {},
2846
+ ...config.smartHide !== void 0 ? { smartHide: config.smartHide } : {},
2847
+ ...config.draggable !== void 0 ? { draggable: config.draggable } : {},
2848
+ ...config.brandFooter !== void 0 ? { brandFooter: config.brandFooter } : {},
2849
+ ...config.outdatedBanner !== void 0 ? { outdatedBanner: config.outdatedBanner } : {},
2850
+ ...config.betaMode !== void 0 ? { betaMode: config.betaMode } : {},
2851
+ ...config.minDescriptionLength !== void 0 ? { minDescriptionLength: config.minDescriptionLength } : {},
2852
+ ...config.dashboardUrl !== void 0 ? { dashboardUrl: config.dashboardUrl } : {},
2853
+ ...config.responseSlaLabel !== void 0 ? { responseSlaLabel: config.responseSlaLabel } : {},
2854
+ ...config.featureRequestCard !== void 0 ? { featureRequestCard: config.featureRequestCard } : {},
2855
+ ...config.featureRequestLabel !== void 0 ? { featureRequestLabel: config.featureRequestLabel || "Feature request" } : {},
2856
+ ...config.featureRequestDescription !== void 0 ? { featureRequestDescription: config.featureRequestDescription || "Suggest something new \u2014 even rough ideas help us prioritise" } : {},
2857
+ // Runtime/dashboard config delivers bannerMessage/bannerLabel via
2858
+ // mergeRuntimeConfig → bannerConfig. The widget is constructed before
2859
+ // that fetch resolves, so this pass-through is what makes server-driven
2860
+ // banner copy actually render.
2861
+ ...config.bannerConfig !== void 0 ? { bannerConfig: config.bannerConfig } : {},
2862
+ ...config.categories !== void 0 ? { categories: config.categories } : {}
2863
+ };
2864
+ this.locale = getLocale(this.config.locale === "auto" ? void 0 : this.config.locale);
2865
+ if (this.host.isConnected) this.syncHostChromeState();
2866
+ this.syncAttachedLaunchers();
2867
+ this.syncSmartHide();
2868
+ this.render();
2370
2869
  }
2371
- destroy() {
2372
- if (this.successTimer !== null) {
2373
- clearTimeout(this.successTimer);
2374
- this.successTimer = null;
2375
- }
2376
- if (this.autoCloseTimer !== null) {
2377
- clearTimeout(this.autoCloseTimer);
2378
- this.autoCloseTimer = null;
2379
- }
2380
- if (this.smartHideTimer !== null) {
2381
- clearTimeout(this.smartHideTimer);
2382
- this.smartHideTimer = null;
2383
- }
2384
- this.smartHideCleanup?.();
2385
- this.smartHideCleanup = null;
2386
- this.attachedLaunchers.forEach((cleanup) => cleanup());
2387
- this.attachedLaunchers = [];
2388
- this.removeSelectorHint();
2389
- this.removeNudge();
2390
- this.removeBodyNudge();
2391
- this.host.remove();
2870
+ // ─── Custom category helpers ──────────────────────────────────────────────
2871
+ /** Find a custom category entry by id. Returns undefined for built-in ids. */
2872
+ resolveCustomCategory(id) {
2873
+ return this.config.categories?.find((c) => c.id === id);
2392
2874
  }
2393
- /* ── Host chrome contract ────────────────────────────────────────────────
2394
- The host element must never create an invisible full-screen touch blocker.
2395
- We own these inline styles — consumer CSS can only win with `!important`,
2396
- which is explicitly banned by the SDK contract. Calling this at mount()
2397
- and after every zIndex update is the only safe invariant. */
2398
2875
  /**
2399
- * Apply the SDK-owned pass-through layout to the host element so it is
2400
- * always zero-sized and click/touch-transparent. Only the shadow-root
2401
- * internals (`.mushi-trigger`, `.mushi-banner`, `.mushi-panel`) opt back
2402
- * into pointer events. This is idempotent and safe to call repeatedly.
2876
+ * Map a (possibly custom) category id to the built-in `MushiReportCategory`
2877
+ * used for the report wire format. Falls back to `'other'`.
2403
2878
  */
2404
- syncHostChromeState() {
2405
- const s = this.host.style;
2406
- s.setProperty("position", "fixed");
2407
- s.setProperty("top", "0");
2408
- s.setProperty("left", "0");
2409
- s.setProperty("width", "0");
2410
- s.setProperty("height", "0");
2411
- s.setProperty("overflow", "visible");
2412
- s.setProperty("pointer-events", "none");
2413
- s.setProperty("z-index", String(this.config.zIndex));
2414
- s.setProperty("margin", "0");
2415
- s.setProperty("padding", "0");
2416
- s.setProperty("border", "none");
2417
- s.setProperty("background", "none");
2879
+ resolveBaseCategory(id) {
2880
+ const BUILTIN = ["bug", "slow", "visual", "confusing", "other"];
2881
+ if (BUILTIN.includes(id)) return id;
2882
+ const custom = this.resolveCustomCategory(id);
2883
+ return custom?.baseCategory ?? "other";
2418
2884
  }
2419
- /**
2420
- * Returns true when a DOM element matching `hideOnSelector` is currently
2421
- * present in the host document. Used by both the trigger and the banner
2422
- * so a single selector consistently hides ALL SDK-injected launcher
2423
- * surfaces. Invalid selectors are swallowed silently (non-fatal).
2424
- */
2425
- isSuppressedByHost() {
2426
- if (!this.config.hideOnSelector || typeof document === "undefined") return false;
2427
- try {
2428
- return Boolean(document.querySelector(this.config.hideOnSelector));
2429
- } catch {
2430
- return false;
2885
+ /** Icon for the selected category — custom entry's icon or built-in emoji. */
2886
+ categoryIcon(id) {
2887
+ const custom = this.resolveCustomCategory(id);
2888
+ if (custom?.icon) return custom.icon;
2889
+ return CATEGORY_ICONS[id] ?? "\u{1F4AC}";
2890
+ }
2891
+ /** Label for the selected category — custom entry label or built-in i18n string. */
2892
+ categoryLabel(id) {
2893
+ const custom = this.resolveCustomCategory(id);
2894
+ if (custom) return custom.label;
2895
+ const t = this.locale;
2896
+ return t.step1.categories[id] ?? id;
2897
+ }
2898
+ // ─── Open / close ─────────────────────────────────────────────────────────
2899
+ open(options) {
2900
+ if (this.isOpen) return;
2901
+ this.isOpen = true;
2902
+ this.screenshotAttached = false;
2903
+ this.screenshotCapturing = false;
2904
+ this.screenshotError = false;
2905
+ this.elementSelected = false;
2906
+ this.elementCapturing = false;
2907
+ this.submitting = false;
2908
+ this.submittedAt = null;
2909
+ this.removeSelectorHint();
2910
+ this.lastReportId = null;
2911
+ this.lastSubmitQueuedOffline = false;
2912
+ this.viaFeatureRequest = false;
2913
+ if (options?.featureRequest) {
2914
+ this.selectedCategory = "other";
2915
+ this.selectedIntent = FEATURE_REQUEST_INTENT;
2916
+ this.viaFeatureRequest = true;
2917
+ this.step = "details";
2918
+ } else if (options?.category) {
2919
+ this.selectedCategory = options.category;
2920
+ this.selectedIntent = null;
2921
+ const custom = this.resolveCustomCategory(options.category);
2922
+ this.step = custom && (!custom.intents || custom.intents.length === 0) ? "details" : "intent";
2923
+ } else {
2924
+ this.selectedCategory = null;
2925
+ this.selectedIntent = null;
2926
+ this.step = "category";
2431
2927
  }
2928
+ this.render();
2929
+ this.callbacks.onOpen();
2930
+ }
2931
+ close() {
2932
+ if (!this.isOpen) return;
2933
+ this.isOpen = false;
2934
+ this.render();
2935
+ this.callbacks.onClose();
2432
2936
  }
2433
2937
  /**
2434
- * Returns a snapshot of the widget's host-layer health for use in
2435
- * `Mushi.diagnose()`. Callers check this to know whether the widget
2436
- * could ever block host-app UI without opening a browser devtools.
2938
+ * Briefly highlight the trigger button (a soft pulse + tooltip) without
2939
+ * opening the full reporter panel. Use for first-session welcome nudges
2940
+ * and other "by the way, this exists" prompts where forcing the panel
2941
+ * open would feel aggressive. Honours `position: 'none'` (no-op when
2942
+ * the trigger button is hidden).
2437
2943
  */
2438
- getWidgetDiagnostics() {
2439
- const s = this.host.style;
2440
- const widgetHostPointerSafe = s.pointerEvents === "none" && (s.width === "0" || s.width === "0px") && (s.height === "0" || s.height === "0px");
2441
- const widgetHostBounds = this.host.isConnected ? { width: this.host.offsetWidth, height: this.host.offsetHeight } : null;
2442
- const widgetSuppressed = this.isSuppressedByHost() || this.isRouteHidden() || !this.triggerVisible;
2443
- const bannerRendered = this.config.trigger === "banner" && !this.bannerDismissed && !this.isSuppressedByHost() && !this.isRouteHidden() && this.triggerVisible;
2444
- return { widgetHostPointerSafe, widgetHostBounds, widgetSuppressed, bannerRendered };
2445
- }
2446
- syncAttachedLaunchers() {
2447
- this.attachedLaunchers.forEach((cleanup) => cleanup());
2448
- this.attachedLaunchers = [];
2449
- if (this.config.trigger !== "attach" || !this.config.attachToSelector) return;
2450
- if (typeof document === "undefined") return;
2451
- this.attachedLaunchers.push(this.attachTo(this.config.attachToSelector));
2944
+ pulseTrigger() {
2945
+ if (this.isOpen) return;
2946
+ const trigger = this.shadow.querySelector(".mushi-trigger");
2947
+ if (!trigger) return;
2948
+ trigger.classList.add("mushi-trigger-pulse");
2949
+ window.setTimeout(() => {
2950
+ trigger.classList.remove("mushi-trigger-pulse");
2951
+ }, 2400);
2452
2952
  }
2453
- syncSmartHide() {
2454
- this.smartHideCleanup?.();
2455
- this.smartHideCleanup = null;
2456
- this.triggerShrunk = false;
2457
- this.triggerHiddenByScroll = false;
2458
- if (!this.config.smartHide || typeof window === "undefined") return;
2459
- const smart = this.config.smartHide === true ? { onScroll: "shrink", onIdleMs: 900 } : this.config.smartHide;
2460
- if (!smart.onScroll) return;
2461
- const onScroll = () => {
2462
- if (smart.onScroll === "hide") {
2463
- this.triggerHiddenByScroll = true;
2464
- } else {
2465
- this.triggerShrunk = true;
2466
- }
2467
- this.render();
2468
- if (this.smartHideTimer !== null) clearTimeout(this.smartHideTimer);
2469
- this.smartHideTimer = setTimeout(() => {
2470
- this.triggerHiddenByScroll = false;
2471
- this.triggerShrunk = false;
2472
- this.render();
2473
- }, smart.onIdleMs ?? 900);
2474
- };
2475
- window.addEventListener("scroll", onScroll, { passive: true });
2476
- this.smartHideCleanup = () => window.removeEventListener("scroll", onScroll);
2953
+ getIsOpen() {
2954
+ return this.isOpen;
2477
2955
  }
2478
- shouldRenderTrigger() {
2479
- if (!this.triggerVisible) return false;
2480
- if (this.triggerHiddenByScroll) return false;
2481
- if (this.config.trigger === "manual" || this.config.trigger === "hidden" || this.config.trigger === "attach" || this.config.trigger === "banner") {
2482
- return false;
2483
- }
2484
- if (this.isMobileSmartHidden()) return false;
2485
- if (this.isRouteHidden()) return false;
2486
- if (this.isSuppressedByHost()) return false;
2487
- const action = this.config.environments[this.detectEnvironment()];
2488
- return action !== "never" && action !== "manual";
2956
+ showTrigger() {
2957
+ this.triggerVisible = true;
2958
+ this.render();
2489
2959
  }
2490
- /** Height of the banner in px — kept in sync with the CSS `.mushi-banner` height (36px). */
2491
- static BANNER_HEIGHT = 36;
2492
- /** CSS property applied to document.body so host-app content doesn't slide under the banner. */
2493
- static BODY_NUDGE_PROP = "--mushi-banner-offset";
2494
- applyBodyNudge(position) {
2495
- const h = `${_MushiWidget.BANNER_HEIGHT}px`;
2496
- if (position === "top") {
2497
- document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
2498
- if (!document.body.style.paddingTop) {
2499
- document.body.style.paddingTop = h;
2500
- document.body.dataset.mushiBannerNudged = "top";
2501
- }
2502
- } else {
2503
- document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
2504
- if (!document.body.style.paddingBottom) {
2505
- document.body.style.paddingBottom = h;
2506
- document.body.dataset.mushiBannerNudged = "bottom";
2507
- }
2508
- }
2960
+ hideTrigger() {
2961
+ this.triggerVisible = false;
2962
+ this.render();
2509
2963
  }
2510
- removeBodyNudge() {
2511
- document.documentElement.style.removeProperty(_MushiWidget.BODY_NUDGE_PROP);
2512
- const nudged = document.body.dataset.mushiBannerNudged;
2513
- if (nudged === "top") {
2514
- document.body.style.paddingTop = "";
2515
- delete document.body.dataset.mushiBannerNudged;
2516
- } else if (nudged === "bottom") {
2517
- document.body.style.paddingBottom = "";
2518
- delete document.body.dataset.mushiBannerNudged;
2519
- }
2964
+ setTrigger(trigger) {
2965
+ this.updateConfig({ trigger });
2520
2966
  }
2521
- renderBanner() {
2522
- if (this.config.trigger !== "banner") return;
2523
- if (this.bannerDismissed) {
2524
- this.removeBodyNudge();
2525
- return;
2526
- }
2527
- if (!this.triggerVisible) {
2528
- this.removeBodyNudge();
2529
- return;
2530
- }
2531
- if (this.isRouteHidden()) {
2532
- this.removeBodyNudge();
2533
- return;
2534
- }
2535
- if (this.isSuppressedByHost()) {
2536
- this.removeBodyNudge();
2537
- return;
2538
- }
2539
- const bc = this.config.bannerConfig ?? {};
2540
- const variant = bc.variant ?? "brand";
2541
- const position = bc.position ?? "top";
2542
- const message = bc.message?.trim() ?? "";
2543
- const richLayout = message.length > 0;
2544
- const bugLabel = bc.bugCta ?? "\u{1F41B} Report a bug";
2545
- const showFeat = bc.featureCta !== false;
2546
- const featLabel = bc.featureCtaLabel ?? "\u2728 Request feature";
2547
- const zIdx = bc.zIndex ?? (this.config.zIndex ?? 99999) - 1;
2548
- const banner = document.createElement("div");
2549
- banner.className = `mushi-banner ${variant} ${position}${richLayout ? " mushi-banner--rich" : ""}`;
2550
- banner.style.setProperty("--mushi-banner-z", String(zIdx));
2551
- banner.setAttribute("role", "banner");
2552
- const dismissBtn = document.createElement("button");
2553
- dismissBtn.className = "mushi-banner-dismiss";
2554
- dismissBtn.textContent = "\u2715";
2555
- dismissBtn.setAttribute("aria-label", "Dismiss feedback banner");
2556
- dismissBtn.addEventListener("click", () => {
2557
- this.bannerDismissed = true;
2558
- this.removeBodyNudge();
2559
- this.render();
2560
- });
2561
- if (richLayout) {
2562
- const body = document.createElement("div");
2563
- body.className = "mushi-banner-body";
2564
- const labelText = bc.label === false ? null : bc.label ?? "Beta";
2565
- if (labelText) {
2566
- const pill = document.createElement("span");
2567
- pill.className = "mushi-banner-pill";
2568
- pill.textContent = labelText;
2569
- body.appendChild(pill);
2570
- }
2571
- const msg = document.createElement("span");
2572
- msg.className = "mushi-banner-message";
2573
- msg.textContent = message;
2574
- body.appendChild(msg);
2575
- banner.appendChild(body);
2576
- const nav = document.createElement("nav");
2577
- nav.className = "mushi-banner-actions";
2578
- nav.setAttribute("aria-label", "Feedback banner actions");
2579
- const appendDivider = (extra = false) => {
2580
- const sep = document.createElement("span");
2581
- sep.className = `mushi-banner-divider${extra ? " mushi-banner-extra" : ""}`;
2582
- sep.setAttribute("aria-hidden", "true");
2583
- sep.textContent = "|";
2584
- nav.appendChild(sep);
2585
- };
2586
- const appendAction = (label, onClick, extra = false) => {
2587
- const btn = document.createElement("button");
2588
- btn.type = "button";
2589
- btn.className = `mushi-banner-link${extra ? " mushi-banner-extra" : ""}`;
2590
- btn.textContent = label;
2591
- btn.addEventListener("click", onClick);
2592
- nav.appendChild(btn);
2967
+ attachTo(selectorOrElement, options = {}) {
2968
+ const elements = typeof selectorOrElement === "string" ? Array.from(document.querySelectorAll(selectorOrElement)) : [selectorOrElement];
2969
+ const cleanups = elements.map((el) => {
2970
+ const onClick = (event) => {
2971
+ event.preventDefault();
2972
+ this.updateConfig(options);
2973
+ this.open();
2593
2974
  };
2594
- appendAction(bugLabel, () => this.open());
2595
- if (showFeat) {
2596
- appendDivider(true);
2597
- appendAction(featLabel, () => this.open({ featureRequest: true }), true);
2598
- }
2599
- for (const link of bc.links ?? []) {
2600
- const linkLabel = link.label?.trim();
2601
- if (!linkLabel) continue;
2602
- const href = link.href && (/^https?:\/\//i.test(link.href) || link.href.startsWith("/")) ? link.href : void 0;
2603
- appendDivider(true);
2604
- if (href) {
2605
- const anchor = document.createElement("a");
2606
- anchor.className = "mushi-banner-link mushi-banner-extra";
2607
- anchor.href = href;
2608
- anchor.textContent = linkLabel;
2609
- anchor.target = "_blank";
2610
- anchor.rel = "noopener noreferrer";
2611
- nav.appendChild(anchor);
2612
- } else {
2613
- appendAction(linkLabel, () => {
2614
- if (link.featureRequest) this.open({ featureRequest: true });
2615
- else this.open();
2616
- }, true);
2617
- }
2618
- }
2619
- banner.appendChild(nav);
2620
- banner.appendChild(dismissBtn);
2975
+ el.addEventListener("click", onClick);
2976
+ return () => el.removeEventListener("click", onClick);
2977
+ });
2978
+ return () => cleanups.forEach((cleanup) => cleanup());
2979
+ }
2980
+ setScreenshotAttached(attached) {
2981
+ this.screenshotAttached = attached;
2982
+ if (this.isOpen) this.render();
2983
+ }
2984
+ setAllowScreenshotRemove(allow) {
2985
+ this.allowScreenshotRemove = allow;
2986
+ if (this.isOpen) this.render();
2987
+ }
2988
+ setElementSelected(selected) {
2989
+ this.elementSelected = selected;
2990
+ this.elementCapturing = false;
2991
+ this.removeSelectorHint();
2992
+ if (this.isOpen) this.render();
2993
+ }
2994
+ setScreenshotCapturing(capturing) {
2995
+ this.screenshotCapturing = capturing;
2996
+ this.screenshotError = false;
2997
+ if (this.isOpen) this.render();
2998
+ }
2999
+ setScreenshotError(failed) {
3000
+ this.screenshotError = failed;
3001
+ this.screenshotCapturing = false;
3002
+ if (this.isOpen) this.render();
3003
+ }
3004
+ setElementCapturing(capturing) {
3005
+ this.elementCapturing = capturing;
3006
+ if (capturing) {
3007
+ this.showSelectorHint();
2621
3008
  } else {
2622
- const bugBtn = document.createElement("button");
2623
- bugBtn.className = "mushi-banner-btn";
2624
- bugBtn.textContent = bugLabel;
2625
- bugBtn.addEventListener("click", () => this.open());
2626
- banner.appendChild(bugBtn);
2627
- if (showFeat) {
2628
- const featBtn = document.createElement("button");
2629
- featBtn.className = "mushi-banner-btn";
2630
- featBtn.textContent = featLabel;
2631
- featBtn.addEventListener("click", () => this.open({ featureRequest: true }));
2632
- banner.appendChild(featBtn);
2633
- }
2634
- banner.appendChild(dismissBtn);
3009
+ this.removeSelectorHint();
2635
3010
  }
2636
- this.shadow.appendChild(banner);
2637
- this.applyBodyNudge(position);
3011
+ if (this.isOpen) this.render();
2638
3012
  }
2639
- effectiveTrigger() {
2640
- if (!this.config.smartHide || typeof window === "undefined") return this.config.trigger;
2641
- const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
2642
- if (window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "edge-tab") {
2643
- return "edge-tab";
2644
- }
2645
- return this.config.trigger;
3013
+ /** Hide the widget panel (but keep the host element) during element selection
3014
+ * so the user can click any element on the page without the panel
3015
+ * intercepting the event. */
3016
+ hidePanel() {
3017
+ const panel = this.shadow.querySelector(".mushi-panel");
3018
+ if (panel) panel.style.display = "none";
2646
3019
  }
2647
- isMobileSmartHidden() {
2648
- if (!this.config.smartHide || typeof window === "undefined") return false;
2649
- const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
2650
- return window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "hide";
3020
+ showPanel() {
3021
+ const panel = this.shadow.querySelector(".mushi-panel");
3022
+ if (panel) panel.style.display = "";
2651
3023
  }
2652
- detectEnvironment() {
2653
- const host = typeof location !== "undefined" ? location.hostname : "";
2654
- if (host === "localhost" || host === "127.0.0.1" || host.endsWith(".local")) return "development";
2655
- if (/\b(staging|stage|preview|dev)\b/i.test(host)) return "staging";
2656
- return "production";
3024
+ showSelectorHint() {
3025
+ this.removeSelectorHint();
3026
+ const hint = document.createElement("div");
3027
+ hint.id = "mushi-selector-hint";
3028
+ hint.setAttribute("role", "status");
3029
+ hint.setAttribute("aria-live", "polite");
3030
+ hint.style.cssText = `
3031
+ position: fixed;
3032
+ bottom: 24px;
3033
+ left: 50%;
3034
+ transform: translateX(-50%);
3035
+ z-index: 2147483646;
3036
+ background: rgba(17,17,17,0.92);
3037
+ color: #fff;
3038
+ font-family: ui-monospace, SFMono-Regular, monospace;
3039
+ font-size: 12px;
3040
+ letter-spacing: 0.04em;
3041
+ padding: 8px 16px;
3042
+ border-radius: 20px;
3043
+ pointer-events: none;
3044
+ white-space: nowrap;
3045
+ backdrop-filter: blur(4px);
3046
+ box-shadow: 0 2px 12px rgba(0,0,0,0.35);
3047
+ `;
3048
+ hint.textContent = this.locale.step3.elementSelectorHint;
3049
+ document.body.appendChild(hint);
3050
+ this.selectorHint = hint;
2657
3051
  }
2658
- isRouteHidden() {
2659
- if (!this.config.hideOnRoutes.length || typeof location === "undefined") return false;
2660
- return this.config.hideOnRoutes.some((route) => location.pathname.includes(route));
3052
+ removeSelectorHint() {
3053
+ this.selectorHint?.remove();
3054
+ this.selectorHint = null;
3055
+ document.getElementById("mushi-selector-hint")?.remove();
2661
3056
  }
2662
- getTheme() {
2663
- if (this.config.theme !== "auto") return this.config.theme;
2664
- if (typeof window !== "undefined" && window.matchMedia("(prefers-color-scheme: dark)").matches) {
2665
- return "dark";
2666
- }
2667
- return "light";
3057
+ showNudge() {
3058
+ if (this.nudgeShown || this.nudgeEl) return;
3059
+ this.nudgeShown = true;
3060
+ const trigger = this.shadow.querySelector(".mushi-trigger");
3061
+ const rect = trigger?.getBoundingClientRect();
3062
+ const nudge = document.createElement("div");
3063
+ nudge.id = "mushi-nudge-bubble";
3064
+ nudge.setAttribute("role", "tooltip");
3065
+ const isRight = this.config.position.includes("right");
3066
+ nudge.style.cssText = `
3067
+ position: fixed;
3068
+ z-index: 2147483645;
3069
+ ${rect ? `bottom: ${window.innerHeight - rect.top + 8}px; ${isRight ? `right: ${window.innerWidth - rect.right}px;` : `left: ${rect.left}px;`}` : "bottom: 80px; right: 24px;"}
3070
+ background: rgba(17,17,17,0.92);
3071
+ color: #fff;
3072
+ font-family: ui-sans-serif, system-ui, sans-serif;
3073
+ font-size: 12px;
3074
+ line-height: 1.4;
3075
+ padding: 8px 12px;
3076
+ border-radius: 8px;
3077
+ max-width: 200px;
3078
+ pointer-events: none;
3079
+ backdrop-filter: blur(4px);
3080
+ box-shadow: 0 2px 12px rgba(0,0,0,0.35);
3081
+ animation: mushi-fade-in 0.15s ease forwards;
3082
+ `;
3083
+ 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}";
3084
+ document.body.appendChild(nudge);
3085
+ this.nudgeEl = nudge;
3086
+ if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
3087
+ this.nudgeTimer = setTimeout(() => this.removeNudge(), 5e3);
2668
3088
  }
2669
- render() {
2670
- const theme = this.getTheme();
2671
- const pos = this.config.position;
2672
- const t = this.locale;
2673
- this.shadow.innerHTML = "";
2674
- const style = document.createElement("style");
2675
- style.textContent = getWidgetStyles(theme);
2676
- this.shadow.appendChild(style);
2677
- this.renderBanner();
2678
- if (this.shouldRenderTrigger()) {
2679
- const effectiveTrigger = this.effectiveTrigger();
2680
- const trigger = document.createElement("button");
2681
- trigger.className = `mushi-trigger ${pos}${effectiveTrigger === "edge-tab" ? " edge-tab" : ""}${this.triggerShrunk ? " shrunk" : ""}`;
2682
- trigger.textContent = this.config.triggerText;
2683
- trigger.setAttribute("aria-label", t.widget.trigger);
2684
- trigger.setAttribute("aria-haspopup", "dialog");
2685
- trigger.setAttribute("aria-expanded", String(this.isOpen));
2686
- trigger.style.zIndex = String(this.config.zIndex);
2687
- this.applyInsetVars(trigger);
2688
- trigger.addEventListener("click", () => {
2689
- this.removeNudge();
2690
- if (this.isOpen) this.close();
2691
- else this.open();
2692
- });
2693
- trigger.addEventListener("mouseenter", () => {
2694
- const onPageMs = this.mountedAt ? Date.now() - this.mountedAt : 0;
2695
- if (!this.nudgeShown && !this.isOpen && onPageMs >= 3e4) {
2696
- this.showNudge();
2697
- }
2698
- });
2699
- trigger.addEventListener("mouseleave", () => {
2700
- if (this.nudgeEl) {
2701
- if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
2702
- this.nudgeTimer = setTimeout(() => this.removeNudge(), 2e3);
2703
- }
2704
- });
2705
- this.shadow.appendChild(trigger);
2706
- }
2707
- const panel = document.createElement("div");
2708
- panel.className = `mushi-panel ${pos}${this.isOpen ? " open" : " closed"}`;
2709
- panel.setAttribute("role", "dialog");
2710
- panel.setAttribute("aria-modal", "true");
2711
- panel.setAttribute("aria-label", t.widget.title);
2712
- panel.style.zIndex = String(this.config.zIndex + 1);
2713
- this.applyInsetVars(panel);
2714
- if (this.isOpen) {
2715
- panel.innerHTML = `${this.renderOutdatedBanner()}${this.renderStep()}${this.renderBrandFooter()}`;
2716
- this.shadow.appendChild(panel);
2717
- this.attachHandlers(panel);
2718
- this.trapFocus(panel);
3089
+ removeNudge() {
3090
+ if (this.nudgeTimer !== null) {
3091
+ clearTimeout(this.nudgeTimer);
3092
+ this.nudgeTimer = null;
2719
3093
  }
3094
+ this.nudgeEl?.remove();
3095
+ this.nudgeEl = null;
3096
+ document.getElementById("mushi-nudge-bubble")?.remove();
2720
3097
  }
2721
- /**
2722
- * Queries each `avoidSelectors` element in the host document and returns
2723
- * the minimum top-offset in px so that a top-anchored element clears all
2724
- * of them by `gap` pixels. Returns `null` when no selectors are provided
2725
- * or no matching elements have a non-zero bounding rect.
2726
- *
2727
- * Runs in the host document (not shadow DOM) so it can reach fixed headers,
2728
- * sticky nav bars, and sign-in CTAs.
2729
- */
2730
- computeAvoidTopPx(gap = 8) {
2731
- const sels = this.config.avoidSelectors;
2732
- if (!sels?.length) return null;
2733
- let maxBottom = 0;
2734
- for (const sel of sels) {
2735
- try {
2736
- const el = document.querySelector(sel);
2737
- if (!el) continue;
2738
- const r = el.getBoundingClientRect();
2739
- if (r.bottom > maxBottom && r.width > 0 && r.height > 0) {
2740
- maxBottom = r.bottom;
2741
- }
2742
- } catch {
2743
- }
2744
- }
2745
- return maxBottom > 0 ? Math.ceil(maxBottom) + gap : null;
3098
+ setSdkFreshness(info) {
3099
+ this.sdkFreshness = info;
3100
+ if (this.isOpen) this.render();
2746
3101
  }
2747
- applyInsetVars(el) {
2748
- const { anchor } = this.config;
2749
- if (anchor && Object.keys(anchor).length > 0) {
2750
- ["top", "right", "bottom", "left"].forEach((edge) => {
2751
- const value = anchor[edge];
2752
- if (value !== void 0) el.style.setProperty(`--mushi-${edge}`, value);
2753
- });
2754
- el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
2755
- } else {
2756
- const { inset } = this.config;
2757
- if (!this.config.respectSafeArea) {
2758
- ["top", "right", "bottom", "left"].forEach((edge) => {
2759
- if (inset[edge] === void 0) el.style.setProperty(`--mushi-${edge}`, "24px");
2760
- });
2761
- }
2762
- ["top", "right", "bottom", "left"].forEach((edge) => {
2763
- const value = inset[edge];
2764
- if (value === void 0) return;
2765
- el.style.setProperty(`--mushi-${edge}`, value === "auto" ? "auto" : `${value}px`);
2766
- });
2767
- el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
2768
- }
2769
- const isTopAnchored = anchor?.top !== void 0 || this.config.position?.startsWith("top") || !this.config.position && !anchor?.bottom;
2770
- if (isTopAnchored) {
2771
- const avoidPx = this.computeAvoidTopPx();
2772
- if (avoidPx !== null) {
2773
- el.style.setProperty("--mushi-top", `${avoidPx}px`);
2774
- }
2775
- }
3102
+ setRewardsState(state) {
3103
+ this.rewardsState = state;
3104
+ if (this.isOpen) this.render();
2776
3105
  }
2777
- renderStep() {
2778
- switch (this.step) {
2779
- case "category":
2780
- return this.renderCategoryStep();
2781
- case "intent":
2782
- return this.renderIntentStep();
2783
- case "details":
2784
- return this.renderDetailsStep();
2785
- case "success":
2786
- return this.renderSuccessStep();
2787
- case "reports":
2788
- return this.renderReportsStep();
2789
- case "report-detail":
2790
- return this.renderReportDetailStep();
2791
- case "leaderboard":
2792
- return this.renderLeaderboardStep();
2793
- case "roadmap":
2794
- return this.renderRoadmapStep();
2795
- }
2796
- }
2797
- renderOutdatedBanner() {
2798
- if (!this.sdkFreshness) return "";
2799
- if (this.config.outdatedBanner === "off" || this.config.outdatedBanner === "console-only") return "";
2800
- const { latest, current, deprecated, message } = this.sdkFreshness;
2801
- if (!latest && !deprecated) return "";
2802
- return `
2803
- <div class="mushi-outdated" role="status">
2804
- <strong>Mushi SDK ${escapeHtml(current)}</strong>
2805
- ${latest ? `latest is ${escapeHtml(latest)}.` : "needs attention."}
2806
- ${message ? `<span>${escapeHtml(message)}</span>` : ""}
2807
- </div>
2808
- `;
3106
+ setLeaderboard(entries, loading = false) {
3107
+ this.leaderboardEntries = entries;
3108
+ this.leaderboardLoading = loading;
3109
+ if (this.isOpen && this.step === "leaderboard") this.render();
3110
+ }
3111
+ // ── Community public setters (called by mushi.ts after API calls) ──────────
3112
+ setTesterSession(jwt, info) {
3113
+ this.testerJwt = jwt;
3114
+ this.testerInfo = info;
3115
+ if (this.isOpen) this.render();
2809
3116
  }
2810
- renderBrandFooter() {
2811
- if (this.config.brandFooter === false) return "";
2812
- return `<div class="mushi-brand-footer">Powered by Mushi v${escapeHtml(this.sdkVersion)}</div>`;
3117
+ setGlobalLeaderboard(entries, loading = false) {
3118
+ this.globalLeaderboard = entries;
3119
+ this.globalLeaderboardLoading = loading;
3120
+ if (this.isOpen && (this.step === "leaderboard" || this.step === "account")) this.render();
3121
+ }
3122
+ setCrossAppReports(reports, loading = false) {
3123
+ this.crossAppReports = reports;
3124
+ this.crossAppLoading = loading;
3125
+ if (this.isOpen && this.step === "cross-app-reports") this.render();
3126
+ }
3127
+ setTesterReputation(rep) {
3128
+ this.testerReputation = rep;
3129
+ if (this.isOpen && (this.step === "account" || this.step === "leaderboard")) this.render();
3130
+ }
3131
+ destroy() {
3132
+ if (this.successTimer !== null) {
3133
+ clearTimeout(this.successTimer);
3134
+ this.successTimer = null;
3135
+ }
3136
+ if (this.autoCloseTimer !== null) {
3137
+ clearTimeout(this.autoCloseTimer);
3138
+ this.autoCloseTimer = null;
3139
+ }
3140
+ if (this.smartHideTimer !== null) {
3141
+ clearTimeout(this.smartHideTimer);
3142
+ this.smartHideTimer = null;
3143
+ }
3144
+ this.smartHideCleanup?.();
3145
+ this.smartHideCleanup = null;
3146
+ this.teardownViewportHandlers();
3147
+ this.attachedLaunchers.forEach((cleanup) => cleanup());
3148
+ this.attachedLaunchers = [];
3149
+ this.removeSelectorHint();
3150
+ this.removeNudge();
3151
+ this.removeBodyNudge();
3152
+ this.host.remove();
2813
3153
  }
3154
+ /* ── Host chrome contract ────────────────────────────────────────────────
3155
+ The host element must never create an invisible full-screen touch blocker.
3156
+ We own these inline styles — consumer CSS can only win with `!important`,
3157
+ which is explicitly banned by the SDK contract. Calling this at mount()
3158
+ and after every zIndex update is the only safe invariant. */
2814
3159
  /**
2815
- * Editorial masthead. Always carries:
2816
- * • the brand mark (虫 kanji on vermillion, "MUSHI" in mono above)
2817
- * • the page title (serif display)
2818
- * • the close affordance
2819
- *
2820
- * On sub-steps it additionally renders a back button (replacing the
2821
- * "MUSHI" eyebrow with a "← BACK" mono link) and a step counter
2822
- * ledger ("02 / 03") on the far right.
3160
+ * Apply the SDK-owned pass-through layout to the host element so it is
3161
+ * always zero-sized and click/touch-transparent. Only the shadow-root
3162
+ * internals (`.mushi-trigger`, `.mushi-banner`, `.mushi-panel`) opt back
3163
+ * into pointer events. This is idempotent and safe to call repeatedly.
2823
3164
  */
2824
- renderHeader(opts) {
2825
- const t = this.locale;
2826
- const { title, showBack = false, step, eyebrow } = opts;
2827
- 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>`;
2828
- const counterHtml = step ? `<span class="mushi-step-counter" aria-label="Step ${step} of ${TOTAL_STEPS}"><b>${pad2(step)}</b> / ${pad2(TOTAL_STEPS)}</span>` : "";
2829
- return `
2830
- <div class="mushi-header">
2831
- <div class="mushi-header-mark" aria-hidden="true">\u866B</div>
2832
- <div class="mushi-header-titles">
2833
- ${eyebrowHtml}
2834
- <h3>${title}</h3>
2835
- </div>
2836
- <div class="mushi-header-meta">
2837
- ${counterHtml}
2838
- <button type="button" class="mushi-close" data-action="close" aria-label="${t.widget.close}">\u2715</button>
2839
- </div>
2840
- </div>
2841
- `;
3165
+ syncHostChromeState() {
3166
+ const s = this.host.style;
3167
+ s.setProperty("position", "fixed");
3168
+ s.setProperty("top", "0");
3169
+ s.setProperty("left", "0");
3170
+ s.setProperty("width", "0");
3171
+ s.setProperty("height", "0");
3172
+ s.setProperty("overflow", "visible");
3173
+ s.setProperty("pointer-events", "none");
3174
+ s.setProperty("z-index", String(this.config.zIndex));
3175
+ s.setProperty("margin", "0");
3176
+ s.setProperty("padding", "0");
3177
+ s.setProperty("border", "none");
3178
+ s.setProperty("background", "none");
2842
3179
  }
2843
3180
  /**
2844
- * Numeral step indicator: "01 — 02 — 03", with the active step in
2845
- * vermillion serif and completed steps struck through in mono.
2846
- * Replaces the original three-dot indicator (a generic SaaS pattern).
3181
+ * Returns true when a DOM element matching `hideOnSelector` is currently
3182
+ * present in the host document. Used by both the trigger and the banner
3183
+ * so a single selector consistently hides ALL SDK-injected launcher
3184
+ * surfaces. Invalid selectors are swallowed silently (non-fatal).
2847
3185
  */
2848
- renderStepIndicator(currentStep) {
2849
- const segments = [];
2850
- for (let i = 1; i <= TOTAL_STEPS; i++) {
2851
- const cls = i < currentStep ? "mushi-step-num done" : i === currentStep ? "mushi-step-num active" : "mushi-step-num";
2852
- segments.push(`<span class="${cls}">${pad2(i)}</span>`);
2853
- if (i < TOTAL_STEPS) segments.push('<span class="mushi-step-sep" aria-hidden="true"></span>');
3186
+ isSuppressedByHost() {
3187
+ if (!this.config.hideOnSelector || typeof document === "undefined") return false;
3188
+ try {
3189
+ return Boolean(document.querySelector(this.config.hideOnSelector));
3190
+ } catch {
3191
+ return false;
2854
3192
  }
2855
- return `<div class="mushi-step-indicator" aria-hidden="true">${segments.join("")}</div>`;
2856
- }
2857
- renderCategoryStep() {
2858
- const t = this.locale;
2859
- const categoryEntries = this.config.categories && this.config.categories.length > 0 ? this.config.categories.map((c) => ({
2860
- id: c.id,
2861
- icon: c.icon ?? "\u{1F4AC}",
2862
- label: c.label,
2863
- desc: c.description ?? ""
2864
- })) : ["bug", "slow", "visual", "confusing", "other"].map((id) => ({
2865
- id,
2866
- icon: CATEGORY_ICONS[id],
2867
- label: t.step1.categories[id],
2868
- desc: t.step1.categoryDescriptions[id]
2869
- }));
2870
- const categories = categoryEntries.map(({ id, icon, label, desc }) => `
2871
- <button type="button" class="mushi-option-btn" data-category="${escapeHtml(id)}" role="radio" aria-checked="false">
2872
- <span class="mushi-option-icon" aria-hidden="true">${escapeHtml(icon)}</span>
2873
- <div class="mushi-option-text">
2874
- <span class="mushi-option-label">${escapeHtml(label)}</span>
2875
- ${desc ? `<span class="mushi-option-desc">${escapeHtml(desc)}</span>` : ""}
2876
- </div>
2877
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2878
- </button>
2879
- `).join("");
2880
- return `
2881
- ${this.renderHeader({ title: t.step1.heading, step: STEP_NUMBER.category })}
2882
- ${this.config.betaMode?.enabled ? this.renderBetaStrip() : ""}
2883
- <div class="mushi-body" role="radiogroup" aria-label="${t.step1.heading}">
2884
- <button type="button" class="mushi-option-btn mushi-reports-entry" data-action="reports">
2885
- <span class="mushi-option-icon" aria-hidden="true">\u{1F4EC}</span>
2886
- <div class="mushi-option-text">
2887
- <span class="mushi-option-label">Your reports${this.unreadCount() ? ` (${this.unreadCount()} new)` : ""}</span>
2888
- <span class="mushi-option-desc">See status, developer replies, and respond</span>
2889
- </div>
2890
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2891
- </button>
2892
- ${this.renderFeatureRequestEntry()}
2893
- ${this.callbacks.onFeatureBoardRequest ? `
2894
- <button type="button" class="mushi-option-btn" data-action="roadmap">
2895
- <span class="mushi-option-icon" aria-hidden="true">\u{1F5F3}\uFE0F</span>
2896
- <div class="mushi-option-text">
2897
- <span class="mushi-option-label">Community ideas</span>
2898
- <span class="mushi-option-desc">Vote on features and see what shipped</span>
2899
- </div>
2900
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2901
- </button>` : ""}
2902
- ${categories}
2903
- ${this.rewardsState ? this.renderRewardsNudge() : ""}
2904
- </div>
2905
- ${this.renderStepIndicator(STEP_NUMBER.category)}
2906
- `;
2907
3193
  }
2908
3194
  /**
2909
- * First-class "Feature request" entry rendered at the top of the
2910
- * category step. Beta apps consistently get more useful signal when
2911
- * the user has a no-friction path to say "I wish this did X" — burying
2912
- * it as an intent under the "Other" category drops feature submissions
2913
- * by ~40% in industry studies (Userpilot, Usersnap 2025).
2914
- *
2915
- * Wire format: still routes through the standard `other` category with
2916
- * a `user_category = 'Feature request'` stamp, so we don't need a DB
2917
- * migration. The admin console filters on that string to surface the
2918
- * Feature-request swimlane.
3195
+ * Returns a snapshot of the widget's host-layer health for use in
3196
+ * `Mushi.diagnose()`. Callers check this to know whether the widget
3197
+ * could ever block host-app UI without opening a browser devtools.
2919
3198
  */
2920
- renderFeatureRequestEntry() {
2921
- const enabled = this.config.featureRequestCard !== false;
2922
- if (!enabled) return "";
2923
- const label = this.config.featureRequestLabel ?? "Feature request";
2924
- const desc = this.config.featureRequestDescription ?? "Suggest something new \u2014 even rough ideas help us prioritise";
2925
- return `
2926
- <button
2927
- type="button"
2928
- class="mushi-option-btn mushi-feature-entry"
2929
- data-action="feature-request"
2930
- aria-label="${escapeHtml(label)}"
2931
- >
2932
- <span class="mushi-option-icon" aria-hidden="true">\u2728</span>
2933
- <div class="mushi-option-text">
2934
- <span class="mushi-option-label">${escapeHtml(label)}</span>
2935
- <span class="mushi-option-desc">${escapeHtml(desc)}</span>
2936
- </div>
2937
- <span class="mushi-option-arrow" aria-hidden="true">\u2192</span>
2938
- </button>
2939
- `;
3199
+ getWidgetDiagnostics() {
3200
+ const s = this.host.style;
3201
+ const widgetHostPointerSafe = s.pointerEvents === "none" && (s.width === "0" || s.width === "0px") && (s.height === "0" || s.height === "0px");
3202
+ const widgetHostBounds = this.host.isConnected ? { width: this.host.offsetWidth, height: this.host.offsetHeight } : null;
3203
+ const widgetSuppressed = this.isSuppressedByHost() || this.isRouteHidden() || !this.triggerVisible;
3204
+ const bannerRendered = this.config.trigger === "banner" && !this.bannerDismissed && !this.isSuppressedByHost() && !this.isRouteHidden() && this.triggerVisible;
3205
+ return { widgetHostPointerSafe, widgetHostBounds, widgetSuppressed, bannerRendered };
2940
3206
  }
2941
- /** Collapsible "What's new" changelog row. Closes the reporter feedback loop. */
2942
- renderBetaChangelog() {
2943
- const entries = this.config.betaMode?.changelogItems;
2944
- if (!entries?.length) return "";
2945
- const latest = entries[0];
2946
- const items = latest.items.map((item) => `<li>\u2022 ${escapeHtml(item)}</li>`).join("");
2947
- const label = latest.date ? `What\u2019s new in ${escapeHtml(latest.version)} \xB7 ${escapeHtml(latest.date)}` : `What\u2019s new in ${escapeHtml(latest.version)}`;
2948
- return `
2949
- <details class="mushi-changelog">
2950
- <summary class="mushi-changelog-summary">${label}</summary>
2951
- <ul class="mushi-changelog-list">${items}</ul>
2952
- </details>
2953
- `;
3207
+ syncAttachedLaunchers() {
3208
+ this.attachedLaunchers.forEach((cleanup) => cleanup());
3209
+ this.attachedLaunchers = [];
3210
+ if (this.config.trigger !== "attach" || !this.config.attachToSelector) return;
3211
+ if (typeof document === "undefined") return;
3212
+ this.attachedLaunchers.push(this.attachTo(this.config.attachToSelector));
2954
3213
  }
2955
- /**
2956
- * Discreet beta status strip: communicates "work in progress", invites
2957
- * feedback, and sets expectations — reducing user frustration while
2958
- * nudging the reciprocity instinct ("your reports help us build this").
2959
- */
2960
- renderBetaStrip() {
2961
- const beta = this.config.betaMode;
2962
- const appName = escapeHtml(beta.appName ?? "This app");
2963
- const message = beta.message ? escapeHtml(beta.message) : `${appName} is in early development \u2014 updates ship weekly`;
2964
- const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
2965
- const perks = beta.perks ?? [];
2966
- return `
2967
- <div class="mushi-beta-strip" role="note" aria-label="Beta status">
2968
- <div class="mushi-beta-strip-row">
2969
- <span class="mushi-beta-tag" aria-hidden="true">BETA</span>
2970
- <span class="mushi-beta-msg">${message}</span>
2971
- </div>
2972
- ${email ? `<div class="mushi-beta-contact-hint">Reports go to ${email} \xB7 reviewed by the team</div>` : ""}
2973
- ${perks.length > 0 ? `
2974
- <ul class="mushi-beta-perks" aria-label="Beta tester perks">
2975
- ${perks.map((p) => `<li>\u2713 ${escapeHtml(p)}</li>`).join("")}
2976
- </ul>
2977
- ` : ""}
2978
- ${this.renderBetaChangelog()}
2979
- </div>
2980
- `;
3214
+ syncSmartHide() {
3215
+ this.smartHideCleanup?.();
3216
+ this.smartHideCleanup = null;
3217
+ this.triggerShrunk = false;
3218
+ this.triggerHiddenByScroll = false;
3219
+ if (!this.config.smartHide || typeof window === "undefined") return;
3220
+ const smart = this.config.smartHide === true ? { onScroll: "shrink", onIdleMs: 900 } : this.config.smartHide;
3221
+ if (!smart.onScroll) return;
3222
+ const onScroll = () => {
3223
+ if (smart.onScroll === "hide") {
3224
+ this.triggerHiddenByScroll = true;
3225
+ } else {
3226
+ this.triggerShrunk = true;
3227
+ }
3228
+ this.render();
3229
+ if (this.smartHideTimer !== null) clearTimeout(this.smartHideTimer);
3230
+ this.smartHideTimer = setTimeout(() => {
3231
+ this.triggerHiddenByScroll = false;
3232
+ this.triggerShrunk = false;
3233
+ this.render();
3234
+ }, smart.onIdleMs ?? 900);
3235
+ };
3236
+ window.addEventListener("scroll", onScroll, { passive: true });
3237
+ this.smartHideCleanup = () => window.removeEventListener("scroll", onScroll);
2981
3238
  }
2982
- renderReportsStep() {
2983
- const reports = this.reporterReports.map((report) => {
2984
- const title = report.summary ?? report.description ?? `Report ${report.id.slice(0, 8)}`;
2985
- const tone = reporterStatusTone(report.status);
2986
- const when = formatRelativeTime(report.created_at);
2987
- const unread = report.unread_count && report.unread_count > 0 ? `<span class="mushi-unread-badge" aria-label="${report.unread_count} unread">${report.unread_count}</span>` : "";
2988
- return `
2989
- <button type="button" class="mushi-report-row" data-report-id="${escapeHtml(report.id)}" aria-label="View report: ${escapeHtml(title)}">
2990
- <div class="mushi-report-main">
2991
- <span class="mushi-report-title">${escapeHtml(title)}</span>
2992
- <span class="mushi-report-meta">
2993
- <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusShort(report.status))}</span>
2994
- ${when ? `<span class="mushi-report-when">${escapeHtml(when)}</span>` : ""}
2995
- ${unread}
2996
- </span>
2997
- </div>
2998
- <span class="mushi-report-chevron" aria-hidden="true">\u203A</span>
2999
- </button>`;
3000
- }).join("");
3001
- const leaderboardBtn = this.rewardsState ? `<button type="button" class="mushi-leaderboard-link" data-action="open-leaderboard">\u{1F3C6} Leaderboard</button>` : "";
3002
- return `
3003
- ${this.renderHeader({ title: "Your reports", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
3004
- <div class="mushi-body">
3005
- ${this.reporterLoading ? '<p class="mushi-muted">Loading reports\u2026</p>' : ""}
3006
- ${this.reporterError ? `<p class="mushi-error-inline">${escapeHtml(this.reporterError)}</p>` : ""}
3007
- ${reports || (!this.reporterLoading ? '<p class="mushi-muted">No reports from this browser yet.</p>' : "")}
3008
- ${leaderboardBtn}
3009
- </div>
3010
- `;
3239
+ shouldRenderTrigger() {
3240
+ if (!this.triggerVisible) return false;
3241
+ if (this.triggerHiddenByScroll) return false;
3242
+ if (this.config.trigger === "manual" || this.config.trigger === "hidden" || this.config.trigger === "attach" || this.config.trigger === "banner") {
3243
+ return false;
3244
+ }
3245
+ if (this.isMobileSmartHidden()) return false;
3246
+ if (this.isRouteHidden()) return false;
3247
+ if (this.isSuppressedByHost()) return false;
3248
+ const action = this.config.environments[this.detectEnvironment()];
3249
+ return action !== "never" && action !== "manual";
3250
+ }
3251
+ /** Height of the banner in px — kept in sync with the CSS `.mushi-banner` height (36px). */
3252
+ static BANNER_HEIGHT = 36;
3253
+ /** CSS property applied to document.body so host-app content doesn't slide under the banner. */
3254
+ static BODY_NUDGE_PROP = "--mushi-banner-offset";
3255
+ applyBodyNudge(position) {
3256
+ const h = `${_MushiWidget.BANNER_HEIGHT}px`;
3257
+ if (position === "top") {
3258
+ document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
3259
+ if (!document.body.style.paddingTop) {
3260
+ document.body.style.paddingTop = h;
3261
+ document.body.dataset.mushiBannerNudged = "top";
3262
+ }
3263
+ } else {
3264
+ document.documentElement.style.setProperty(_MushiWidget.BODY_NUDGE_PROP, h);
3265
+ if (!document.body.style.paddingBottom) {
3266
+ document.body.style.paddingBottom = h;
3267
+ document.body.dataset.mushiBannerNudged = "bottom";
3268
+ }
3269
+ }
3270
+ }
3271
+ removeBodyNudge() {
3272
+ document.documentElement.style.removeProperty(_MushiWidget.BODY_NUDGE_PROP);
3273
+ const nudged = document.body.dataset.mushiBannerNudged;
3274
+ if (nudged === "top") {
3275
+ document.body.style.paddingTop = "";
3276
+ delete document.body.dataset.mushiBannerNudged;
3277
+ } else if (nudged === "bottom") {
3278
+ document.body.style.paddingBottom = "";
3279
+ delete document.body.dataset.mushiBannerNudged;
3280
+ }
3281
+ }
3282
+ renderBanner() {
3283
+ if (this.config.trigger !== "banner") return;
3284
+ if (this.bannerDismissed) {
3285
+ this.removeBodyNudge();
3286
+ return;
3287
+ }
3288
+ if (!this.triggerVisible) {
3289
+ this.removeBodyNudge();
3290
+ return;
3291
+ }
3292
+ if (this.isRouteHidden()) {
3293
+ this.removeBodyNudge();
3294
+ return;
3295
+ }
3296
+ if (this.isSuppressedByHost()) {
3297
+ this.removeBodyNudge();
3298
+ return;
3299
+ }
3300
+ const bc = this.config.bannerConfig ?? {};
3301
+ const variant = bc.variant ?? "brand";
3302
+ const position = bc.position ?? "top";
3303
+ const message = bc.message?.trim() ?? "";
3304
+ const richLayout = message.length > 0;
3305
+ const bugLabel = bc.bugCta ?? "\u{1F41B} Report a bug";
3306
+ const showFeat = bc.featureCta !== false;
3307
+ const featLabel = bc.featureCtaLabel ?? "Request feature";
3308
+ const zIdx = bc.zIndex ?? (this.config.zIndex ?? 99999) - 1;
3309
+ const banner = document.createElement("div");
3310
+ banner.className = `mushi-banner ${variant} ${position}${richLayout ? " mushi-banner--rich" : ""}`;
3311
+ banner.style.setProperty("--mushi-banner-z", String(zIdx));
3312
+ banner.setAttribute("role", "banner");
3313
+ const dismissBtn = document.createElement("button");
3314
+ dismissBtn.className = "mushi-banner-dismiss";
3315
+ dismissBtn.textContent = "\u2715";
3316
+ dismissBtn.setAttribute("aria-label", "Dismiss feedback banner");
3317
+ dismissBtn.addEventListener("click", () => {
3318
+ this.bannerDismissed = true;
3319
+ this.removeBodyNudge();
3320
+ this.render();
3321
+ });
3322
+ if (richLayout) {
3323
+ const body = document.createElement("div");
3324
+ body.className = "mushi-banner-body";
3325
+ const labelText = bc.label === false ? null : bc.label ?? "Beta";
3326
+ if (labelText) {
3327
+ const pill = document.createElement("span");
3328
+ pill.className = "mushi-banner-pill";
3329
+ pill.textContent = labelText;
3330
+ body.appendChild(pill);
3331
+ }
3332
+ const msg = document.createElement("span");
3333
+ msg.className = "mushi-banner-message";
3334
+ msg.textContent = message;
3335
+ body.appendChild(msg);
3336
+ banner.appendChild(body);
3337
+ const nav = document.createElement("nav");
3338
+ nav.className = "mushi-banner-actions";
3339
+ nav.setAttribute("aria-label", "Feedback banner actions");
3340
+ const appendDivider = (extra = false) => {
3341
+ const sep = document.createElement("span");
3342
+ sep.className = `mushi-banner-divider${extra ? " mushi-banner-extra" : ""}`;
3343
+ sep.setAttribute("aria-hidden", "true");
3344
+ sep.textContent = "|";
3345
+ nav.appendChild(sep);
3346
+ };
3347
+ const appendAction = (label, onClick, extra = false) => {
3348
+ const btn = document.createElement("button");
3349
+ btn.type = "button";
3350
+ btn.className = `mushi-banner-link${extra ? " mushi-banner-extra" : ""}`;
3351
+ btn.textContent = label;
3352
+ btn.addEventListener("click", onClick);
3353
+ nav.appendChild(btn);
3354
+ };
3355
+ appendAction(bugLabel, () => this.open());
3356
+ if (showFeat) {
3357
+ appendDivider(true);
3358
+ appendAction(featLabel, () => this.open({ featureRequest: true }), true);
3359
+ }
3360
+ for (const link of bc.links ?? []) {
3361
+ const linkLabel = link.label?.trim();
3362
+ if (!linkLabel) continue;
3363
+ const href = link.href && (/^https?:\/\//i.test(link.href) || link.href.startsWith("/")) ? link.href : void 0;
3364
+ appendDivider(true);
3365
+ if (href) {
3366
+ const anchor = document.createElement("a");
3367
+ anchor.className = "mushi-banner-link mushi-banner-extra";
3368
+ anchor.href = href;
3369
+ anchor.textContent = linkLabel;
3370
+ anchor.target = "_blank";
3371
+ anchor.rel = "noopener noreferrer";
3372
+ nav.appendChild(anchor);
3373
+ } else {
3374
+ appendAction(linkLabel, () => {
3375
+ if (link.featureRequest) this.open({ featureRequest: true });
3376
+ else this.open();
3377
+ }, true);
3378
+ }
3379
+ }
3380
+ banner.appendChild(nav);
3381
+ banner.appendChild(dismissBtn);
3382
+ } else {
3383
+ const bugBtn = document.createElement("button");
3384
+ bugBtn.className = "mushi-banner-btn";
3385
+ bugBtn.textContent = bugLabel;
3386
+ bugBtn.addEventListener("click", () => this.open());
3387
+ banner.appendChild(bugBtn);
3388
+ if (showFeat) {
3389
+ const featBtn = document.createElement("button");
3390
+ featBtn.className = "mushi-banner-btn";
3391
+ featBtn.textContent = featLabel;
3392
+ featBtn.addEventListener("click", () => this.open({ featureRequest: true }));
3393
+ banner.appendChild(featBtn);
3394
+ }
3395
+ banner.appendChild(dismissBtn);
3396
+ }
3397
+ this.shadow.appendChild(banner);
3398
+ this.applyBodyNudge(position);
3011
3399
  }
3012
- renderRoadmapStep() {
3013
- const rows = this.featureBoard.map((ticket) => {
3014
- const id = String(ticket.id ?? "");
3015
- const subject = escapeHtml(String(ticket.subject ?? "Untitled idea"));
3016
- const votes = Number(ticket.vote_count ?? 0);
3017
- const shipped = Boolean(ticket.shipped_at);
3018
- const voted = Boolean(ticket.my_vote);
3019
- const status = shipped ? "Shipped" : String(ticket.status_label ?? ticket.status ?? "open");
3020
- return `
3021
- <div class="mushi-report-row mushi-roadmap-row">
3022
- <div class="mushi-report-main">
3023
- <span class="mushi-report-title">${subject}</span>
3024
- <span class="mushi-report-meta">
3025
- <span class="mushi-report-status">${escapeHtml(status)}</span>
3026
- <span class="mushi-report-when">${votes} vote${votes === 1 ? "" : "s"}</span>
3027
- </span>
3028
- </div>
3029
- ${this.callbacks.onFeatureBoardVote ? `
3030
- <button type="button" class="mushi-vote-btn" data-vote-id="${escapeHtml(id)}" aria-pressed="${voted}">
3031
- ${voted ? "Voted" : "Vote"}
3032
- </button>` : ""}
3033
- </div>`;
3034
- }).join("");
3035
- return `
3036
- ${this.renderHeader({ title: "Community ideas", showBack: true, eyebrow: "Mushi \xB7 Roadmap" })}
3037
- <div class="mushi-body">
3038
- ${this.reporterLoading ? '<p class="mushi-muted">Loading ideas\u2026</p>' : ""}
3039
- ${this.reporterError ? `<p class="mushi-error-inline">${escapeHtml(this.reporterError)}</p>` : ""}
3040
- ${rows || (!this.reporterLoading ? '<p class="mushi-muted">No community ideas yet. Be the first to suggest one.</p>' : "")}
3041
- </div>
3042
- `;
3400
+ effectiveTrigger() {
3401
+ if (!this.config.smartHide || typeof window === "undefined") return this.config.trigger;
3402
+ const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
3403
+ if (window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "edge-tab") {
3404
+ return "edge-tab";
3405
+ }
3406
+ return this.config.trigger;
3043
3407
  }
3044
- renderLeaderboardStep() {
3045
- const myRank = this.rewardsState && this.leaderboardEntries ? this.leaderboardEntries.findIndex((e) => e.display_name === "You") + 1 : 0;
3046
- const rows = (this.leaderboardEntries ?? []).map((e, i) => `
3047
- <div class="mushi-lb-row ${i === 0 ? "mushi-lb-top" : ""}">
3048
- <span class="mushi-lb-rank">#${i + 1}</span>
3049
- <span class="mushi-lb-name">${escapeHtml(e.display_name)}</span>
3050
- ${e.tier_name ? `<span class="mushi-lb-tier">${escapeHtml(e.tier_name)}</span>` : ""}
3051
- <span class="mushi-lb-pts">${e.total_points.toLocaleString()} pts</span>
3052
- </div>
3053
- `).join("");
3054
- return `
3055
- ${this.renderHeader({ title: "\u{1F3C6} Leaderboard", showBack: true, eyebrow: "Mushi \xB7 Contributors" })}
3056
- <div class="mushi-body">
3057
- ${this.leaderboardLoading ? '<p class="mushi-muted">Loading leaderboard\u2026</p>' : ""}
3058
- ${!this.leaderboardLoading && !this.leaderboardEntries?.length ? '<p class="mushi-muted">No contributors yet \u2014 be the first!</p>' : ""}
3059
- <div class="mushi-lb-list">${rows}</div>
3060
- ${myRank > 0 ? `<p class="mushi-lb-myrank">You are ranked #${myRank}</p>` : ""}
3061
- <p class="mushi-lb-note">Top contributors this month \xB7 Points refresh monthly</p>
3062
- </div>
3063
- `;
3408
+ isMobileSmartHidden() {
3409
+ if (!this.config.smartHide || typeof window === "undefined") return false;
3410
+ const smart = this.config.smartHide === true ? { onMobile: "edge-tab" } : this.config.smartHide;
3411
+ return window.matchMedia("(max-width: 768px)").matches && smart.onMobile === "hide";
3064
3412
  }
3065
- renderReportDetailStep() {
3066
- const report = this.reporterReports.find((r) => r.id === this.selectedReportId);
3067
- const status = report?.status ?? "unknown";
3068
- const tone = reporterStatusTone(status);
3069
- const when = report?.created_at ? formatRelativeTime(report.created_at) : "";
3070
- const comments = this.reporterComments.map((comment) => `
3071
- <div class="mushi-thread-comment ${comment.author_kind}">
3072
- <strong>${escapeHtml(comment.author_kind === "reporter" ? "You" : comment.author_name ?? "Developer")}</strong>
3073
- <p>${escapeHtml(comment.body)}</p>
3074
- </div>
3075
- `).join("");
3076
- return `
3077
- ${this.renderHeader({ title: "Report thread", showBack: true, eyebrow: "Mushi \xB7 Inbox" })}
3078
- <div class="mushi-body">
3079
- <div class="mushi-thread-summary">
3080
- <div class="mushi-thread-summary-meta">
3081
- <span class="mushi-report-status mushi-status-${tone}">${escapeHtml(reporterStatusLabel(status))}</span>
3082
- ${when ? `<span class="mushi-report-when">Reported ${escapeHtml(when)}</span>` : ""}
3083
- </div>
3084
- <p>${escapeHtml(report?.summary ?? report?.description ?? "Report details")}</p>
3085
- </div>
3086
- <div class="mushi-thread">
3087
- ${this.reporterLoading ? '<p class="mushi-muted">Loading thread\u2026</p>' : comments || '<p class="mushi-muted">No developer replies yet.</p>'}
3088
- </div>
3089
- ${["fixed", "resolved", "verified"].includes(status) ? `
3090
- <div class="mushi-verify-actions" role="group" aria-label="Fix verification">
3091
- <button type="button" class="mushi-intent-btn" data-action="reporter-confirms">Yes, fixed for me</button>
3092
- <button type="button" class="mushi-intent-btn" data-action="reporter-not-fixed">Not fixed yet</button>
3093
- </div>
3094
- ` : ""}
3095
- <textarea class="mushi-textarea" data-role="reporter-reply" rows="3" placeholder="Reply to the developer\u2026"></textarea>
3096
- <button type="button" class="mushi-submit" data-action="reporter-reply">
3097
- <span>Reply</span><span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
3098
- </button>
3099
- </div>
3100
- `;
3413
+ detectEnvironment() {
3414
+ const host = typeof location !== "undefined" ? location.hostname : "";
3415
+ if (host === "localhost" || host === "127.0.0.1" || host.endsWith(".local")) return "development";
3416
+ if (/\b(staging|stage|preview|dev)\b/i.test(host)) return "staging";
3417
+ return "production";
3101
3418
  }
3102
- renderIntentStep() {
3103
- const t = this.locale;
3104
- const catId = this.selectedCategory;
3105
- const customEntry = this.resolveCustomCategory(catId);
3106
- const intents = customEntry?.intents ?? (t.step2.intents[catId] || []);
3107
- const options = intents.map((intent) => `
3108
- <button type="button" class="mushi-intent-btn" data-intent="${escapeHtml(intent)}">
3109
- ${escapeHtml(intent)}
3110
- </button>
3111
- `).join("");
3112
- const icon = this.categoryIcon(catId);
3113
- const label = this.categoryLabel(catId);
3114
- return `
3115
- ${this.renderHeader({ title: t.step2.heading, showBack: true, step: STEP_NUMBER.intent })}
3116
- <div class="mushi-body">
3117
- <div class="mushi-selected-category">
3118
- <span aria-hidden="true">${escapeHtml(icon)}</span>
3119
- <span>${escapeHtml(label)}</span>
3120
- </div>
3121
- <div class="mushi-intents">
3122
- ${options}
3123
- </div>
3124
- </div>
3125
- ${this.renderStepIndicator(STEP_NUMBER.intent)}
3126
- `;
3419
+ isRouteHidden() {
3420
+ if (!this.config.hideOnRoutes.length || typeof location === "undefined") return false;
3421
+ return this.config.hideOnRoutes.some((route) => location.pathname.includes(route));
3127
3422
  }
3128
- effectiveMinLength() {
3129
- const base = this.config.minDescriptionLength ?? 20;
3130
- const lang = this.config.locale === "auto" ? typeof navigator !== "undefined" ? navigator.language ?? "" : "" : this.config.locale ?? "";
3131
- const isCjk = /^(ja|zh|ko)/i.test(lang);
3132
- return isCjk ? Math.max(4, Math.floor(base / 2)) : base;
3423
+ getTheme() {
3424
+ const t = this.config.theme;
3425
+ if (t === "light" || t === "dark") return t;
3426
+ if (t === "inherit") {
3427
+ const root = document.documentElement;
3428
+ const colorScheme = root.getAttribute("data-color-scheme") || root.getAttribute("data-theme") || root.getAttribute("color-scheme") || "";
3429
+ if (/dark/i.test(colorScheme)) return "dark";
3430
+ if (/light/i.test(colorScheme)) return "light";
3431
+ if (root.classList.contains("dark")) return "dark";
3432
+ if (root.classList.contains("light")) return "light";
3433
+ try {
3434
+ const bg = getComputedStyle(root).backgroundColor;
3435
+ const m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
3436
+ if (m) {
3437
+ const L = 0.299 * +m[1] + 0.587 * +m[2] + 0.114 * +m[3];
3438
+ return L < 128 ? "dark" : "light";
3439
+ }
3440
+ } catch {
3441
+ }
3442
+ }
3443
+ if (typeof window !== "undefined" && window.matchMedia("(prefers-color-scheme: dark)").matches) {
3444
+ return "dark";
3445
+ }
3446
+ return "light";
3133
3447
  }
3134
- renderDetailsStep() {
3448
+ render() {
3449
+ const theme = this.getTheme();
3450
+ const pos = this.config.position;
3135
3451
  const t = this.locale;
3136
- const minLen = this.effectiveMinLength();
3137
- const screenshotLabel = this.screenshotCapturing ? t.step3.screenshotCapturing : this.screenshotError ? t.step3.screenshotFailed : this.screenshotAttached ? t.step3.screenshotAttached : t.step3.screenshotButton;
3138
- const screenshotClass = [
3139
- "mushi-attach-btn",
3140
- this.screenshotAttached ? "active" : "",
3141
- this.screenshotError ? "error" : "",
3142
- this.screenshotCapturing ? "loading" : ""
3143
- ].filter(Boolean).join(" ");
3144
- const elementLabel = this.elementCapturing ? t.step3.elementCapturing : this.elementSelected ? t.step3.elementSelected : t.step3.elementButton;
3145
- const elementClass = [
3146
- "mushi-attach-btn",
3147
- this.elementSelected ? "active" : "",
3148
- this.elementCapturing ? "loading" : ""
3149
- ].filter(Boolean).join(" ");
3150
- const exampleChips = t.step3.examplePrompts.map((p) => `<button type="button" class="mushi-example-chip" data-example="${escapeHtml(p)}">${escapeHtml(p)}</button>`).join("");
3151
- return `
3152
- ${this.renderHeader({ title: t.step3.heading, showBack: true, step: STEP_NUMBER.details })}
3153
- <div class="mushi-body">
3154
- <div class="mushi-example-chips" aria-label="Example prompts">${exampleChips}</div>
3155
- <div class="mushi-textarea-wrap">
3156
- <textarea
3157
- class="mushi-textarea"
3158
- placeholder="${t.step3.descriptionPlaceholder}"
3159
- rows="4"
3160
- aria-label="${t.step3.heading}"
3161
- autofocus
3162
- ></textarea>
3163
- <div class="mushi-char-counter" data-role="char-counter" aria-hidden="true">
3164
- <span data-role="char-current">0</span>/<span data-role="char-min">${minLen}</span>
3165
- </div>
3166
- </div>
3167
- <div class="mushi-attachments">
3168
- <button type="button" class="${screenshotClass}"
3169
- data-action="screenshot"
3170
- ${this.screenshotCapturing ? "disabled" : ""}
3171
- aria-label="${escapeHtml(screenshotLabel)}"
3172
- >
3173
- ${this.screenshotCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F4F8}"}
3174
- ${escapeHtml(screenshotLabel)}
3175
- </button>
3176
- ${this.screenshotAttached && this.allowScreenshotRemove ? '<button type="button" class="mushi-attach-btn danger" data-action="remove-screenshot" aria-label="Remove screenshot">\u2715 Remove</button>' : ""}
3177
- ${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>' : ""}
3178
- <button type="button" class="${elementClass}"
3179
- data-action="element"
3180
- ${this.elementCapturing ? "disabled" : ""}
3181
- aria-label="${escapeHtml(elementLabel)}"
3182
- >
3183
- ${this.elementCapturing ? '<span class="mushi-spinner" aria-hidden="true"></span>' : "\u{1F3AF}"}
3184
- ${escapeHtml(elementLabel)}
3185
- </button>
3186
- </div>
3187
- <div class="mushi-error" style="display:none" role="alert"></div>
3188
- </div>
3189
- <div class="mushi-footer">
3190
- <span class="mushi-footer-hint" aria-hidden="true">\u2318 + ENTER \u2192 send</span>
3191
- <button type="button" class="mushi-submit" data-action="submit"${this.submitting ? " disabled" : ""}>
3192
- <span>${this.submitting ? t.widget.submitting : t.widget.submit}</span>
3193
- <span class="mushi-submit-arrow" aria-hidden="true">\u2192</span>
3194
- </button>
3195
- </div>
3196
- ${this.renderStepIndicator(STEP_NUMBER.details)}
3197
- `;
3452
+ this.shadow.innerHTML = "";
3453
+ const style = document.createElement("style");
3454
+ style.textContent = getWidgetStyles(theme, this.config.accent ?? "", this.config.accentText ?? "");
3455
+ this.shadow.appendChild(style);
3456
+ this.renderBanner();
3457
+ if (this.shouldRenderTrigger()) {
3458
+ const effectiveTrigger = this.effectiveTrigger();
3459
+ const trigger = document.createElement("button");
3460
+ trigger.className = `mushi-trigger ${pos}${effectiveTrigger === "edge-tab" ? " edge-tab" : ""}${this.triggerShrunk ? " shrunk" : ""}`;
3461
+ trigger.textContent = this.config.triggerText;
3462
+ trigger.setAttribute("aria-label", t.widget.trigger);
3463
+ trigger.setAttribute("aria-haspopup", "dialog");
3464
+ trigger.setAttribute("aria-expanded", String(this.isOpen));
3465
+ trigger.style.zIndex = String(this.config.zIndex);
3466
+ this.applyInsetVars(trigger);
3467
+ trigger.addEventListener("click", () => {
3468
+ this.removeNudge();
3469
+ if (this.isOpen) this.close();
3470
+ else this.open();
3471
+ });
3472
+ trigger.addEventListener("mouseenter", () => {
3473
+ const onPageMs = this.mountedAt ? Date.now() - this.mountedAt : 0;
3474
+ if (!this.nudgeShown && !this.isOpen && onPageMs >= 3e4) {
3475
+ this.showNudge();
3476
+ }
3477
+ });
3478
+ trigger.addEventListener("mouseleave", () => {
3479
+ if (this.nudgeEl) {
3480
+ if (this.nudgeTimer !== null) clearTimeout(this.nudgeTimer);
3481
+ this.nudgeTimer = setTimeout(() => this.removeNudge(), 2e3);
3482
+ }
3483
+ });
3484
+ trigger.addEventListener("keydown", (e) => {
3485
+ const draggableConfig = this.config.draggable;
3486
+ if (!draggableConfig) return;
3487
+ const STEP = 8;
3488
+ const axis = typeof draggableConfig === "object" ? draggableConfig.axis ?? "both" : "both";
3489
+ let dx = 0, dy = 0;
3490
+ if (axis !== "y") {
3491
+ if (e.key === "ArrowLeft") dx = -STEP;
3492
+ else if (e.key === "ArrowRight") dx = STEP;
3493
+ }
3494
+ if (axis !== "x") {
3495
+ if (e.key === "ArrowUp") dy = -STEP;
3496
+ else if (e.key === "ArrowDown") dy = STEP;
3497
+ }
3498
+ if (dx !== 0 || dy !== 0) {
3499
+ e.preventDefault();
3500
+ const cur = this.fabPos ?? { x: 0, y: 0 };
3501
+ this.moveFab(trigger, cur.x + dx, cur.y + dy, false);
3502
+ }
3503
+ });
3504
+ if (this.config.draggable) {
3505
+ this.attachDragHandlers(trigger);
3506
+ }
3507
+ this.shadow.appendChild(trigger);
3508
+ if (this.fabPos && this.config.draggable) {
3509
+ const savedPos = this.fabPos;
3510
+ this.fabPos = { x: 0, y: 0 };
3511
+ this.moveFab(trigger, savedPos.x, savedPos.y, false);
3512
+ }
3513
+ }
3514
+ const panel = document.createElement("div");
3515
+ panel.className = `mushi-panel ${pos}${this.isOpen ? " open" : " closed"}`;
3516
+ panel.setAttribute("role", "dialog");
3517
+ panel.setAttribute("aria-modal", "true");
3518
+ panel.setAttribute("aria-label", t.widget.title);
3519
+ panel.style.zIndex = String(this.config.zIndex + 1);
3520
+ this.applyInsetVars(panel);
3521
+ if (this.isOpen) {
3522
+ const ctx = this.renderCtx();
3523
+ panel.innerHTML = `${renderOutdatedBanner(ctx)}${renderStep(ctx)}${renderBrandFooter(ctx)}`;
3524
+ this.shadow.appendChild(panel);
3525
+ this.attachHandlers(panel);
3526
+ this.trapFocus(panel);
3527
+ this.attachViewportHandlers(panel);
3528
+ } else {
3529
+ this.teardownViewportHandlers();
3530
+ }
3198
3531
  }
3199
3532
  /**
3200
- * Editorial success state: 朱印-style red stamp ring with the kanji
3201
- * 受 ("received") at its centre, the localised "thank you" string
3202
- * in serif below, and a mono ledger receipt ("REPORT · HH:MM:SS").
3203
- * The ring + label animations are defined in styles.ts so this stays
3204
- * pure markup and `prefers-reduced-motion` flips them to the final
3205
- * frame instantly.
3533
+ * Queries each `avoidSelectors` element in the host document and returns
3534
+ * the minimum top-offset in px so that a top-anchored element clears all
3535
+ * of them by `gap` pixels. Returns `null` when no selectors are provided
3536
+ * or no matching elements have a non-zero bounding rect.
3537
+ *
3538
+ * Runs in the host document (not shadow DOM) so it can reach fixed headers,
3539
+ * sticky nav bars, and sign-in CTAs.
3206
3540
  */
3207
- renderSuccessStep() {
3208
- const t = this.locale;
3209
- const stamp = this.submittedAt ?? /* @__PURE__ */ new Date();
3210
- const time = stamp.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
3211
- return `
3212
- ${this.renderHeader({ title: t.widget.title, eyebrow: "Mushi \xB7 Receipt" })}
3213
- <div class="mushi-body">
3214
- <div class="mushi-success">
3215
- <div class="mushi-success-stamp" aria-hidden="true">
3216
- <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet"><circle cx="50" cy="50" r="44"/></svg>
3217
- <span class="mushi-success-stamp-label">\u53D7</span>
3218
- </div>
3219
- <div class="mushi-success-headline">${t.widget.submitted}</div>
3220
- <div class="mushi-success-meta">REPORT \xB7 ${time}</div>
3221
- ${this.renderSuccessReceipt()}
3222
- ${this.rewardsState ? this.renderSuccessRewards() : ""}
3223
- ${this.config.betaMode?.enabled ? this.renderBetaSuccessFooter() : ""}
3224
- </div>
3225
- </div>
3226
- `;
3541
+ computeAvoidTopPx(gap = 8) {
3542
+ const sels = this.config.avoidSelectors;
3543
+ if (!sels?.length) return null;
3544
+ let maxBottom = 0;
3545
+ for (const sel of sels) {
3546
+ try {
3547
+ const el = document.querySelector(sel);
3548
+ if (!el) continue;
3549
+ const r = el.getBoundingClientRect();
3550
+ if (r.bottom > maxBottom && r.width > 0 && r.height > 0) {
3551
+ maxBottom = r.bottom;
3552
+ }
3553
+ } catch {
3554
+ }
3555
+ }
3556
+ return maxBottom > 0 ? Math.ceil(maxBottom) + gap : null;
3227
3557
  }
3228
- /**
3229
- * Two-way receipt block. Until the host's `onSubmit` resolves with a
3230
- * server-confirmed report id, we show a discreet "delivering..." pill so
3231
- * the user knows their submission is still in flight. Once we have the
3232
- * id, we surface a short monospaced id + a copy button + an optional
3233
- * "Track on Mushi" deep link to `dashboardUrl/reports/<id>` so the user
3234
- * can watch the status walk through queued -> classified -> fixed in
3235
- * real time (Peak-End rule: the last impression sticks). If we never
3236
- * get an id (offline retry queue), we say so explicitly rather than
3237
- * pretending everything is fine.
3238
- */
3239
- renderSuccessReceipt() {
3240
- if (this.lastSubmitQueuedOffline) {
3241
- return `
3242
- <div class="mushi-success-receipt" role="status">
3243
- <div class="mushi-success-receipt-row mushi-success-receipt-warn">
3244
- <span class="mushi-success-receipt-label">Queued offline</span>
3245
- <span class="mushi-success-receipt-hint">We&rsquo;ll send it the moment you&rsquo;re back online.</span>
3246
- </div>
3247
- </div>
3248
- `;
3558
+ applyInsetVars(el) {
3559
+ const { anchor } = this.config;
3560
+ if (anchor && Object.keys(anchor).length > 0) {
3561
+ ["top", "right", "bottom", "left"].forEach((edge) => {
3562
+ const value = anchor[edge];
3563
+ if (value !== void 0) el.style.setProperty(`--mushi-${edge}`, value);
3564
+ });
3565
+ el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
3566
+ } else {
3567
+ const { inset } = this.config;
3568
+ if (!this.config.respectSafeArea) {
3569
+ ["top", "right", "bottom", "left"].forEach((edge) => {
3570
+ if (inset[edge] === void 0) el.style.setProperty(`--mushi-${edge}`, "24px");
3571
+ });
3572
+ }
3573
+ ["top", "right", "bottom", "left"].forEach((edge) => {
3574
+ const value = inset[edge];
3575
+ if (value === void 0) return;
3576
+ el.style.setProperty(`--mushi-${edge}`, value === "auto" ? "auto" : `${value}px`);
3577
+ });
3578
+ el.style.setProperty("--mushi-safe-area", this.config.respectSafeArea ? "1" : "0");
3249
3579
  }
3250
- if (!this.lastReportId) {
3251
- return `
3252
- <div class="mushi-success-receipt" role="status">
3253
- <div class="mushi-success-receipt-row">
3254
- <span class="mushi-success-receipt-spinner" aria-hidden="true"></span>
3255
- <span class="mushi-success-receipt-hint">Delivering to the team\u2026</span>
3256
- </div>
3257
- ${this.renderSlaLine()}
3258
- </div>
3259
- `;
3580
+ const isTopAnchored = anchor?.top !== void 0 || this.config.position?.startsWith("top") || !this.config.position && !anchor?.bottom;
3581
+ if (isTopAnchored) {
3582
+ const avoidPx = this.computeAvoidTopPx();
3583
+ if (avoidPx !== null) {
3584
+ el.style.setProperty("--mushi-top", `${avoidPx}px`);
3585
+ }
3586
+ }
3587
+ }
3588
+ // ─── Draggable FAB ──────────────────────────────────────────────────────────
3589
+ /** Storage key for the FAB position, scoped to projectId when available. */
3590
+ fabStorageKey() {
3591
+ const id = this.config["projectId"] ?? "";
3592
+ return `mushi_fab_pos${id ? `_${id}` : ""}`;
3593
+ }
3594
+ /** Move the FAB to the given translated offset (relative to the inset origin),
3595
+ * clamping inside viewport safe area, and optionally snap to nearest edge.
3596
+ *
3597
+ * The FAB's CSS anchor can be any corner (bottom-right, bottom-left, …) so we
3598
+ * must derive the *base* position (CSS anchor with zero drag offset) to compute
3599
+ * correct clamp bounds and snap targets. We do this by subtracting the
3600
+ * already-applied drag offset from the live getBoundingClientRect() value. */
3601
+ moveFab(trigger, x, y, snap) {
3602
+ const axis = (() => {
3603
+ const d2 = this.config.draggable;
3604
+ if (!d2) return "both";
3605
+ return typeof d2 === "object" ? d2.axis ?? "both" : "both";
3606
+ })();
3607
+ const W = window.innerWidth;
3608
+ const H = window.innerHeight;
3609
+ const btnW = trigger.offsetWidth || 52;
3610
+ const btnH = trigger.offsetHeight || 52;
3611
+ const safeL = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-left") || "0") || 0;
3612
+ const safeR = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-right") || "0") || 0;
3613
+ const safeT = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-top") || "0") || 0;
3614
+ const safeB = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--sai-bottom") || "0") || 0;
3615
+ const margin = 8;
3616
+ const rect = trigger.getBoundingClientRect();
3617
+ const prevDragX = this.fabPos?.x ?? 0;
3618
+ const prevDragY = this.fabPos?.y ?? 0;
3619
+ const baseLeft = rect.left - prevDragX;
3620
+ const baseTop = rect.top - prevDragY;
3621
+ const minX = safeL + margin - baseLeft;
3622
+ const maxX = W - safeR - margin - btnW - baseLeft;
3623
+ const minY = safeT + margin - baseTop;
3624
+ const maxY = H - safeB - margin - btnH - baseTop;
3625
+ const newX = axis === "y" ? 0 : Math.max(minX, Math.min(maxX, x));
3626
+ const newY = axis === "x" ? 0 : Math.max(minY, Math.min(maxY, y));
3627
+ let finalX = newX;
3628
+ if (snap) {
3629
+ const d2 = this.config.draggable;
3630
+ const shouldSnap = d2 === true || typeof d2 === "object" && (d2.snapToEdge ?? true);
3631
+ if (shouldSnap && axis !== "y") {
3632
+ const center = rect.left + btnW / 2;
3633
+ finalX = center < W / 2 ? safeL + margin - baseLeft : W - safeR - margin - btnW - baseLeft;
3634
+ }
3635
+ }
3636
+ this.fabPos = { x: finalX, y: newY };
3637
+ trigger.style.setProperty("--mushi-drag-x", `${finalX}px`);
3638
+ trigger.style.setProperty("--mushi-drag-y", `${newY}px`);
3639
+ trigger.style.setProperty("--mushi-drag-active", "1");
3640
+ const d = this.config.draggable;
3641
+ const shouldPersist = d === true || typeof d === "object" && (d.persist ?? true);
3642
+ if (shouldPersist) {
3643
+ try {
3644
+ localStorage.setItem(this.fabStorageKey(), JSON.stringify(this.fabPos));
3645
+ } catch {
3646
+ }
3260
3647
  }
3261
- const idShort = `#${this.lastReportId.slice(0, 8)}`;
3262
- const dashboard = (this.config.dashboardUrl ?? "").replace(/\/$/, "");
3263
- const trackHref = dashboard ? `${dashboard}/reports/${encodeURIComponent(this.lastReportId)}` : "";
3264
- return `
3265
- <div class="mushi-success-receipt" role="status">
3266
- <div class="mushi-success-receipt-row">
3267
- <span class="mushi-success-receipt-label">Receipt</span>
3268
- <button
3269
- type="button"
3270
- class="mushi-success-receipt-id"
3271
- data-action="copy-report-id"
3272
- data-copy-id="${escapeHtml(this.lastReportId)}"
3273
- title="Copy report id ${escapeHtml(this.lastReportId)}"
3274
- aria-label="Copy report id ${escapeHtml(this.lastReportId)}"
3275
- >${escapeHtml(idShort)}<span class="mushi-success-receipt-copy" aria-hidden="true">\u2398</span></button>
3276
- </div>
3277
- ${trackHref ? `
3278
- <a
3279
- class="mushi-success-receipt-track"
3280
- href="${escapeHtml(trackHref)}"
3281
- target="_blank"
3282
- rel="noopener noreferrer"
3283
- >Track on Mushi <span aria-hidden="true">\u2197</span></a>
3284
- ` : ""}
3285
- ${this.renderSlaLine()}
3286
- </div>
3287
- `;
3288
3648
  }
3289
- renderSlaLine() {
3290
- const sla = (this.config.responseSlaLabel ?? "").trim();
3291
- if (sla) {
3292
- return `<div class="mushi-success-sla">${escapeHtml(sla)}</div>`;
3649
+ /** Load previously persisted FAB position. */
3650
+ loadFabPos() {
3651
+ const d = this.config.draggable;
3652
+ if (!d) return;
3653
+ const shouldPersist = d === true || typeof d === "object" && (d.persist ?? true);
3654
+ if (!shouldPersist) return;
3655
+ try {
3656
+ const raw = localStorage.getItem(this.fabStorageKey());
3657
+ if (raw) {
3658
+ const parsed = JSON.parse(raw);
3659
+ if (typeof parsed?.x === "number" && typeof parsed?.y === "number") {
3660
+ this.fabPos = parsed;
3661
+ }
3662
+ }
3663
+ } catch {
3293
3664
  }
3294
- return `<div class="mushi-success-sla mushi-success-sla-default">A human will look at this within a working day.</div>`;
3665
+ }
3666
+ /** Attach Pointer Events-based drag to the trigger element. */
3667
+ attachDragHandlers(trigger) {
3668
+ if (this.fabPos === null) this.loadFabPos();
3669
+ let startX = 0, startY = 0;
3670
+ let originX = 0, originY = 0;
3671
+ let dragging = false;
3672
+ let moved = false;
3673
+ const onPointerDown = (e) => {
3674
+ if (e.button !== 0 && e.pointerType !== "touch") return;
3675
+ trigger.setPointerCapture(e.pointerId);
3676
+ startX = e.clientX;
3677
+ startY = e.clientY;
3678
+ const cur = this.fabPos ?? { x: 0, y: 0 };
3679
+ originX = cur.x;
3680
+ originY = cur.y;
3681
+ dragging = true;
3682
+ moved = false;
3683
+ };
3684
+ const DRAG_THRESHOLD = 6;
3685
+ const onPointerMove = (e) => {
3686
+ if (!dragging) return;
3687
+ const dx = e.clientX - startX;
3688
+ const dy = e.clientY - startY;
3689
+ if (!moved && Math.hypot(dx, dy) > DRAG_THRESHOLD) {
3690
+ moved = true;
3691
+ trigger.classList.add("dragging");
3692
+ trigger.setAttribute("aria-grabbed", "true");
3693
+ }
3694
+ if (moved) {
3695
+ e.preventDefault();
3696
+ this.moveFab(trigger, originX + dx, originY + dy, false);
3697
+ }
3698
+ };
3699
+ const onPointerUp = (e) => {
3700
+ if (!dragging) return;
3701
+ dragging = false;
3702
+ trigger.classList.remove("dragging");
3703
+ trigger.removeAttribute("aria-grabbed");
3704
+ if (moved) {
3705
+ const dx = e.clientX - startX;
3706
+ const dy = e.clientY - startY;
3707
+ this.moveFab(trigger, originX + dx, originY + dy, true);
3708
+ const suppressClick = (ev) => {
3709
+ ev.stopImmediatePropagation();
3710
+ trigger.removeEventListener("click", suppressClick, { capture: true });
3711
+ };
3712
+ trigger.addEventListener("click", suppressClick, { capture: true });
3713
+ }
3714
+ moved = false;
3715
+ };
3716
+ trigger.addEventListener("pointerdown", onPointerDown);
3717
+ trigger.addEventListener("pointermove", onPointerMove);
3718
+ trigger.addEventListener("pointerup", onPointerUp);
3719
+ trigger.addEventListener("pointercancel", onPointerUp);
3720
+ }
3721
+ // ─── Keyboard / visualViewport ──────────────────────────────────────────────
3722
+ /** Lift the panel above the software keyboard using visualViewport. */
3723
+ attachViewportHandlers(panel) {
3724
+ this.teardownViewportHandlers();
3725
+ const vv = window.visualViewport;
3726
+ if (!vv) return;
3727
+ const update = () => {
3728
+ const keyboardInset = window.innerHeight - vv.height - vv.offsetTop;
3729
+ if (keyboardInset > 50) {
3730
+ panel.style.setProperty("--mushi-keyboard-inset", `${Math.round(keyboardInset)}px`);
3731
+ panel.classList.add("keyboard-open");
3732
+ const ta = panel.querySelector('textarea, input[type="text"]');
3733
+ ta?.scrollIntoView({ block: "nearest", behavior: "smooth" });
3734
+ } else {
3735
+ panel.style.setProperty("--mushi-keyboard-inset", "0px");
3736
+ panel.classList.remove("keyboard-open");
3737
+ }
3738
+ };
3739
+ vv.addEventListener("resize", update, { passive: true });
3740
+ vv.addEventListener("scroll", update, { passive: true });
3741
+ const onFocus = () => requestAnimationFrame(update);
3742
+ panel.addEventListener("focusin", onFocus);
3743
+ this.vvCleanup = () => {
3744
+ vv.removeEventListener("resize", update);
3745
+ vv.removeEventListener("scroll", update);
3746
+ panel.removeEventListener("focusin", onFocus);
3747
+ };
3748
+ }
3749
+ teardownViewportHandlers() {
3750
+ this.vvCleanup?.();
3751
+ this.vvCleanup = null;
3295
3752
  }
3296
3753
  /**
3297
- * Reciprocity footer on the success step: closes the feedback loop by
3298
- * attributing where the report goes, sets a response expectation, and
3299
- * reinforces the "beta tester" identity (Peak-End Rule — the last thing
3300
- * the user sees shapes their entire impression of the interaction).
3754
+ * Minimum description length, lowered for CJK locales where each character
3755
+ * carries more meaning. Used by both the view layer (via renderCtx) and the
3756
+ * details-step input validation in attachHandlers.
3301
3757
  */
3302
- renderBetaSuccessFooter() {
3303
- const beta = this.config.betaMode;
3304
- const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
3305
- const appName = escapeHtml(beta.appName ?? "the team");
3306
- return `
3307
- <div class="mushi-beta-success-footer" role="note" aria-label="Beta feedback acknowledgement">
3308
- ${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>`}
3309
- <div class="mushi-beta-success-line mushi-beta-success-dim">We aim to review within 48h \xB7 thank you for helping build this</div>
3310
- </div>
3311
- `;
3758
+ effectiveMinLength() {
3759
+ const base = this.config.minDescriptionLength ?? 20;
3760
+ const lang = this.config.locale === "auto" ? typeof navigator !== "undefined" ? navigator.language ?? "" : "" : this.config.locale ?? "";
3761
+ const isCjk = /^(ja|zh|ko)/i.test(lang);
3762
+ return isCjk ? Math.max(4, Math.floor(base / 2)) : base;
3312
3763
  }
3764
+ /** Tier accent colour for the rewards UI. */
3313
3765
  tierColor(slug) {
3314
3766
  const colors = {
3315
3767
  free: "#6b7280",
@@ -3319,62 +3771,57 @@ var MushiWidget = class _MushiWidget {
3319
3771
  };
3320
3772
  return colors[slug] ?? "#6c47ff";
3321
3773
  }
3322
- /** Compact rewards nudge rendered at the bottom of the category-step body. */
3323
- renderRewardsNudge() {
3324
- const { tier, nextTier, totalPoints, pointsForReport } = this.rewardsState;
3325
- const tierName = tier?.displayName ?? "Free";
3326
- const tierSlug = tier?.slug ?? "free";
3327
- const color = this.tierColor(tierSlug);
3328
- let pct = 100;
3329
- let nextLabel = "";
3330
- if (nextTier) {
3331
- const base = tier?.pointsThreshold ?? 0;
3332
- const ceiling = nextTier.pointsThreshold;
3333
- pct = ceiling > base ? Math.round(Math.min(1, (totalPoints - base) / (ceiling - base)) * 100) : 100;
3334
- const remaining = Math.max(0, ceiling - totalPoints);
3335
- nextLabel = `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}`;
3336
- }
3337
- return `
3338
- <div class="mushi-rewards-nudge" aria-label="Rewards progress">
3339
- <div class="mushi-rewards-row">
3340
- <span class="mushi-tier-pip" style="background:${color}" aria-hidden="true"></span>
3341
- <span class="mushi-rewards-tier-name">${escapeHtml(tierName)}</span>
3342
- <span class="mushi-rewards-pts-count">${totalPoints.toLocaleString()} pts</span>
3343
- <span class="mushi-rewards-pts-earn">+${pointsForReport} pts for a report</span>
3344
- </div>
3345
- ${nextTier ? `
3346
- <div class="mushi-tier-bar-track" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="Progress to ${escapeHtml(nextTier.displayName)}">
3347
- <div class="mushi-tier-bar-fill" style="width:${pct}%"></div>
3348
- </div>
3349
- <div class="mushi-rewards-next-label">${nextLabel}</div>
3350
- ` : ""}
3351
- </div>
3352
- `;
3353
- }
3354
- /** Points earned + tier progress shown on the success step. */
3355
- renderSuccessRewards() {
3356
- const { tier, nextTier, totalPoints, pointsForReport } = this.rewardsState;
3357
- const projected = totalPoints + pointsForReport;
3358
- let pctAfter = 100;
3359
- let nextLabel = "";
3360
- if (nextTier) {
3361
- const base = tier?.pointsThreshold ?? 0;
3362
- const ceiling = nextTier.pointsThreshold;
3363
- pctAfter = ceiling > base ? Math.round(Math.min(1, (projected - base) / (ceiling - base)) * 100) : 100;
3364
- const remaining = Math.max(0, ceiling - projected);
3365
- nextLabel = remaining > 0 ? `${remaining.toLocaleString()} pts to ${escapeHtml(nextTier.displayName)}` : `\u{1F389} ${escapeHtml(nextTier.displayName)} reached!`;
3366
- }
3367
- return `
3368
- <div class="mushi-success-rewards">
3369
- <div class="mushi-success-pts-award">+${pointsForReport} pts</div>
3370
- ${nextTier ? `
3371
- <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)}">
3372
- <div class="mushi-tier-bar-fill" style="width:${pctAfter}%"></div>
3373
- </div>
3374
- <div class="mushi-rewards-next-label">${nextLabel}</div>
3375
- ` : ""}
3376
- </div>
3377
- `;
3774
+ /**
3775
+ * Build the read-only snapshot + bound helper closures the stateless view
3776
+ * layer (widget-render.ts) renders from. Rebuilt once per render() pass so
3777
+ * the HTML always reflects current state.
3778
+ */
3779
+ renderCtx() {
3780
+ return {
3781
+ config: this.config,
3782
+ rewardsState: this.rewardsState,
3783
+ lastReportId: this.lastReportId,
3784
+ reporterLoading: this.reporterLoading,
3785
+ locale: this.locale,
3786
+ testerReputation: this.testerReputation,
3787
+ testerInfo: this.testerInfo,
3788
+ screenshotCapturing: this.screenshotCapturing,
3789
+ screenshotAttached: this.screenshotAttached,
3790
+ reporterError: this.reporterError,
3791
+ magicLinkError: this.magicLinkError,
3792
+ elementCapturing: this.elementCapturing,
3793
+ submitting: this.submitting,
3794
+ sdkFreshness: this.sdkFreshness,
3795
+ screenshotError: this.screenshotError,
3796
+ reporterReports: this.reporterReports,
3797
+ magicLinkSending: this.magicLinkSending,
3798
+ magicLinkEmail: this.magicLinkEmail,
3799
+ globalLeaderboardLoading: this.globalLeaderboardLoading,
3800
+ globalLeaderboard: this.globalLeaderboard,
3801
+ elementSelected: this.elementSelected,
3802
+ crossAppLoading: this.crossAppLoading,
3803
+ callbacks: this.callbacks,
3804
+ testerJwt: this.testerJwt,
3805
+ submittedAt: this.submittedAt,
3806
+ step: this.step,
3807
+ selectedReportId: this.selectedReportId,
3808
+ selectedCategory: this.selectedCategory,
3809
+ sdkVersion: this.sdkVersion,
3810
+ reporterComments: this.reporterComments,
3811
+ magicLinkSent: this.magicLinkSent,
3812
+ leaderboardLoading: this.leaderboardLoading,
3813
+ leaderboardEntries: this.leaderboardEntries,
3814
+ lastSubmitQueuedOffline: this.lastSubmitQueuedOffline,
3815
+ featureBoard: this.featureBoard,
3816
+ crossAppReports: this.crossAppReports,
3817
+ allowScreenshotRemove: this.allowScreenshotRemove,
3818
+ unreadCount: () => this.unreadCount(),
3819
+ tierColor: (slug) => this.tierColor(slug),
3820
+ resolveCustomCategory: (id) => this.resolveCustomCategory(id),
3821
+ effectiveMinLength: () => this.effectiveMinLength(),
3822
+ categoryLabel: (id) => this.categoryLabel(id),
3823
+ categoryIcon: (id) => this.categoryIcon(id)
3824
+ };
3378
3825
  }
3379
3826
  attachHandlers(panel) {
3380
3827
  const t = this.locale;
@@ -3433,6 +3880,56 @@ var MushiWidget = class _MushiWidget {
3433
3880
  panel.querySelector('[data-action="open-leaderboard"]')?.addEventListener("click", () => {
3434
3881
  this.step = "leaderboard";
3435
3882
  this.callbacks.onLeaderboardOpen?.();
3883
+ this.callbacks.onGlobalLeaderboardOpen?.();
3884
+ this.render();
3885
+ });
3886
+ panel.querySelector('[data-action="open-account"]')?.addEventListener("click", () => {
3887
+ this.step = "account";
3888
+ this.render();
3889
+ });
3890
+ panel.querySelector('[data-action="open-cross-app-reports"]')?.addEventListener("click", () => {
3891
+ this.step = "cross-app-reports";
3892
+ this.crossAppLoading = true;
3893
+ this.crossAppReports = null;
3894
+ this.render();
3895
+ if (this.callbacks.onCrossAppReportsOpen) {
3896
+ this.callbacks.onCrossAppReportsOpen();
3897
+ } else {
3898
+ this.crossAppLoading = false;
3899
+ this.crossAppReports = [];
3900
+ this.render();
3901
+ }
3902
+ });
3903
+ panel.querySelector('[data-action="open-global-leaderboard"]')?.addEventListener("click", () => {
3904
+ this.step = "leaderboard";
3905
+ this.globalLeaderboard = null;
3906
+ this.globalLeaderboardLoading = true;
3907
+ this.render();
3908
+ if (this.callbacks.onGlobalLeaderboardOpen) {
3909
+ this.callbacks.onGlobalLeaderboardOpen();
3910
+ } else {
3911
+ this.globalLeaderboardLoading = false;
3912
+ this.globalLeaderboard = [];
3913
+ this.render();
3914
+ }
3915
+ });
3916
+ panel.querySelector('[data-action="send-magic-link"]')?.addEventListener("click", () => {
3917
+ void this.handleMagicLinkSend(panel);
3918
+ });
3919
+ panel.querySelector('[data-action="resend-magic-link"]')?.addEventListener("click", () => {
3920
+ this.magicLinkSent = false;
3921
+ this.magicLinkError = "";
3922
+ this.render();
3923
+ });
3924
+ panel.querySelector('[data-action="sign-out-tester"]')?.addEventListener("click", () => {
3925
+ this.testerJwt = null;
3926
+ this.testerInfo = null;
3927
+ this.testerReputation = null;
3928
+ this.crossAppReports = null;
3929
+ this.magicLinkSent = false;
3930
+ this.magicLinkEmail = "";
3931
+ this.step = "category";
3932
+ this.callbacks.onTesterSignOut?.();
3436
3933
  this.render();
3437
3934
  });
3438
3935
  panel.querySelector('[data-action="reporter-reply"]')?.addEventListener("click", () => {
@@ -3718,6 +4215,30 @@ var MushiWidget = class _MushiWidget {
3718
4215
  this.render();
3719
4216
  }
3720
4217
  }
4218
+ /* ── Community: magic-link sign-in ───────────────────────────────── */
4219
+ async handleMagicLinkSend(panel) {
4220
+ if (this.magicLinkSending) return;
4221
+ const emailInput = panel.querySelector('[data-role="magic-link-email"]');
4222
+ const email = (emailInput?.value ?? this.magicLinkEmail).trim();
4223
+ if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
4224
+ this.magicLinkError = "Please enter a valid email address.";
4225
+ this.render();
4226
+ return;
4227
+ }
4228
+ this.magicLinkEmail = email;
4229
+ this.magicLinkError = "";
4230
+ this.magicLinkSending = true;
4231
+ this.render();
4232
+ try {
4233
+ await this.callbacks.onMushiSignIn?.(email);
4234
+ this.magicLinkSent = true;
4235
+ } catch (err) {
4236
+ this.magicLinkError = err instanceof Error ? err.message : "Could not send sign-in link. Try again.";
4237
+ } finally {
4238
+ this.magicLinkSending = false;
4239
+ this.render();
4240
+ }
4241
+ }
3721
4242
  /* ── Marketing / Playwright recorder (debug GIF capture) ─────────── */
3722
4243
  getRecorderStep() {
3723
4244
  return this.step;
@@ -5800,10 +6321,6 @@ function createProactiveManager(config = {}) {
5800
6321
  return { shouldShow, recordDismissal, recordSubmission, reset };
5801
6322
  }
5802
6323
 
5803
- // src/version.ts
5804
- var MUSHI_SDK_PACKAGE = "@mushi-mushi/web";
5805
- var MUSHI_SDK_VERSION = "1.13.0" ;
5806
-
5807
6324
  // src/mushi.ts
5808
6325
  var instance = null;
5809
6326
  var Mushi = class {
@@ -5884,6 +6401,42 @@ function createInstance(config) {
5884
6401
  let replayCap = null;
5885
6402
  let replayGeneration = 0;
5886
6403
  let widget;
6404
+ const TESTER_JWT_KEY = `mushi:tester-jwt:${bootstrapConfig.projectId}`;
6405
+ function readTesterJwt() {
6406
+ try {
6407
+ return typeof localStorage !== "undefined" ? localStorage.getItem(TESTER_JWT_KEY) : null;
6408
+ } catch {
6409
+ return null;
6410
+ }
6411
+ }
6412
+ function clearTesterJwt() {
6413
+ try {
6414
+ if (typeof localStorage !== "undefined") localStorage.removeItem(TESTER_JWT_KEY);
6415
+ } catch {
6416
+ }
6417
+ }
6418
+ async function loadTesterSession(jwt) {
6419
+ const statusResult = await apiClient2.getTesterStatus(jwt);
6420
+ if (!statusResult.ok || !statusResult.data) {
6421
+ clearTesterJwt();
6422
+ return;
6423
+ }
6424
+ const status = statusResult.data;
6425
+ if (!status.is_tester) {
6426
+ clearTesterJwt();
6427
+ return;
6428
+ }
6429
+ widget.setTesterSession(jwt, {
6430
+ id: jwt.substring(0, 16),
6431
+ public_handle: status.public_handle ?? null,
6432
+ display_name: status.display_name ?? null
6433
+ });
6434
+ const repResult = await apiClient2.getMyReputation(jwt);
6435
+ if (repResult.ok && repResult.data) {
6436
+ const repData = repResult.data;
6437
+ if (repData.reputation) widget.setTesterReputation(repData.reputation);
6438
+ }
6439
+ }
5887
6440
  function syncCaptureModules() {
5888
6441
  if (activeConfig.capture?.console !== false) {
5889
6442
  consoleCap ??= createConsoleCapture();
@@ -6177,6 +6730,56 @@ function createInstance(config) {
6177
6730
  void fetchLeaderboard(10).then((entries) => {
6178
6731
  widget.setLeaderboard(entries, false);
6179
6732
  });
6733
+ },
6734
+ // ── Community callbacks ──────────────────────────────────────────────
6735
+ async onMushiSignIn(email) {
6736
+ const res = await apiClient2.sendMagicLink(email);
6737
+ if (!res.ok) throw new Error(res.error?.message ?? "Could not send sign-in link");
6738
+ return { ok: true };
6739
+ },
6740
+ async onGlobalLeaderboardOpen() {
6741
+ widget.setGlobalLeaderboard(null, true);
6742
+ try {
6743
+ const jwt = readTesterJwt();
6744
+ const res = await apiClient2.getPublicLeaderboard(50);
6745
+ const rawEntries = res.ok ? res.data?.leaderboard ?? [] : [];
6746
+ const entries = rawEntries.map((e) => ({
6747
+ tester_id: e.tester_id,
6748
+ rank: e.rank,
6749
+ public_handle: e.public_handle,
6750
+ display_name: e.display_name,
6751
+ points_30d: e.points_30d,
6752
+ total_points: e.total_points ?? 0,
6753
+ badge: e.badge_slug
6754
+ }));
6755
+ widget.setGlobalLeaderboard(entries, false);
6756
+ if (jwt) {
6757
+ const repRes = await apiClient2.getMyReputation(jwt);
6758
+ if (repRes.ok && repRes.data) {
6759
+ const repData = repRes.data;
6760
+ if (repData.reputation) widget.setTesterReputation(repData.reputation);
6761
+ }
6762
+ }
6763
+ } catch {
6764
+ widget.setGlobalLeaderboard([], false);
6765
+ }
6766
+ },
6767
+ async onCrossAppReportsOpen() {
6768
+ const jwt = readTesterJwt();
6769
+ if (!jwt) {
6770
+ widget.setCrossAppReports([], false);
6771
+ return;
6772
+ }
6773
+ try {
6774
+ const res = await apiClient2.getCrossAppReports(jwt);
6775
+ const reports = res.ok ? res.data?.reports ?? [] : [];
6776
+ widget.setCrossAppReports(reports, false);
6777
+ } catch {
6778
+ widget.setCrossAppReports([], false);
6779
+ }
6780
+ },
6781
+ onTesterSignOut() {
6782
+ clearTesterJwt();
6180
6783
  }
6181
6784
  }, MUSHI_SDK_VERSION);
6182
6785
  syncCaptureModules();
@@ -6187,6 +6790,10 @@ function createInstance(config) {
6187
6790
  widget.mount();
6188
6791
  }
6189
6792
  }
6793
+ const cachedJwt = readTesterJwt();
6794
+ if (cachedJwt) {
6795
+ void loadTesterSession(cachedJwt).catch(() => clearTesterJwt());
6796
+ }
6190
6797
  let proactiveTriggers = null;
6191
6798
  let proactiveManager = null;
6192
6799
  const proactiveCfg = activeConfig.proactive;