@usero/sdk 0.2.1 → 0.3.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/README.md +86 -0
- package/dist/plugins/session-replay.cjs +178 -0
- package/dist/plugins/session-replay.cjs.map +1 -0
- package/dist/plugins/session-replay.d.cts +75 -0
- package/dist/plugins/session-replay.d.ts +75 -0
- package/dist/plugins/session-replay.js +175 -0
- package/dist/plugins/session-replay.js.map +1 -0
- package/dist/react.cjs +122 -19
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +23 -0
- package/dist/react.d.ts +23 -0
- package/dist/react.js +122 -19
- package/dist/react.js.map +1 -1
- package/dist/rrweb-IQA3KVSA.js +17065 -0
- package/dist/rrweb-IQA3KVSA.js.map +1 -0
- package/dist/rrweb-SDFFFL7O.cjs +17077 -0
- package/dist/rrweb-SDFFFL7O.cjs.map +1 -0
- package/dist/usero.iife.js +43 -36
- package/dist/usero.iife.js.map +1 -1
- package/dist/vanilla.cjs +123 -19
- package/dist/vanilla.cjs.map +1 -1
- package/dist/vanilla.d.cts +25 -1
- package/dist/vanilla.d.ts +25 -1
- package/dist/vanilla.js +123 -20
- package/dist/vanilla.js.map +1 -1
- package/package.json +9 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/session-replay.ts"],"names":[],"mappings":";AA4FA,IAAM,eAAA,GAEF;AAAA,EACH,aAAA,EAAe,EAAA;AAAA,EACf,YAAA,EAAc,CAAA;AAAA,EACd,UAAA,EAAY,CAAA;AAAA,EACZ,QAAA,EAAU,EAAE,SAAA,EAAW,EAAA,EAAI,QAAQ,GAAA,EAAI;AAAA,EACvC,aAAA,EAAe,IAAA;AAAA,EACf,gBAAA,EAAkB,mBAAA;AAAA,EAClB,gBAAA,EAAkB,IAAA;AAAA,EAClB,aAAA,EAAe;AAChB,CAAA;AAEA,SAAS,cAAA,CAAe,MAAA,EAAsB,aAAA,EAAuB,GAAA,EA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UAAA,KAAA,CAAM,aAAA,EAAc;AAAA,QACrB,SAAS,GAAA,EAAK;AACb,UAAA,GAAA,CAAI,MAAA,CAAO,IAAA,CAAK,kBAAA,EAAoB,GAAG,CAAA;AAAA,QACxC;AAAA,MACD;AACA,MAAA,KAAA,CAAM,OAAO,MAAA,GAAS,CAAA;AAAA,IACvB;AAAA,GACD;AACD;AAGO,IAAM,QAAA,GAAW,EAAE,cAAA,EAAgB,UAAA,EAAY,aAAA","file":"session-replay.js","sourcesContent":["// Session replay plugin for the Usero widget.\n//\n// Lazy-loads rrweb the first time it's actually needed and keeps a rolling\n// in-memory buffer of the last `bufferSeconds` of events. On feedback\n// submit, the buffer is gzipped via the native CompressionStream API and\n// attached as `replayEvents` (base64 string) on the outgoing payload.\n//\n// Bundle hygiene is the whole point of this plugin existing as its own\n// subpath export. Importing this module pulls in the small wrapper below;\n// the heavy rrweb dependency only loads at runtime via dynamic `import()`.\n//\n// Privacy defaults err on the side of safety: all <input>/<textarea> values\n// are masked, anything tagged `data-usero-mask` is masked too, and inline\n// styles are inlined so we never leak external stylesheet URLs.\n\nimport type { UseroPlugin, PluginContext } from '../plugin'\nimport type { FeedbackSubmission } from '../types'\n\n// We deliberately avoid importing rrweb's types at the top level — that\n// would force consumers to install rrweb as a peer dep and would also pull\n// the type declarations into our published .d.ts files. Plugin internals\n// use a minimal local shape and rely on rrweb's runtime API only.\n\n// rrweb event sample-rate map. Keys match rrweb's `sampling` option. See\n// https://github.com/rrweb-io/rrweb/blob/master/guide.md#options for the\n// full list. We expose the two that matter most (mousemove, scroll).\nexport interface ReplaySampling {\n\t// Capture a mousemove event at most every N ms (default 50).\n\tmousemove?: number\n\t// Capture a scroll event at most every N ms (default 100).\n\tscroll?: number\n\t// Capture a media-interaction event at most every N ms.\n\tmedia?: number\n\t// Capture an input event at most every N ms, or 'last' to keep only the\n\t// final input value per element.\n\tinput?: number | 'last'\n}\n\nexport interface SessionReplayOptions {\n\t// Length of the rolling buffer in seconds. Older events are evicted as\n\t// new ones arrive. Default 30.\n\tbufferSeconds?: number\n\t// Wait this many ms after page load before loading rrweb and starting\n\t// to record. If the user navigates away before this elapses, rrweb is\n\t// never loaded. Default 0 (start immediately).\n\tstartAfterMs?: number\n\t// Probability (0..1) that this session records at all. Decided once at\n\t// init via Math.random(). Sessions that lose the dice roll never load\n\t// rrweb. Default 1 (always record).\n\tsampleRate?: number\n\t// rrweb sampling rates per event type. See ReplaySampling above.\n\tsampling?: ReplaySampling\n\t// Mask all <input>/<textarea> values in the recording. Default true.\n\tmaskAllInputs?: boolean\n\t// CSS selector for nodes whose text content should be masked. Default\n\t// `[data-usero-mask]`. Pass an empty string to disable selector masking.\n\tmaskTextSelector?: string\n\t// Inline external stylesheets into the recording so the replay viewer\n\t// renders correctly without network access. Default true.\n\tinlineStylesheet?: boolean\n\t// Block (entirely skip) DOM subtrees matching this selector. Default\n\t// `[data-usero-block]`.\n\tblockSelector?: string\n}\n\ninterface RrwebEvent {\n\ttype: number\n\tdata: unknown\n\ttimestamp: number\n}\n\ninterface RrwebRecordOptions {\n\temit: (event: RrwebEvent) => void\n\tmaskAllInputs?: boolean\n\tmaskTextSelector?: string\n\tinlineStylesheet?: boolean\n\tblockSelector?: string\n\tsampling?: ReplaySampling\n}\n\ntype RrwebRecord = (opts: RrwebRecordOptions) => () => void\n\ninterface ReplayStore {\n\tevents: RrwebEvent[]\n\tstopRecording: (() => void) | null\n\tstartTimer: ReturnType<typeof setTimeout> | null\n\tpageHideHandler: (() => void) | null\n\tloadInProgress: boolean\n\tcancelled: boolean\n\toptions: Required<Omit<SessionReplayOptions, 'sampling'>> & { sampling: ReplaySampling }\n}\n\nconst DEFAULT_OPTIONS: Required<Omit<SessionReplayOptions, 'sampling'>> & {\n\tsampling: ReplaySampling\n} = {\n\tbufferSeconds: 30,\n\tstartAfterMs: 0,\n\tsampleRate: 1,\n\tsampling: { mousemove: 50, scroll: 100 },\n\tmaskAllInputs: true,\n\tmaskTextSelector: '[data-usero-mask]',\n\tinlineStylesheet: true,\n\tblockSelector: '[data-usero-block]',\n}\n\nfunction evictOldEvents(events: RrwebEvent[], bufferSeconds: number, now: number): void {\n\tif (events.length === 0) return\n\tconst cutoff = now - bufferSeconds * 1000\n\t// Events are appended in chronological order; find the first event\n\t// inside the window with a linear scan from the head and splice once.\n\tlet dropCount = 0\n\tfor (const e of events) {\n\t\tif (e.timestamp >= cutoff) break\n\t\tdropCount++\n\t}\n\tif (dropCount > 0) events.splice(0, dropCount)\n}\n\n// Convert a Uint8Array to base64 without bringing in a dependency. Chunked\n// to avoid blowing the call stack on large buffers.\nfunction uint8ToBase64(bytes: Uint8Array): string {\n\tlet binary = ''\n\tconst chunkSize = 0x8000\n\tfor (let i = 0; i < bytes.length; i += chunkSize) {\n\t\tconst chunk = bytes.subarray(i, i + chunkSize)\n\t\tbinary += String.fromCharCode.apply(null, Array.from(chunk))\n\t}\n\treturn typeof btoa === 'function' ? btoa(binary) : ''\n}\n\nasync function gzipString(input: string): Promise<string> {\n\tif (typeof CompressionStream === 'undefined') {\n\t\t// Browsers without CompressionStream (very old) fall back to raw\n\t\t// base64 of the JSON. The server can detect this by sniffing the\n\t\t// gzip magic bytes; cheaper than shipping a JS gzip lib.\n\t\tconst bytes = new TextEncoder().encode(input)\n\t\treturn uint8ToBase64(bytes)\n\t}\n\tconst stream = new Blob([input]).stream().pipeThrough(new CompressionStream('gzip'))\n\tconst compressed = await new Response(stream).arrayBuffer()\n\treturn uint8ToBase64(new Uint8Array(compressed))\n}\n\nasync function loadRrwebRecord(): Promise<RrwebRecord | null> {\n\ttry {\n\t\tconst mod: unknown = await import(/* webpackChunkName: \"rrweb\" */ 'rrweb')\n\t\tif (\n\t\t\tmod &&\n\t\t\ttypeof mod === 'object' &&\n\t\t\t'record' in mod &&\n\t\t\ttypeof (mod as { record: unknown }).record === 'function'\n\t\t) {\n\t\t\treturn (mod as { record: RrwebRecord }).record\n\t\t}\n\t\treturn null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction startRecording(store: ReplayStore, ctx: PluginContext): void {\n\tif (store.cancelled || store.stopRecording || store.loadInProgress) return\n\tstore.loadInProgress = true\n\tvoid loadRrwebRecord().then(record => {\n\t\tstore.loadInProgress = false\n\t\t// Window may have been torn down between the import resolving and\n\t\t// us getting here. Don't start a recording into a destroyed plugin.\n\t\tif (store.cancelled || !record) {\n\t\t\tif (!record) ctx.logger.warn('rrweb failed to load, replay disabled')\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tconst stop = record({\n\t\t\t\temit: event => {\n\t\t\t\t\tstore.events.push(event)\n\t\t\t\t\tevictOldEvents(store.events, store.options.bufferSeconds, event.timestamp)\n\t\t\t\t},\n\t\t\t\tmaskAllInputs: store.options.maskAllInputs,\n\t\t\t\tmaskTextSelector: store.options.maskTextSelector || undefined,\n\t\t\t\tinlineStylesheet: store.options.inlineStylesheet,\n\t\t\t\tblockSelector: store.options.blockSelector,\n\t\t\t\tsampling: store.options.sampling,\n\t\t\t})\n\t\t\tstore.stopRecording = stop\n\t\t} catch (err) {\n\t\t\tctx.logger.error('rrweb record() threw', err)\n\t\t}\n\t})\n}\n\nexport function sessionReplay(options: SessionReplayOptions = {}): UseroPlugin {\n\tconst merged = {\n\t\t...DEFAULT_OPTIONS,\n\t\t...options,\n\t\tsampling: { ...DEFAULT_OPTIONS.sampling, ...(options.sampling ?? {}) },\n\t}\n\n\treturn {\n\t\tname: 'session-replay',\n\t\tonInit(ctx) {\n\t\t\t// Lose the dice roll? Don't even prepare to load rrweb.\n\t\t\tif (merged.sampleRate < 1 && Math.random() >= merged.sampleRate) {\n\t\t\t\tctx.logger.debug('skipped by sampleRate')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (typeof window === 'undefined') return\n\n\t\t\tconst store: ReplayStore = {\n\t\t\t\tevents: [],\n\t\t\t\tstopRecording: null,\n\t\t\t\tstartTimer: null,\n\t\t\t\tpageHideHandler: null,\n\t\t\t\tloadInProgress: false,\n\t\t\t\tcancelled: false,\n\t\t\t\toptions: merged,\n\t\t\t}\n\t\t\tctx.setStore(store)\n\n\t\t\tconst begin = (): void => {\n\t\t\t\tif (store.startTimer) {\n\t\t\t\t\tclearTimeout(store.startTimer)\n\t\t\t\t\tstore.startTimer = null\n\t\t\t\t}\n\t\t\t\tif (store.pageHideHandler) {\n\t\t\t\t\twindow.removeEventListener('pagehide', store.pageHideHandler)\n\t\t\t\t\twindow.removeEventListener('beforeunload', store.pageHideHandler)\n\t\t\t\t\tstore.pageHideHandler = null\n\t\t\t\t}\n\t\t\t\tstartRecording(store, ctx)\n\t\t\t}\n\n\t\t\tif (merged.startAfterMs > 0) {\n\t\t\t\t// Engagement gate: only load rrweb if the user is still on the\n\t\t\t\t// page after `startAfterMs`. If they navigate away first we\n\t\t\t\t// cancel and never pull the heavy module.\n\t\t\t\tconst cancelOnExit = (): void => {\n\t\t\t\t\tstore.cancelled = true\n\t\t\t\t\tif (store.startTimer) {\n\t\t\t\t\t\tclearTimeout(store.startTimer)\n\t\t\t\t\t\tstore.startTimer = null\n\t\t\t\t\t}\n\t\t\t\t\tif (store.pageHideHandler) {\n\t\t\t\t\t\twindow.removeEventListener('pagehide', store.pageHideHandler)\n\t\t\t\t\t\twindow.removeEventListener('beforeunload', store.pageHideHandler)\n\t\t\t\t\t\tstore.pageHideHandler = null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstore.pageHideHandler = cancelOnExit\n\t\t\t\twindow.addEventListener('pagehide', cancelOnExit, { once: true })\n\t\t\t\twindow.addEventListener('beforeunload', cancelOnExit, { once: true })\n\t\t\t\tstore.startTimer = setTimeout(begin, merged.startAfterMs)\n\t\t\t} else {\n\t\t\t\tbegin()\n\t\t\t}\n\t\t},\n\t\tasync onFeedbackSubmit(ctx): Promise<Partial<FeedbackSubmission> | undefined> {\n\t\t\tconst store = ctx.getStore<ReplayStore>()\n\t\t\tif (!store || store.cancelled || store.events.length === 0) return undefined\n\t\t\t// Snapshot the current buffer so concurrent emits can't mutate\n\t\t\t// what we're serializing.\n\t\t\tconst snapshot = store.events.slice()\n\t\t\ttry {\n\t\t\t\tconst json = JSON.stringify(snapshot)\n\t\t\t\tconst replayEvents = await gzipString(json)\n\t\t\t\treturn { replayEvents }\n\t\t\t} catch (err) {\n\t\t\t\tctx.logger.error('failed to encode replay buffer', err)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t},\n\t\tonDestroy(ctx) {\n\t\t\tconst store = ctx.getStore<ReplayStore>()\n\t\t\tif (!store) return\n\t\t\tstore.cancelled = true\n\t\t\tif (store.startTimer) clearTimeout(store.startTimer)\n\t\t\tif (store.pageHideHandler) {\n\t\t\t\twindow.removeEventListener('pagehide', store.pageHideHandler)\n\t\t\t\twindow.removeEventListener('beforeunload', store.pageHideHandler)\n\t\t\t}\n\t\t\tif (store.stopRecording) {\n\t\t\t\ttry {\n\t\t\t\t\tstore.stopRecording()\n\t\t\t\t} catch (err) {\n\t\t\t\t\tctx.logger.warn('rrweb stop threw', err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tstore.events.length = 0\n\t\t},\n\t}\n}\n\n// Internal helper exports for testing only. Not part of the public API.\nexport const __test__ = { evictOldEvents, gzipString, uint8ToBase64 }\n"]}
|
package/dist/react.cjs
CHANGED
|
@@ -161,6 +161,25 @@ function getGradientEnd(color) {
|
|
|
161
161
|
return `#${[shiftedR, shiftedG, shiftedB].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
// src/plugin.ts
|
|
165
|
+
function createPluginLogger(name) {
|
|
166
|
+
const prefix = `[usero:${name}]`;
|
|
167
|
+
return {
|
|
168
|
+
debug: (...args) => {
|
|
169
|
+
if (typeof console !== "undefined") console.debug(prefix, ...args);
|
|
170
|
+
},
|
|
171
|
+
info: (...args) => {
|
|
172
|
+
if (typeof console !== "undefined") console.info(prefix, ...args);
|
|
173
|
+
},
|
|
174
|
+
warn: (...args) => {
|
|
175
|
+
if (typeof console !== "undefined") console.warn(prefix, ...args);
|
|
176
|
+
},
|
|
177
|
+
error: (...args) => {
|
|
178
|
+
if (typeof console !== "undefined") console.error(prefix, ...args);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
164
183
|
// src/validation.ts
|
|
165
184
|
function validateFeedbackSubmission(data) {
|
|
166
185
|
const errors = [];
|
|
@@ -341,10 +360,17 @@ var FEEDBACK_CSS = `
|
|
|
341
360
|
box-sizing: border-box;
|
|
342
361
|
}
|
|
343
362
|
|
|
363
|
+
.fb-toolrow {
|
|
364
|
+
display: flex;
|
|
365
|
+
align-items: center;
|
|
366
|
+
justify-content: space-between;
|
|
367
|
+
gap: 12px;
|
|
368
|
+
margin-bottom: 8px;
|
|
369
|
+
}
|
|
370
|
+
|
|
344
371
|
.fb-charcount {
|
|
345
372
|
font-size: 12px;
|
|
346
373
|
margin-left: auto;
|
|
347
|
-
margin-bottom: 6px;
|
|
348
374
|
text-align: right;
|
|
349
375
|
}
|
|
350
376
|
|
|
@@ -640,6 +666,21 @@ function escapeHtml(value) {
|
|
|
640
666
|
}
|
|
641
667
|
});
|
|
642
668
|
}
|
|
669
|
+
function mergePluginPatches(base, patches) {
|
|
670
|
+
let result = base;
|
|
671
|
+
for (const patch of patches) {
|
|
672
|
+
if (!patch || typeof patch !== "object") continue;
|
|
673
|
+
const { metadata: patchMetadata, ...rest } = patch;
|
|
674
|
+
result = { ...result, ...rest };
|
|
675
|
+
if (patchMetadata && typeof patchMetadata === "object") {
|
|
676
|
+
result.metadata = {
|
|
677
|
+
...result.metadata ?? {},
|
|
678
|
+
...patchMetadata
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return result;
|
|
683
|
+
}
|
|
643
684
|
function readStoredEmail() {
|
|
644
685
|
if (typeof window === "undefined") return "";
|
|
645
686
|
try {
|
|
@@ -664,7 +705,8 @@ function initUseroFeedbackWidget(props) {
|
|
|
664
705
|
close: () => {
|
|
665
706
|
},
|
|
666
707
|
update: () => {
|
|
667
|
-
}
|
|
708
|
+
},
|
|
709
|
+
whenReady: () => Promise.resolve()
|
|
668
710
|
};
|
|
669
711
|
}
|
|
670
712
|
const { clientId, baseUrl } = props;
|
|
@@ -679,7 +721,8 @@ function initUseroFeedbackWidget(props) {
|
|
|
679
721
|
close: () => {
|
|
680
722
|
},
|
|
681
723
|
update: () => {
|
|
682
|
-
}
|
|
724
|
+
},
|
|
725
|
+
whenReady: () => Promise.resolve()
|
|
683
726
|
};
|
|
684
727
|
}
|
|
685
728
|
let position = props.position ?? "right";
|
|
@@ -696,6 +739,34 @@ function initUseroFeedbackWidget(props) {
|
|
|
696
739
|
let onOpen = props.onOpen;
|
|
697
740
|
let onClose = props.onClose;
|
|
698
741
|
const apiClient = new FeedbackApiClient(baseUrl);
|
|
742
|
+
const pluginList = props.plugins ?? [];
|
|
743
|
+
const pluginStores = /* @__PURE__ */ new Map();
|
|
744
|
+
const pluginContexts = /* @__PURE__ */ new Map();
|
|
745
|
+
const initPromises = [];
|
|
746
|
+
for (const plugin of pluginList) {
|
|
747
|
+
const ctx = {
|
|
748
|
+
clientId,
|
|
749
|
+
baseUrl: baseUrl ?? DEFAULT_API_URL,
|
|
750
|
+
logger: createPluginLogger(plugin.name),
|
|
751
|
+
getStore: () => pluginStores.get(plugin.name),
|
|
752
|
+
setStore: (value) => {
|
|
753
|
+
pluginStores.set(plugin.name, value);
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
pluginContexts.set(plugin.name, ctx);
|
|
757
|
+
if (plugin.onInit) {
|
|
758
|
+
const settled = (async () => {
|
|
759
|
+
try {
|
|
760
|
+
await plugin.onInit?.(ctx);
|
|
761
|
+
} catch (err) {
|
|
762
|
+
ctx.logger.error("onInit threw", err);
|
|
763
|
+
}
|
|
764
|
+
})();
|
|
765
|
+
initPromises.push(settled);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
const readyPromise = initPromises.length === 0 ? Promise.resolve() : Promise.all(initPromises).then(() => {
|
|
769
|
+
});
|
|
699
770
|
let isOpen = false;
|
|
700
771
|
let selectedRating = void 0;
|
|
701
772
|
let comment = "";
|
|
@@ -814,8 +885,24 @@ function initUseroFeedbackWidget(props) {
|
|
|
814
885
|
setSubmitMessage({ type: "error", text: validation.errors.join(", ") });
|
|
815
886
|
return;
|
|
816
887
|
}
|
|
888
|
+
let enrichedSubmission = submission;
|
|
889
|
+
if (pluginList.length > 0) {
|
|
890
|
+
const patchPromises = pluginList.map(async (plugin) => {
|
|
891
|
+
if (!plugin.onFeedbackSubmit) return void 0;
|
|
892
|
+
const ctx = pluginContexts.get(plugin.name);
|
|
893
|
+
if (!ctx) return void 0;
|
|
894
|
+
try {
|
|
895
|
+
return await plugin.onFeedbackSubmit(ctx, submission);
|
|
896
|
+
} catch (err) {
|
|
897
|
+
ctx.logger.error("onFeedbackSubmit threw", err);
|
|
898
|
+
return void 0;
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
const patches = await Promise.all(patchPromises);
|
|
902
|
+
enrichedSubmission = mergePluginPatches(submission, patches);
|
|
903
|
+
}
|
|
817
904
|
try {
|
|
818
|
-
const response = await apiClient.submitFeedback(
|
|
905
|
+
const response = await apiClient.submitFeedback(enrichedSubmission);
|
|
819
906
|
if (response.success) {
|
|
820
907
|
if (shareEmail && userEmail) writeStoredEmail(userEmail);
|
|
821
908
|
onSubmit?.(feedbackData);
|
|
@@ -872,17 +959,26 @@ function initUseroFeedbackWidget(props) {
|
|
|
872
959
|
const cls = ["fb-ec", sel && "fb-ec--sel"].filter(Boolean).join(" ");
|
|
873
960
|
return `
|
|
874
961
|
<div class="${cls}" style="background:${bg}">
|
|
875
|
-
<button type="button" class="fb-eb" data-rating="${r}" role="radio" aria-checked="${sel}" aria-label="${r}: ${RATING_LABELS[r]}">
|
|
962
|
+
<button type="button" class="fb-eb" data-rating="${r}" role="radio" aria-checked="${sel}" aria-label="${r}: ${RATING_LABELS[r]}" style="color:${theme.text}">
|
|
876
963
|
<div class="fb-ei"><span role="img" aria-label="${RATING_LABELS[r]}">${EMOJI_MAP[r]}</span></div>
|
|
877
|
-
<div class="fb-el">${RATING_LABELS[r]}</div>
|
|
964
|
+
<div class="fb-el" style="color:${theme.text}">${RATING_LABELS[r]}</div>
|
|
878
965
|
</button>
|
|
879
966
|
</div>
|
|
880
967
|
`;
|
|
881
968
|
}).join("");
|
|
882
969
|
const messageHtml = submitMessage ? `<div class="fb-msg fb-msg--header ${submitMessage.type === "success" ? "fb-msg--ok" : "fb-msg--err"}">${submitMessage.type === "success" ? "\u2713" : "\u26A0"} ${escapeHtml(submitMessage.text)}</div>` : "";
|
|
883
|
-
const
|
|
970
|
+
const uploadBtnHtml = showScreenshotOption ? (() => {
|
|
884
971
|
const atMax = screenshots.length >= MAX_SCREENSHOTS;
|
|
885
972
|
const btnDisabled = isUploadingScreenshot || atMax;
|
|
973
|
+
return `
|
|
974
|
+
<input type="file" accept="image/*" data-role="screenshot-input" style="display:none;" aria-label="Choose screenshot" />
|
|
975
|
+
<button type="button" class="fb-upb ${btnDisabled ? "fb-upb--dis" : ""}" data-role="screenshot-pick" ${btnDisabled ? "disabled" : ""} style="border:1px solid ${theme.border};color:${theme.text};">
|
|
976
|
+
${isUploadingScreenshot ? '<span class="fb-ups"></span> Uploading...' : "\u{1F4F7} Add screenshot"}
|
|
977
|
+
</button>
|
|
978
|
+
`;
|
|
979
|
+
})() : "";
|
|
980
|
+
const uploadExtrasHtml = showScreenshotOption ? (() => {
|
|
981
|
+
const atMax = screenshots.length >= MAX_SCREENSHOTS;
|
|
886
982
|
const previewsHtml = screenshots.map(
|
|
887
983
|
(shot, i) => `
|
|
888
984
|
<div class="fb-sp">
|
|
@@ -893,16 +989,7 @@ function initUseroFeedbackWidget(props) {
|
|
|
893
989
|
).join("");
|
|
894
990
|
const errorHtml = screenshotError ? `<div class="fb-upe">\u26A0 ${escapeHtml(screenshotError)}</div>` : "";
|
|
895
991
|
const limitHtml = atMax ? `<div class="fb-sl">Max ${MAX_SCREENSHOTS}</div>` : "";
|
|
896
|
-
|
|
897
|
-
return `
|
|
898
|
-
<div class="fb-up">
|
|
899
|
-
<input type="file" accept="image/*" data-role="screenshot-input" style="display:none;" aria-label="Choose screenshot" />
|
|
900
|
-
<button type="button" class="fb-upb ${btnDisabled ? "fb-upb--dis" : ""}" data-role="screenshot-pick" ${btnDisabled ? "disabled" : ""} style="border:1px solid ${theme.border};color:${theme.text};">
|
|
901
|
-
${isUploadingScreenshot ? '<span class="fb-ups"></span> Uploading...' : "\u{1F4F7} Add screenshot"}
|
|
902
|
-
</button>
|
|
903
|
-
${extrasHtml}
|
|
904
|
-
</div>
|
|
905
|
-
`;
|
|
992
|
+
return screenshotError || screenshots.length > 0 || atMax ? `<div class="fb-up-extras">${errorHtml}${screenshots.length > 0 ? `<div class="fb-ss">${previewsHtml}</div>` : ""}${limitHtml}</div>` : "";
|
|
906
993
|
})() : "";
|
|
907
994
|
const emailBlockHtml = showEmailOption ? `
|
|
908
995
|
<div class="fb-email">
|
|
@@ -925,8 +1012,11 @@ function initUseroFeedbackWidget(props) {
|
|
|
925
1012
|
<form data-role="form">
|
|
926
1013
|
<div class="fb-es" role="radiogroup" aria-label="Rate experience">${ratingsHtml}</div>
|
|
927
1014
|
<textarea class="fb-ta" data-role="comment" placeholder="${escapeHtml(placeholder)}" aria-label="Comments" maxlength="1000" rows="2" style="border:1px solid ${theme.border};color:${theme.text};background-color:${theme.background};">${escapeHtml(comment)}</textarea>
|
|
928
|
-
<div class="fb-
|
|
929
|
-
|
|
1015
|
+
<div class="fb-toolrow">
|
|
1016
|
+
${uploadBtnHtml}
|
|
1017
|
+
<div class="fb-charcount${lowChars ? " fb-charcount--low" : ""}" data-role="charcount" style="color:${lowChars ? "#dc2626" : theme.text};opacity:${lowChars ? 1 : 0.6};">${remaining} chars remaining</div>
|
|
1018
|
+
</div>
|
|
1019
|
+
${uploadExtrasHtml ? `<div class="fb-up">${uploadExtrasHtml}</div>` : ""}
|
|
930
1020
|
${emailBlockHtml}
|
|
931
1021
|
<button class="fb-sub ${submitDisabled ? "fb-sub--dis" : ""}" type="submit" aria-label="Submit" ${submitDisabled ? "disabled" : ""} style="${submitStyle}">
|
|
932
1022
|
${isSubmitting ? '<span class="fb-spin"></span>' : ""}
|
|
@@ -1057,10 +1147,23 @@ function initUseroFeedbackWidget(props) {
|
|
|
1057
1147
|
destroyed = true;
|
|
1058
1148
|
document.removeEventListener("keydown", onKeyDown);
|
|
1059
1149
|
detachMqlListener();
|
|
1150
|
+
for (const plugin of pluginList) {
|
|
1151
|
+
if (!plugin.onDestroy) continue;
|
|
1152
|
+
const ctx = pluginContexts.get(plugin.name);
|
|
1153
|
+
if (!ctx) continue;
|
|
1154
|
+
try {
|
|
1155
|
+
plugin.onDestroy(ctx);
|
|
1156
|
+
} catch (err) {
|
|
1157
|
+
ctx.logger.error("onDestroy threw", err);
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
pluginStores.clear();
|
|
1161
|
+
pluginContexts.clear();
|
|
1060
1162
|
host.remove();
|
|
1061
1163
|
},
|
|
1062
1164
|
open,
|
|
1063
1165
|
close,
|
|
1166
|
+
whenReady: () => readyPromise,
|
|
1064
1167
|
update: (next) => {
|
|
1065
1168
|
if (destroyed) return;
|
|
1066
1169
|
let needsRender = false;
|