@microsurveysai/react-native 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/dist/index.cjs +1949 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +377 -0
- package/dist/index.d.ts +377 -0
- package/dist/index.js +1920 -0
- package/dist/index.js.map +1 -0
- package/package.json +63 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1920 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
+
|
|
5
|
+
// src/MicroSurveys.ts
|
|
6
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
7
|
+
import { AppState, Platform } from "react-native";
|
|
8
|
+
|
|
9
|
+
// src/core/storage.ts
|
|
10
|
+
var STORAGE_KEY_PREFIX = "com.microsurveys.";
|
|
11
|
+
function uuid() {
|
|
12
|
+
try {
|
|
13
|
+
const crypto = globalThis.crypto;
|
|
14
|
+
if (crypto && typeof crypto.randomUUID === "function") {
|
|
15
|
+
return crypto.randomUUID();
|
|
16
|
+
}
|
|
17
|
+
} catch {
|
|
18
|
+
}
|
|
19
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
20
|
+
const r = Math.random() * 16 | 0;
|
|
21
|
+
const v = c === "x" ? r : r & 3 | 8;
|
|
22
|
+
return v.toString(16);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/core/outbox.ts
|
|
27
|
+
var KEY = "com.microsurveys.outbox";
|
|
28
|
+
var MAX_ENTRIES = 200;
|
|
29
|
+
var Outbox = class {
|
|
30
|
+
constructor(kv) {
|
|
31
|
+
__publicField(this, "kv", kv);
|
|
32
|
+
}
|
|
33
|
+
read() {
|
|
34
|
+
const data = this.kv.getItem(KEY);
|
|
35
|
+
if (!data) return [];
|
|
36
|
+
try {
|
|
37
|
+
const parsed = JSON.parse(data);
|
|
38
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
39
|
+
} catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
write(entries) {
|
|
44
|
+
this.kv.setItem(KEY, JSON.stringify(entries));
|
|
45
|
+
}
|
|
46
|
+
enqueue(path, body) {
|
|
47
|
+
const entries = this.read();
|
|
48
|
+
entries.push({ id: uuid(), path, body });
|
|
49
|
+
if (entries.length > MAX_ENTRIES) entries.splice(0, entries.length - MAX_ENTRIES);
|
|
50
|
+
this.write(entries);
|
|
51
|
+
}
|
|
52
|
+
snapshot() {
|
|
53
|
+
return this.read();
|
|
54
|
+
}
|
|
55
|
+
remove(id) {
|
|
56
|
+
this.write(this.read().filter((e) => e.id !== id));
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/core/types.ts
|
|
61
|
+
function endUserIdOf(identity) {
|
|
62
|
+
return identity.amplitudeUserId ?? identity.amplitudeDeviceId ?? identity.hostUserId ?? identity.anonymousId;
|
|
63
|
+
}
|
|
64
|
+
function newTriggerRecord() {
|
|
65
|
+
return { stepIndex: 0, startedAt: null, satisfiedCount: 0 };
|
|
66
|
+
}
|
|
67
|
+
function newUserTriggerState() {
|
|
68
|
+
return { triggers: {}, surveys: {} };
|
|
69
|
+
}
|
|
70
|
+
function asObject(v) {
|
|
71
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
72
|
+
}
|
|
73
|
+
function numOr(v, fallback) {
|
|
74
|
+
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
|
75
|
+
}
|
|
76
|
+
function strOrUndef(v) {
|
|
77
|
+
return typeof v === "string" ? v : void 0;
|
|
78
|
+
}
|
|
79
|
+
function normalizeConfig(type, raw) {
|
|
80
|
+
switch (type) {
|
|
81
|
+
case "NPS":
|
|
82
|
+
return { kind: "scale", min: numOr(raw.min, 0), max: numOr(raw.max, 10), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
|
|
83
|
+
case "CES":
|
|
84
|
+
return { kind: "scale", min: numOr(raw.min, 1), max: numOr(raw.max, 7), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
|
|
85
|
+
case "CSAT_STAR":
|
|
86
|
+
return { kind: "stars", count: numOr(raw.count, 5) };
|
|
87
|
+
case "CSAT_EMOJI": {
|
|
88
|
+
const opts = Array.isArray(raw.options) ? raw.options : [];
|
|
89
|
+
const options = opts.map((o) => {
|
|
90
|
+
const oo = asObject(o);
|
|
91
|
+
return { value: String(oo.value ?? ""), emoji: typeof oo.emoji === "string" ? oo.emoji : "", label: strOrUndef(oo.label) };
|
|
92
|
+
});
|
|
93
|
+
return { kind: "emoji", options };
|
|
94
|
+
}
|
|
95
|
+
case "THUMBS":
|
|
96
|
+
return { kind: "thumbs" };
|
|
97
|
+
case "SINGLE_CHOICE": {
|
|
98
|
+
const opts = Array.isArray(raw.options) ? raw.options : [];
|
|
99
|
+
const options = opts.map((o) => {
|
|
100
|
+
const oo = asObject(o);
|
|
101
|
+
const value = String(oo.value ?? "");
|
|
102
|
+
return { value, label: typeof oo.label === "string" ? oo.label : value };
|
|
103
|
+
});
|
|
104
|
+
return { kind: "singleChoice", options };
|
|
105
|
+
}
|
|
106
|
+
case "OPEN_TEXT":
|
|
107
|
+
return { kind: "openText", placeholder: strOrUndef(raw.placeholder), maxLength: typeof raw.maxLength === "number" ? raw.maxLength : void 0 };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function normalizeQuestion(raw) {
|
|
111
|
+
const id = strOrUndef(raw.id);
|
|
112
|
+
const type = strOrUndef(raw.type);
|
|
113
|
+
const prompt = strOrUndef(raw.prompt);
|
|
114
|
+
if (!id || !type || prompt === void 0) return null;
|
|
115
|
+
return {
|
|
116
|
+
id,
|
|
117
|
+
order: numOr(raw.order, 0),
|
|
118
|
+
type,
|
|
119
|
+
prompt,
|
|
120
|
+
required: raw.required === true,
|
|
121
|
+
config: normalizeConfig(type, asObject(raw.config))
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function normalizeTrigger(raw) {
|
|
125
|
+
const id = strOrUndef(raw.id);
|
|
126
|
+
if (!id) return null;
|
|
127
|
+
const type = raw.type === "SEQUENCE" ? "SEQUENCE" : "SINGLE";
|
|
128
|
+
const steps = (Array.isArray(raw.steps) ? raw.steps : []).map((s) => {
|
|
129
|
+
const so = asObject(s);
|
|
130
|
+
const event = strOrUndef(so.event);
|
|
131
|
+
if (!event) return null;
|
|
132
|
+
return { order: numOr(so.order, 0), event, match: asObject(so.match) };
|
|
133
|
+
}).filter((s) => s !== null);
|
|
134
|
+
return {
|
|
135
|
+
id,
|
|
136
|
+
type,
|
|
137
|
+
delaySeconds: numOr(raw.delaySeconds, 0),
|
|
138
|
+
sequenceWindowSeconds: typeof raw.sequenceWindowSeconds === "number" ? raw.sequenceWindowSeconds : null,
|
|
139
|
+
fireEvery: numOr(raw.fireEvery, 1),
|
|
140
|
+
warmupCount: numOr(raw.warmupCount, 0),
|
|
141
|
+
steps
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
function normalizeSurvey(raw) {
|
|
145
|
+
const id = strOrUndef(raw.id);
|
|
146
|
+
const name = strOrUndef(raw.name);
|
|
147
|
+
if (!id || name === void 0) return null;
|
|
148
|
+
const questions = (Array.isArray(raw.questions) ? raw.questions : []).map((q) => normalizeQuestion(asObject(q))).filter((q) => q !== null);
|
|
149
|
+
const triggers = (Array.isArray(raw.triggers) ? raw.triggers : []).map((t) => normalizeTrigger(asObject(t))).filter((t) => t !== null);
|
|
150
|
+
return {
|
|
151
|
+
id,
|
|
152
|
+
name,
|
|
153
|
+
questions,
|
|
154
|
+
audienceMatch: raw.audienceMatch ?? null,
|
|
155
|
+
samplePercent: typeof raw.samplePercent === "number" ? raw.samplePercent : null,
|
|
156
|
+
maxPerUserDays: typeof raw.maxPerUserDays === "number" ? raw.maxPerUserDays : null,
|
|
157
|
+
startsAt: strOrUndef(raw.startsAt) ?? null,
|
|
158
|
+
endsAt: strOrUndef(raw.endsAt) ?? null,
|
|
159
|
+
triggers,
|
|
160
|
+
dismissible: typeof raw.dismissible === "boolean" ? raw.dismissible : null,
|
|
161
|
+
presentation: strOrUndef(raw.presentation) ?? null,
|
|
162
|
+
successMessage: strOrUndef(raw.successMessage) ?? null,
|
|
163
|
+
platforms: Array.isArray(raw.platforms) ? raw.platforms.filter((p) => typeof p === "string") : null
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function parseConfig(rawText) {
|
|
167
|
+
let root;
|
|
168
|
+
try {
|
|
169
|
+
root = asObject(JSON.parse(rawText));
|
|
170
|
+
} catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const projectId = strOrUndef(root.projectId);
|
|
174
|
+
if (!projectId) return null;
|
|
175
|
+
const surveys = (Array.isArray(root.surveys) ? root.surveys : []).map((s) => normalizeSurvey(asObject(s))).filter((s) => s !== null);
|
|
176
|
+
const theme = root.theme && typeof root.theme === "object" && !Array.isArray(root.theme) ? root.theme : null;
|
|
177
|
+
return { projectId, fetchedAt: strOrUndef(root.fetchedAt) ?? null, theme, surveys };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// src/core/apiClient.ts
|
|
181
|
+
var API_VERSION = "2026-06-30";
|
|
182
|
+
var ApiClient = class {
|
|
183
|
+
constructor(apiKey, baseURL, storage) {
|
|
184
|
+
__publicField(this, "apiKey");
|
|
185
|
+
__publicField(this, "baseURL");
|
|
186
|
+
__publicField(this, "outbox");
|
|
187
|
+
__publicField(this, "isFlushing", false);
|
|
188
|
+
this.apiKey = apiKey;
|
|
189
|
+
this.outbox = new Outbox(storage);
|
|
190
|
+
this.baseURL = baseURL.replace(/\/+$/, "");
|
|
191
|
+
}
|
|
192
|
+
// ── Config ─────────────────────────────────────────────────────────────────
|
|
193
|
+
/** `GET /api/sdk/config` with optional `If-None-Match`. Resolves `notModified`
|
|
194
|
+
* on 304 so the caller keeps its cache. Throws on network/5xx errors. */
|
|
195
|
+
async fetchConfig(etag) {
|
|
196
|
+
const headers = {
|
|
197
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
198
|
+
"MS-Api-Version": API_VERSION
|
|
199
|
+
};
|
|
200
|
+
if (etag) headers["If-None-Match"] = etag;
|
|
201
|
+
const res = await fetch(this.endpoint("/api/sdk/config"), { method: "GET", headers });
|
|
202
|
+
if (res.status === 304) return { kind: "notModified" };
|
|
203
|
+
if (!res.ok) throw new Error(`config fetch failed: ${res.status}`);
|
|
204
|
+
const rawText = await res.text();
|
|
205
|
+
return { kind: "config", rawText, config: parseConfig(rawText), etag: res.headers.get("ETag") };
|
|
206
|
+
}
|
|
207
|
+
// ── Impressions / responses ─────────────────────────────────────────────────
|
|
208
|
+
recordImpression(input) {
|
|
209
|
+
const payload = {
|
|
210
|
+
clientId: uuid(),
|
|
211
|
+
surveyId: input.surveyId,
|
|
212
|
+
triggerId: input.triggerId ?? void 0,
|
|
213
|
+
endUserId: input.endUserId,
|
|
214
|
+
shownAt: input.shownAt.toISOString(),
|
|
215
|
+
dismissed: input.dismissed
|
|
216
|
+
};
|
|
217
|
+
this.enqueue("/api/sdk/impressions", { impressions: [payload] });
|
|
218
|
+
}
|
|
219
|
+
recordResponse(input) {
|
|
220
|
+
const payload = {
|
|
221
|
+
clientId: uuid(),
|
|
222
|
+
surveyId: input.surveyId,
|
|
223
|
+
endUserId: input.endUserId,
|
|
224
|
+
completed: input.completed,
|
|
225
|
+
submittedAt: input.submittedAt.toISOString(),
|
|
226
|
+
userProps: input.userProps,
|
|
227
|
+
answers: input.answers
|
|
228
|
+
};
|
|
229
|
+
this.enqueue("/api/sdk/responses", { responses: [payload] });
|
|
230
|
+
}
|
|
231
|
+
enqueue(path, value) {
|
|
232
|
+
this.outbox.enqueue(path, JSON.stringify(value));
|
|
233
|
+
void this.flush();
|
|
234
|
+
}
|
|
235
|
+
// ── Flush ────────────────────────────────────────────────────────────────────
|
|
236
|
+
/** POSTs queued entries in order. Stops at the first retryable failure (likely
|
|
237
|
+
* offline) and leaves the rest for next time. Idempotency keys make re-sends
|
|
238
|
+
* safe. Never throws. */
|
|
239
|
+
async flush() {
|
|
240
|
+
if (this.isFlushing) return;
|
|
241
|
+
this.isFlushing = true;
|
|
242
|
+
try {
|
|
243
|
+
for (const entry of this.outbox.snapshot()) {
|
|
244
|
+
try {
|
|
245
|
+
await this.post(entry.path, entry.body);
|
|
246
|
+
this.outbox.remove(entry.id);
|
|
247
|
+
} catch {
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
} finally {
|
|
252
|
+
this.isFlushing = false;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
async post(path, body) {
|
|
256
|
+
const res = await fetch(this.endpoint(path), {
|
|
257
|
+
method: "POST",
|
|
258
|
+
headers: {
|
|
259
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
260
|
+
"MS-Api-Version": API_VERSION,
|
|
261
|
+
"Content-Type": "application/json; charset=utf-8"
|
|
262
|
+
},
|
|
263
|
+
body
|
|
264
|
+
});
|
|
265
|
+
if (res.status === 429 || res.status >= 500 && res.status < 600) {
|
|
266
|
+
throw new Error(`retryable ${res.status}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
endpoint(path) {
|
|
270
|
+
return this.baseURL + path;
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
// src/core/persistence.ts
|
|
275
|
+
var CONFIG_KEY = "com.microsurveys.config.cache";
|
|
276
|
+
var STATE_PREFIX = "com.microsurveys.triggerstate.";
|
|
277
|
+
var ConfigStore = class {
|
|
278
|
+
constructor(kv) {
|
|
279
|
+
__publicField(this, "kv", kv);
|
|
280
|
+
__publicField(this, "persisted", null);
|
|
281
|
+
__publicField(this, "parsed", null);
|
|
282
|
+
const data = kv.getItem(CONFIG_KEY);
|
|
283
|
+
if (data) {
|
|
284
|
+
try {
|
|
285
|
+
const entry = JSON.parse(data);
|
|
286
|
+
if (entry && typeof entry.rawConfig === "string") {
|
|
287
|
+
this.persisted = entry;
|
|
288
|
+
this.parsed = parseConfig(entry.rawConfig);
|
|
289
|
+
}
|
|
290
|
+
} catch {
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
get config() {
|
|
295
|
+
return this.parsed;
|
|
296
|
+
}
|
|
297
|
+
get surveys() {
|
|
298
|
+
return this.parsed?.surveys ?? [];
|
|
299
|
+
}
|
|
300
|
+
get theme() {
|
|
301
|
+
return this.parsed?.theme ?? null;
|
|
302
|
+
}
|
|
303
|
+
get etag() {
|
|
304
|
+
return this.persisted?.etag ?? null;
|
|
305
|
+
}
|
|
306
|
+
/** When the cached config was last written (ms epoch), for TTL checks. */
|
|
307
|
+
get storedAt() {
|
|
308
|
+
return this.persisted?.storedAt ?? null;
|
|
309
|
+
}
|
|
310
|
+
/** Persists the raw config response and refreshes the in-memory parse. */
|
|
311
|
+
save(rawConfig, etag) {
|
|
312
|
+
const entry = { rawConfig, etag, storedAt: Date.now() };
|
|
313
|
+
this.persisted = entry;
|
|
314
|
+
this.parsed = parseConfig(rawConfig);
|
|
315
|
+
this.kv.setItem(CONFIG_KEY, JSON.stringify(entry));
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
var TriggerStateStore = class {
|
|
319
|
+
constructor(kv) {
|
|
320
|
+
__publicField(this, "kv", kv);
|
|
321
|
+
}
|
|
322
|
+
load(endUserId) {
|
|
323
|
+
const data = this.kv.getItem(STATE_PREFIX + endUserId);
|
|
324
|
+
if (!data) return newUserTriggerState();
|
|
325
|
+
try {
|
|
326
|
+
const parsed = JSON.parse(data);
|
|
327
|
+
return { triggers: parsed.triggers ?? {}, surveys: parsed.surveys ?? {} };
|
|
328
|
+
} catch {
|
|
329
|
+
return newUserTriggerState();
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
save(endUserId, state) {
|
|
333
|
+
this.kv.setItem(STATE_PREFIX + endUserId, JSON.stringify(state));
|
|
334
|
+
}
|
|
335
|
+
reset(endUserId) {
|
|
336
|
+
this.kv.removeItem(STATE_PREFIX + endUserId);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
// src/core/identity.ts
|
|
341
|
+
var ANON_KEY = "com.microsurveys.anonymousId";
|
|
342
|
+
var PROPS_KEY = "com.microsurveys.userProperties";
|
|
343
|
+
var IdentityStore = class {
|
|
344
|
+
constructor(kv) {
|
|
345
|
+
__publicField(this, "kv", kv);
|
|
346
|
+
__publicField(this, "identity");
|
|
347
|
+
let anon = kv.getItem(ANON_KEY);
|
|
348
|
+
if (!anon) {
|
|
349
|
+
anon = "anon_" + uuid();
|
|
350
|
+
kv.setItem(ANON_KEY, anon);
|
|
351
|
+
}
|
|
352
|
+
let userProperties = {};
|
|
353
|
+
const props = kv.getItem(PROPS_KEY);
|
|
354
|
+
if (props) {
|
|
355
|
+
try {
|
|
356
|
+
const parsed = JSON.parse(props);
|
|
357
|
+
if (parsed && typeof parsed === "object") userProperties = parsed;
|
|
358
|
+
} catch {
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
this.identity = { anonymousId: anon, userProperties };
|
|
362
|
+
}
|
|
363
|
+
/** Thread-safe not required (single-threaded JS); returns a shallow snapshot. */
|
|
364
|
+
snapshot() {
|
|
365
|
+
return { ...this.identity, userProperties: { ...this.identity.userProperties } };
|
|
366
|
+
}
|
|
367
|
+
/** Apply a host `identify(id, properties)` call. Merges properties. */
|
|
368
|
+
setUser(id, properties) {
|
|
369
|
+
if (id) this.identity.hostUserId = id;
|
|
370
|
+
if (properties) {
|
|
371
|
+
for (const key of Object.keys(properties)) {
|
|
372
|
+
this.identity.userProperties[key] = toJson(properties[key]);
|
|
373
|
+
}
|
|
374
|
+
this.persistProperties();
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/** Merge an analytics identity update. Called per event, so it only persists
|
|
378
|
+
* when the properties actually changed. */
|
|
379
|
+
updateFromAnalytics(update) {
|
|
380
|
+
if (update.userId) this.identity.amplitudeUserId = update.userId;
|
|
381
|
+
if (update.deviceId) this.identity.amplitudeDeviceId = update.deviceId;
|
|
382
|
+
let changed = false;
|
|
383
|
+
if (update.userProperties) {
|
|
384
|
+
for (const key of Object.keys(update.userProperties)) {
|
|
385
|
+
const value = toJson(update.userProperties[key]);
|
|
386
|
+
if (JSON.stringify(this.identity.userProperties[key]) !== JSON.stringify(value)) {
|
|
387
|
+
this.identity.userProperties[key] = value;
|
|
388
|
+
changed = true;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (update.setOnceProperties) {
|
|
393
|
+
for (const key of Object.keys(update.setOnceProperties)) {
|
|
394
|
+
if (key in this.identity.userProperties) continue;
|
|
395
|
+
this.identity.userProperties[key] = toJson(update.setOnceProperties[key]);
|
|
396
|
+
changed = true;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
for (const key of update.unsetProperties ?? []) {
|
|
400
|
+
if (key in this.identity.userProperties) {
|
|
401
|
+
delete this.identity.userProperties[key];
|
|
402
|
+
changed = true;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (changed) this.persistProperties();
|
|
406
|
+
}
|
|
407
|
+
persistProperties() {
|
|
408
|
+
this.kv.setItem(PROPS_KEY, JSON.stringify(this.identity.userProperties));
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
function toJson(value) {
|
|
412
|
+
if (value === null || value === void 0) return null;
|
|
413
|
+
switch (typeof value) {
|
|
414
|
+
case "string":
|
|
415
|
+
case "number":
|
|
416
|
+
case "boolean":
|
|
417
|
+
return value;
|
|
418
|
+
case "object":
|
|
419
|
+
if (Array.isArray(value)) return value.map(toJson);
|
|
420
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toJson(v)]));
|
|
421
|
+
default:
|
|
422
|
+
return String(value);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// src/core/sampling.ts
|
|
427
|
+
var encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
|
|
428
|
+
function utf8Bytes(s, useEncoder = true) {
|
|
429
|
+
if (encoder && useEncoder) return encoder.encode(s);
|
|
430
|
+
const out = [];
|
|
431
|
+
for (const ch of s) {
|
|
432
|
+
const c = ch.codePointAt(0);
|
|
433
|
+
if (c < 128) out.push(c);
|
|
434
|
+
else if (c < 2048) {
|
|
435
|
+
out.push(192 | c >> 6, 128 | c & 63);
|
|
436
|
+
} else if (c < 65536) {
|
|
437
|
+
out.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
|
|
438
|
+
} else {
|
|
439
|
+
out.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return Uint8Array.from(out);
|
|
443
|
+
}
|
|
444
|
+
function fnv1a32(s) {
|
|
445
|
+
let hash = 2166136261;
|
|
446
|
+
const bytes = utf8Bytes(s);
|
|
447
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
448
|
+
hash ^= bytes[i];
|
|
449
|
+
hash = Math.imul(hash, 16777619);
|
|
450
|
+
}
|
|
451
|
+
return hash >>> 0;
|
|
452
|
+
}
|
|
453
|
+
function inSample(endUserId, surveyId, samplePercent) {
|
|
454
|
+
if (samplePercent >= 100) return true;
|
|
455
|
+
if (samplePercent <= 0) return false;
|
|
456
|
+
const bucket = fnv1a32(`${endUserId}:${surveyId}`) % 100;
|
|
457
|
+
return bucket < samplePercent;
|
|
458
|
+
}
|
|
459
|
+
function numberString(n) {
|
|
460
|
+
if (Number.isFinite(n) && Math.trunc(n) === n && Math.abs(n) < 1e15) {
|
|
461
|
+
return String(Math.trunc(n));
|
|
462
|
+
}
|
|
463
|
+
return String(n);
|
|
464
|
+
}
|
|
465
|
+
function stringify(value) {
|
|
466
|
+
switch (typeof value) {
|
|
467
|
+
case "string":
|
|
468
|
+
return value;
|
|
469
|
+
case "boolean":
|
|
470
|
+
return value ? "true" : "false";
|
|
471
|
+
case "number":
|
|
472
|
+
return numberString(value);
|
|
473
|
+
default:
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
function matches(filter, properties) {
|
|
478
|
+
for (const key of Object.keys(filter)) {
|
|
479
|
+
const expectedStr = stringify(filter[key]);
|
|
480
|
+
if (expectedStr === null) return false;
|
|
481
|
+
const actualStr = stringify(properties[key]);
|
|
482
|
+
if (actualStr === null) return false;
|
|
483
|
+
if (expectedStr !== actualStr) return false;
|
|
484
|
+
}
|
|
485
|
+
return true;
|
|
486
|
+
}
|
|
487
|
+
function eventMatchesStep(eventName, properties, step) {
|
|
488
|
+
if (eventName !== step.event) return false;
|
|
489
|
+
return matches(step.match, properties);
|
|
490
|
+
}
|
|
491
|
+
function audienceMatches(audience, userProperties) {
|
|
492
|
+
return matches(audience, userProperties);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// src/core/triggerSequencer.ts
|
|
496
|
+
function windowExpired(window, startedAt, nowT) {
|
|
497
|
+
if (window === null || window <= 0 || startedAt === null) return false;
|
|
498
|
+
return nowT - startedAt > window;
|
|
499
|
+
}
|
|
500
|
+
function advance(trigger, record, eventName, properties, nowT) {
|
|
501
|
+
const next = { ...record };
|
|
502
|
+
const steps = [...trigger.steps].sort((a, b) => a.order - b.order);
|
|
503
|
+
if (steps.length === 0) return { record: next, satisfied: false };
|
|
504
|
+
const matchesStep = (index) => eventMatchesStep(eventName, properties, steps[index]);
|
|
505
|
+
let satisfied = false;
|
|
506
|
+
if (trigger.type === "SINGLE") {
|
|
507
|
+
satisfied = matchesStep(0);
|
|
508
|
+
} else {
|
|
509
|
+
const expected = Math.min(next.stepIndex, steps.length - 1);
|
|
510
|
+
if (matchesStep(expected)) {
|
|
511
|
+
if (expected === 0) {
|
|
512
|
+
next.startedAt = nowT;
|
|
513
|
+
next.stepIndex = 1;
|
|
514
|
+
} else if (windowExpired(trigger.sequenceWindowSeconds, next.startedAt, nowT)) {
|
|
515
|
+
if (matchesStep(0)) {
|
|
516
|
+
next.startedAt = nowT;
|
|
517
|
+
next.stepIndex = 1;
|
|
518
|
+
} else {
|
|
519
|
+
next.stepIndex = 0;
|
|
520
|
+
next.startedAt = null;
|
|
521
|
+
}
|
|
522
|
+
} else {
|
|
523
|
+
next.stepIndex = expected + 1;
|
|
524
|
+
}
|
|
525
|
+
if (next.stepIndex >= steps.length) {
|
|
526
|
+
satisfied = true;
|
|
527
|
+
next.stepIndex = 0;
|
|
528
|
+
next.startedAt = null;
|
|
529
|
+
}
|
|
530
|
+
} else if (expected !== 0 && matchesStep(0)) {
|
|
531
|
+
next.startedAt = nowT;
|
|
532
|
+
next.stepIndex = 1;
|
|
533
|
+
if (steps.length === 1) {
|
|
534
|
+
satisfied = true;
|
|
535
|
+
next.stepIndex = 0;
|
|
536
|
+
next.startedAt = null;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (satisfied) next.satisfiedCount += 1;
|
|
541
|
+
return { record: next, satisfied };
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// src/core/triggerEngine.ts
|
|
545
|
+
var TriggerEngine = class {
|
|
546
|
+
constructor(opts) {
|
|
547
|
+
__publicField(this, "store");
|
|
548
|
+
__publicField(this, "surveysProvider");
|
|
549
|
+
__publicField(this, "identityProvider");
|
|
550
|
+
__publicField(this, "onPresent");
|
|
551
|
+
__publicField(this, "platform");
|
|
552
|
+
__publicField(this, "now");
|
|
553
|
+
__publicField(this, "timers", /* @__PURE__ */ new Set());
|
|
554
|
+
this.store = opts.store;
|
|
555
|
+
this.surveysProvider = opts.surveysProvider;
|
|
556
|
+
this.identityProvider = opts.identityProvider;
|
|
557
|
+
this.onPresent = opts.onPresent;
|
|
558
|
+
this.platform = opts.platform;
|
|
559
|
+
this.now = opts.now ?? (() => Date.now() / 1e3);
|
|
560
|
+
}
|
|
561
|
+
/** Feed an event into the engine. */
|
|
562
|
+
process(name, properties = {}) {
|
|
563
|
+
const identity = this.identityProvider();
|
|
564
|
+
const endUserId = endUserIdOf(identity);
|
|
565
|
+
const state = this.store.load(endUserId);
|
|
566
|
+
const nowT = this.now();
|
|
567
|
+
for (const survey of this.surveysProvider()) {
|
|
568
|
+
const triggers = survey.triggers;
|
|
569
|
+
if (!triggers || triggers.length === 0) continue;
|
|
570
|
+
if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) continue;
|
|
571
|
+
for (const trigger of triggers) {
|
|
572
|
+
const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
|
|
573
|
+
if (!satisfied) continue;
|
|
574
|
+
const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;
|
|
575
|
+
if (!this.isWithinWindow(survey, nowT)) continue;
|
|
576
|
+
if (!passesFrequency(trigger, occurrence)) continue;
|
|
577
|
+
if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;
|
|
578
|
+
if (!this.passesSampling(survey, endUserId, state)) continue;
|
|
579
|
+
if (!passesCap(survey, state, nowT)) continue;
|
|
580
|
+
this.scheduleShow(survey, trigger, identity);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
this.store.save(endUserId, state);
|
|
584
|
+
}
|
|
585
|
+
/** Cancels any pending scheduled presentations. */
|
|
586
|
+
stop() {
|
|
587
|
+
for (const t of this.timers) clearTimeout(t);
|
|
588
|
+
this.timers.clear();
|
|
589
|
+
}
|
|
590
|
+
// ── Trigger advancement ────────────────────────────────────────────────────
|
|
591
|
+
advanceTrigger(trigger, state, eventName, properties, nowT) {
|
|
592
|
+
const record = state.triggers[trigger.id] ?? newTriggerRecord();
|
|
593
|
+
const { record: updated, satisfied } = advance(trigger, record, eventName, properties, nowT);
|
|
594
|
+
state.triggers[trigger.id] = updated;
|
|
595
|
+
return satisfied;
|
|
596
|
+
}
|
|
597
|
+
// ── Eligibility checks ─────────────────────────────────────────────────────
|
|
598
|
+
isWithinWindow(survey, nowT) {
|
|
599
|
+
if (survey.startsAt) {
|
|
600
|
+
const start = Date.parse(survey.startsAt);
|
|
601
|
+
if (!Number.isNaN(start) && nowT < start / 1e3) return false;
|
|
602
|
+
}
|
|
603
|
+
if (survey.endsAt) {
|
|
604
|
+
const end = Date.parse(survey.endsAt);
|
|
605
|
+
if (!Number.isNaN(end) && nowT > end / 1e3) return false;
|
|
606
|
+
}
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
passesSampling(survey, endUserId, state) {
|
|
610
|
+
const existing = state.surveys[survey.id]?.sampleDecision;
|
|
611
|
+
if (existing !== void 0 && existing !== null) return existing;
|
|
612
|
+
const decision = inSample(endUserId, survey.id, survey.samplePercent ?? 100);
|
|
613
|
+
const record = state.surveys[survey.id] ?? {};
|
|
614
|
+
record.sampleDecision = decision;
|
|
615
|
+
state.surveys[survey.id] = record;
|
|
616
|
+
return decision;
|
|
617
|
+
}
|
|
618
|
+
// ── Scheduling ─────────────────────────────────────────────────────────────
|
|
619
|
+
scheduleShow(survey, trigger, identity) {
|
|
620
|
+
const delayMs = Math.max(0, trigger.delaySeconds) * 1e3;
|
|
621
|
+
const timer = setTimeout(() => {
|
|
622
|
+
this.timers.delete(timer);
|
|
623
|
+
const endUserId = endUserIdOf(identity);
|
|
624
|
+
const state = this.store.load(endUserId);
|
|
625
|
+
const nowT = this.now();
|
|
626
|
+
if (!passesCap(survey, state, nowT)) return;
|
|
627
|
+
const record = state.surveys[survey.id] ?? {};
|
|
628
|
+
record.lastShownAt = nowT;
|
|
629
|
+
state.surveys[survey.id] = record;
|
|
630
|
+
this.store.save(endUserId, state);
|
|
631
|
+
this.onPresent(survey, trigger, identity);
|
|
632
|
+
}, delayMs);
|
|
633
|
+
this.timers.add(timer);
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
function passesFrequency(trigger, occurrence) {
|
|
637
|
+
const fireEvery = Math.max(1, trigger.fireEvery);
|
|
638
|
+
const effective = occurrence - trigger.warmupCount;
|
|
639
|
+
return effective >= 1 && effective % fireEvery === 0;
|
|
640
|
+
}
|
|
641
|
+
function passesCap(survey, state, nowT) {
|
|
642
|
+
const days = survey.maxPerUserDays ?? 0;
|
|
643
|
+
const lastShown = state.surveys[survey.id]?.lastShownAt;
|
|
644
|
+
if (days <= 0 || lastShown === void 0 || lastShown === null) return true;
|
|
645
|
+
const elapsed = nowT - lastShown;
|
|
646
|
+
return elapsed >= days * 86400;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// src/core/client.ts
|
|
650
|
+
var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
|
|
651
|
+
var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
|
|
652
|
+
var MicroSurveysClient = class {
|
|
653
|
+
constructor(opts) {
|
|
654
|
+
__publicField(this, "api");
|
|
655
|
+
__publicField(this, "configStore");
|
|
656
|
+
__publicField(this, "identityStore");
|
|
657
|
+
__publicField(this, "triggerStateStore");
|
|
658
|
+
__publicField(this, "engine");
|
|
659
|
+
__publicField(this, "configTTLms");
|
|
660
|
+
__publicField(this, "refreshOnForeground");
|
|
661
|
+
__publicField(this, "subscribeForeground");
|
|
662
|
+
__publicField(this, "presentListeners", /* @__PURE__ */ new Set());
|
|
663
|
+
__publicField(this, "configListeners", /* @__PURE__ */ new Set());
|
|
664
|
+
__publicField(this, "active", null);
|
|
665
|
+
__publicField(this, "started", false);
|
|
666
|
+
__publicField(this, "unsubscribeForeground", null);
|
|
667
|
+
const kv = opts.storage;
|
|
668
|
+
this.configStore = new ConfigStore(kv);
|
|
669
|
+
this.identityStore = new IdentityStore(kv);
|
|
670
|
+
this.triggerStateStore = new TriggerStateStore(kv);
|
|
671
|
+
this.api = new ApiClient(opts.apiKey, opts.apiBaseURL ?? DEFAULT_BASE_URL, kv);
|
|
672
|
+
this.configTTLms = opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS;
|
|
673
|
+
this.refreshOnForeground = opts.refreshOnForeground ?? true;
|
|
674
|
+
this.subscribeForeground = opts.subscribeForeground;
|
|
675
|
+
this.engine = new TriggerEngine({
|
|
676
|
+
store: this.triggerStateStore,
|
|
677
|
+
surveysProvider: () => this.configStore.surveys,
|
|
678
|
+
identityProvider: () => this.identityStore.snapshot(),
|
|
679
|
+
onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),
|
|
680
|
+
platform: opts.platform
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
// ── Lifecycle ────────────────────────────────────────────────────────────────
|
|
684
|
+
/** Flush any queued ingest, refresh config, and (optionally) wire the
|
|
685
|
+
* foreground refresh. Safe to call once early. */
|
|
686
|
+
start() {
|
|
687
|
+
if (this.started) return;
|
|
688
|
+
this.started = true;
|
|
689
|
+
void this.api.flush();
|
|
690
|
+
void this.refreshConfig();
|
|
691
|
+
if (this.refreshOnForeground) {
|
|
692
|
+
this.unsubscribeForeground = this.subscribeForeground(() => {
|
|
693
|
+
void this.api.flush();
|
|
694
|
+
this.refreshConfigIfStale();
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
/** Tear down listeners + pending timers. */
|
|
699
|
+
stop() {
|
|
700
|
+
this.engine.stop();
|
|
701
|
+
this.unsubscribeForeground?.();
|
|
702
|
+
this.unsubscribeForeground = null;
|
|
703
|
+
this.started = false;
|
|
704
|
+
}
|
|
705
|
+
/** Force an ETag-aware config refresh; keeps the cache on failure. */
|
|
706
|
+
async refreshConfig() {
|
|
707
|
+
try {
|
|
708
|
+
const result = await this.api.fetchConfig(this.configStore.etag);
|
|
709
|
+
if (result.kind === "config") {
|
|
710
|
+
this.configStore.save(result.rawText, result.etag);
|
|
711
|
+
this.configListeners.forEach((l) => l());
|
|
712
|
+
}
|
|
713
|
+
} catch {
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
/** Refresh only when the cache is missing or older than the TTL. */
|
|
717
|
+
refreshConfigIfStale() {
|
|
718
|
+
const storedAt = this.configStore.storedAt;
|
|
719
|
+
if (storedAt !== null && Date.now() - storedAt < this.configTTLms) return;
|
|
720
|
+
void this.refreshConfig();
|
|
721
|
+
}
|
|
722
|
+
// ── Identity + events ────────────────────────────────────────────────────────
|
|
723
|
+
identify(userId, properties) {
|
|
724
|
+
this.identityStore.setUser(userId, properties);
|
|
725
|
+
}
|
|
726
|
+
track(name, properties = {}) {
|
|
727
|
+
this.engine.process(name, properties);
|
|
728
|
+
}
|
|
729
|
+
/** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
|
|
730
|
+
* Its user/device id take precedence over `identify()` for `endUserId`. */
|
|
731
|
+
updateAnalyticsIdentity(update) {
|
|
732
|
+
this.identityStore.updateFromAnalytics(update);
|
|
733
|
+
}
|
|
734
|
+
// ── Config accessors (for inline rendering) ──────────────────────────────────
|
|
735
|
+
getTheme() {
|
|
736
|
+
return this.configStore.theme;
|
|
737
|
+
}
|
|
738
|
+
getSurvey(surveyId) {
|
|
739
|
+
return this.configStore.surveys.find((s) => s.id === surveyId);
|
|
740
|
+
}
|
|
741
|
+
/** Subscribe to config refreshes (e.g. to render an inline survey that wasn't
|
|
742
|
+
* cached yet). Returns an unsubscribe function. */
|
|
743
|
+
onConfigChange(cb) {
|
|
744
|
+
this.configListeners.add(cb);
|
|
745
|
+
return () => this.configListeners.delete(cb);
|
|
746
|
+
}
|
|
747
|
+
// ── Presentation ─────────────────────────────────────────────────────────────
|
|
748
|
+
/** Subscribe to auto-triggered surveys. Returns an unsubscribe function. If a
|
|
749
|
+
* survey is already active, the new subscriber is notified immediately. */
|
|
750
|
+
onPresent(cb) {
|
|
751
|
+
this.presentListeners.add(cb);
|
|
752
|
+
if (this.active && !this.active.closed) cb(this.toActiveSurvey(this.active));
|
|
753
|
+
return () => this.presentListeners.delete(cb);
|
|
754
|
+
}
|
|
755
|
+
handlePresent(survey, trigger, identity) {
|
|
756
|
+
if (this.active && !this.active.closed) return;
|
|
757
|
+
const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
|
|
758
|
+
this.active = p;
|
|
759
|
+
const active = this.toActiveSurvey(p);
|
|
760
|
+
this.presentListeners.forEach((l) => l(active));
|
|
761
|
+
}
|
|
762
|
+
toActiveSurvey(p) {
|
|
763
|
+
return {
|
|
764
|
+
survey: p.survey,
|
|
765
|
+
trigger: p.trigger,
|
|
766
|
+
close: (result) => {
|
|
767
|
+
if (p.closed) return;
|
|
768
|
+
p.closed = true;
|
|
769
|
+
this.recordOutcome(p.survey.id, p.trigger?.id ?? null, p.identity, p.shownAt, result);
|
|
770
|
+
if (this.active === p) this.active = null;
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
/** Records the outcome of an **inline** `<MicroSurvey>` (no trigger/gate). */
|
|
775
|
+
recordInline(survey, result, shownAt) {
|
|
776
|
+
const identity = this.identityStore.snapshot();
|
|
777
|
+
this.recordOutcome(survey.id, null, identity, shownAt, result);
|
|
778
|
+
}
|
|
779
|
+
recordOutcome(surveyId, triggerId, identity, shownAt, result) {
|
|
780
|
+
const endUserId = endUserIdOf(identity);
|
|
781
|
+
this.api.recordImpression({ surveyId, triggerId, endUserId, shownAt, dismissed: result.dismissed });
|
|
782
|
+
if (result.completed || result.answers.length > 0) {
|
|
783
|
+
this.api.recordResponse({
|
|
784
|
+
surveyId,
|
|
785
|
+
endUserId,
|
|
786
|
+
completed: result.completed,
|
|
787
|
+
submittedAt: /* @__PURE__ */ new Date(),
|
|
788
|
+
userProps: identity.userProperties,
|
|
789
|
+
answers: result.answers
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
};
|
|
794
|
+
function createClient(opts) {
|
|
795
|
+
return new MicroSurveysClient(opts);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// src/amplitude.ts
|
|
799
|
+
function createAmplitudePlugin(forwarder) {
|
|
800
|
+
return {
|
|
801
|
+
name: "microsurveys",
|
|
802
|
+
type: "enrichment",
|
|
803
|
+
async setup() {
|
|
804
|
+
},
|
|
805
|
+
async execute(event) {
|
|
806
|
+
try {
|
|
807
|
+
forwarder.updateAnalyticsIdentity(identityOf(event));
|
|
808
|
+
if (!event.event_type.startsWith("$")) {
|
|
809
|
+
forwarder.track(event.event_type, event.event_properties ?? {});
|
|
810
|
+
}
|
|
811
|
+
} catch {
|
|
812
|
+
}
|
|
813
|
+
return event;
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
function identityOf(event) {
|
|
818
|
+
const update = { userId: event.user_id, deviceId: event.device_id };
|
|
819
|
+
if (event.event_type !== "$identify" || !event.user_properties) return update;
|
|
820
|
+
const ops = event.user_properties;
|
|
821
|
+
const set = asRecord(ops.$set);
|
|
822
|
+
const setOnce = asRecord(ops.$setOnce);
|
|
823
|
+
if (set) update.userProperties = set;
|
|
824
|
+
if (setOnce) update.setOnceProperties = setOnce;
|
|
825
|
+
const unset = asRecord(ops.$unset);
|
|
826
|
+
if (unset) update.unsetProperties = Object.keys(unset);
|
|
827
|
+
return update;
|
|
828
|
+
}
|
|
829
|
+
function asRecord(v) {
|
|
830
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// src/asyncStorage.ts
|
|
834
|
+
async function hydrateAsyncStorage(store) {
|
|
835
|
+
const cache = /* @__PURE__ */ new Map();
|
|
836
|
+
try {
|
|
837
|
+
const keys = (await store.getAllKeys()).filter((k) => k.startsWith(STORAGE_KEY_PREFIX));
|
|
838
|
+
for (const [key, value] of await readMany(store, keys)) {
|
|
839
|
+
if (value !== null) cache.set(key, value);
|
|
840
|
+
}
|
|
841
|
+
} catch {
|
|
842
|
+
}
|
|
843
|
+
let chain = Promise.resolve();
|
|
844
|
+
const enqueue = (write) => {
|
|
845
|
+
chain = chain.then(write).catch(() => {
|
|
846
|
+
});
|
|
847
|
+
};
|
|
848
|
+
return {
|
|
849
|
+
getItem: (key) => cache.get(key) ?? null,
|
|
850
|
+
setItem(key, value) {
|
|
851
|
+
cache.set(key, value);
|
|
852
|
+
enqueue(() => store.setItem(key, value));
|
|
853
|
+
},
|
|
854
|
+
removeItem(key) {
|
|
855
|
+
cache.delete(key);
|
|
856
|
+
enqueue(() => store.removeItem(key));
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
async function readMany(store, keys) {
|
|
861
|
+
if (keys.length === 0) return [];
|
|
862
|
+
if (store.getMany) return Object.entries(await store.getMany(keys));
|
|
863
|
+
if (store.multiGet) return (await store.multiGet(keys)).map(([k, v]) => [k, v]);
|
|
864
|
+
return Promise.all(keys.map(async (k) => [k, await store.getItem(k)]));
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// src/MicroSurveys.ts
|
|
868
|
+
var DEFAULT_BASE_URL2 = "https://console.microsurveys.ai";
|
|
869
|
+
var DEFAULT_CONFIG_TTL_MS2 = 12 * 60 * 60 * 1e3;
|
|
870
|
+
function appStateForeground(onForeground) {
|
|
871
|
+
const sub = AppState.addEventListener("change", (state) => {
|
|
872
|
+
if (state === "active") onForeground();
|
|
873
|
+
});
|
|
874
|
+
return () => sub.remove();
|
|
875
|
+
}
|
|
876
|
+
var MicroSurveys = class {
|
|
877
|
+
constructor(opts) {
|
|
878
|
+
__publicField(this, "apiKey");
|
|
879
|
+
/** Resolves with the underlying runtime once storage has loaded. */
|
|
880
|
+
__publicField(this, "ready");
|
|
881
|
+
__publicField(this, "client", null);
|
|
882
|
+
__publicField(this, "pending", []);
|
|
883
|
+
this.apiKey = opts.apiKey;
|
|
884
|
+
const storage = opts.storage ? Promise.resolve(opts.storage) : hydrateAsyncStorage(opts.asyncStorage ?? AsyncStorage);
|
|
885
|
+
this.ready = storage.then((kv) => {
|
|
886
|
+
const client = createClient({
|
|
887
|
+
apiKey: opts.apiKey,
|
|
888
|
+
apiBaseURL: opts.apiBaseURL ?? DEFAULT_BASE_URL2,
|
|
889
|
+
configTTLms: opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS2,
|
|
890
|
+
refreshOnForeground: opts.refreshOnForeground ?? true,
|
|
891
|
+
// Survey platform targeting: "ios" | "android".
|
|
892
|
+
platform: Platform.OS,
|
|
893
|
+
storage: kv,
|
|
894
|
+
subscribeForeground: appStateForeground
|
|
895
|
+
});
|
|
896
|
+
this.client = client;
|
|
897
|
+
const queued = this.pending;
|
|
898
|
+
this.pending = [];
|
|
899
|
+
for (const run of queued) run(client);
|
|
900
|
+
return client;
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
/** Runs `fn` now if the runtime is ready, otherwise as soon as it is. */
|
|
904
|
+
withClient(fn) {
|
|
905
|
+
if (this.client) fn(this.client);
|
|
906
|
+
else this.pending.push(fn);
|
|
907
|
+
}
|
|
908
|
+
// ── Lifecycle ────────────────────────────────────────────────────────────────
|
|
909
|
+
/** Flushes queued impressions/responses, refreshes the config, and starts the
|
|
910
|
+
* foreground refresh. Safe to call once early in app launch (the provider
|
|
911
|
+
* calls it for you unless `autoStart={false}`). */
|
|
912
|
+
start() {
|
|
913
|
+
this.withClient((c) => c.start());
|
|
914
|
+
}
|
|
915
|
+
/** Stops foreground refresh and cancels pending (delayed) presentations. */
|
|
916
|
+
stop() {
|
|
917
|
+
this.withClient((c) => c.stop());
|
|
918
|
+
}
|
|
919
|
+
/** Forces an ETag-aware config refresh. Keeps the cache on failure. */
|
|
920
|
+
async refreshConfig() {
|
|
921
|
+
const client = await this.ready;
|
|
922
|
+
await client.refreshConfig();
|
|
923
|
+
}
|
|
924
|
+
// ── Identity + events ────────────────────────────────────────────────────────
|
|
925
|
+
/** Identify the current user and/or attach properties used by audience
|
|
926
|
+
* targeting. Optional with Amplitude (identity flows in via the plugin). */
|
|
927
|
+
identify(userId, properties) {
|
|
928
|
+
this.withClient((c) => c.identify(userId, properties));
|
|
929
|
+
}
|
|
930
|
+
/** Record an event. An eligible survey presents itself after its configured
|
|
931
|
+
* delay. Not needed for events that already flow through Amplitude. */
|
|
932
|
+
track(name, properties) {
|
|
933
|
+
this.withClient((c) => c.track(name, properties));
|
|
934
|
+
}
|
|
935
|
+
/** Identity forwarded by an analytics SDK. Used by the Amplitude plugin. */
|
|
936
|
+
updateAnalyticsIdentity(update) {
|
|
937
|
+
this.withClient((c) => c.updateAnalyticsIdentity(update));
|
|
938
|
+
}
|
|
939
|
+
/** The enrichment plugin to register on your Amplitude instance:
|
|
940
|
+
* `amplitude.add(ms.amplitudePlugin())`. Forwards events + identity into the
|
|
941
|
+
* SDK and returns every event unmodified. */
|
|
942
|
+
amplitudePlugin() {
|
|
943
|
+
return createAmplitudePlugin(this);
|
|
944
|
+
}
|
|
945
|
+
// ── Config + presentation (used by the provider and inline surveys) ──────────
|
|
946
|
+
getTheme() {
|
|
947
|
+
return this.client?.getTheme() ?? null;
|
|
948
|
+
}
|
|
949
|
+
getSurvey(surveyId) {
|
|
950
|
+
return this.client?.getSurvey(surveyId);
|
|
951
|
+
}
|
|
952
|
+
/** Subscribe to config loads/refreshes. Fires once when the cached config
|
|
953
|
+
* becomes available. Returns an unsubscribe function. */
|
|
954
|
+
onConfigChange(cb) {
|
|
955
|
+
let unsubscribe = null;
|
|
956
|
+
let cancelled = false;
|
|
957
|
+
this.withClient((c) => {
|
|
958
|
+
if (cancelled) return;
|
|
959
|
+
unsubscribe = c.onConfigChange(cb);
|
|
960
|
+
cb();
|
|
961
|
+
});
|
|
962
|
+
return () => {
|
|
963
|
+
cancelled = true;
|
|
964
|
+
unsubscribe?.();
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
/** Subscribe to auto-triggered surveys. Returns an unsubscribe function. */
|
|
968
|
+
onPresent(cb) {
|
|
969
|
+
let unsubscribe = null;
|
|
970
|
+
let cancelled = false;
|
|
971
|
+
this.withClient((c) => {
|
|
972
|
+
if (!cancelled) unsubscribe = c.onPresent(cb);
|
|
973
|
+
});
|
|
974
|
+
return () => {
|
|
975
|
+
cancelled = true;
|
|
976
|
+
unsubscribe?.();
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
/** Records the outcome of an inline `<MicroSurvey>`. */
|
|
980
|
+
recordInline(survey, result, shownAt) {
|
|
981
|
+
this.withClient((c) => c.recordInline(survey, result, shownAt));
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
|
|
985
|
+
// src/provider.tsx
|
|
986
|
+
import { createContext, useContext, useEffect as useEffect3, useMemo as useMemo3, useRef as useRef3, useState as useState4 } from "react";
|
|
987
|
+
|
|
988
|
+
// src/ui/SurveyModal.tsx
|
|
989
|
+
import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
|
|
990
|
+
import {
|
|
991
|
+
Animated as Animated2,
|
|
992
|
+
Easing,
|
|
993
|
+
Keyboard,
|
|
994
|
+
KeyboardAvoidingView,
|
|
995
|
+
Modal,
|
|
996
|
+
PanResponder,
|
|
997
|
+
Platform as Platform5,
|
|
998
|
+
Pressable as Pressable4,
|
|
999
|
+
StyleSheet as StyleSheet4,
|
|
1000
|
+
View as View4,
|
|
1001
|
+
useColorScheme,
|
|
1002
|
+
useWindowDimensions
|
|
1003
|
+
} from "react-native";
|
|
1004
|
+
import { SafeAreaProvider, initialWindowMetrics, useSafeAreaInsets } from "react-native-safe-area-context";
|
|
1005
|
+
|
|
1006
|
+
// src/ui/SurveyCard.tsx
|
|
1007
|
+
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState as useState2 } from "react";
|
|
1008
|
+
import { Animated, Platform as Platform4, Pressable as Pressable3, ScrollView, StyleSheet as StyleSheet3, Text as Text2, View as View3 } from "react-native";
|
|
1009
|
+
|
|
1010
|
+
// src/ui/CloseButton.tsx
|
|
1011
|
+
import { Platform as Platform3, Pressable, StyleSheet, View } from "react-native";
|
|
1012
|
+
|
|
1013
|
+
// src/ui/platform.ts
|
|
1014
|
+
import { Platform as Platform2 } from "react-native";
|
|
1015
|
+
var usesGlassChrome = Platform2.OS === "ios" && parseInt(String(Platform2.Version), 10) >= 26;
|
|
1016
|
+
var FLOATING_SHEET_INSET = 8;
|
|
1017
|
+
var FLOATING_SHEET_RADIUS = 52;
|
|
1018
|
+
|
|
1019
|
+
// src/ui/CloseButton.tsx
|
|
1020
|
+
import { jsx } from "react/jsx-runtime";
|
|
1021
|
+
function CloseButton({ theme, onPress, style }) {
|
|
1022
|
+
let circle;
|
|
1023
|
+
let cross;
|
|
1024
|
+
if (usesGlassChrome) {
|
|
1025
|
+
circle = {
|
|
1026
|
+
width: 44,
|
|
1027
|
+
height: 44,
|
|
1028
|
+
borderRadius: 22,
|
|
1029
|
+
backgroundColor: theme.dark ? "rgba(72, 72, 74, 0.92)" : "rgba(255, 255, 255, 0.94)",
|
|
1030
|
+
borderWidth: StyleSheet.hairlineWidth,
|
|
1031
|
+
borderColor: theme.dark ? "rgba(255, 255, 255, 0.16)" : "rgba(0, 0, 0, 0.14)",
|
|
1032
|
+
shadowColor: "#000",
|
|
1033
|
+
shadowOpacity: theme.dark ? 0.3 : 0.08,
|
|
1034
|
+
shadowRadius: 8,
|
|
1035
|
+
shadowOffset: { width: 0, height: 2 }
|
|
1036
|
+
};
|
|
1037
|
+
cross = { color: theme.dark ? "rgba(255, 255, 255, 0.92)" : "rgba(0, 0, 0, 0.88)", length: 19, thickness: 2.6 };
|
|
1038
|
+
} else if (Platform3.OS === "ios") {
|
|
1039
|
+
circle = { width: 31, height: 31, borderRadius: 15.5, backgroundColor: theme.dark ? "rgba(235, 235, 245, 0.6)" : "rgba(60, 60, 67, 0.6)" };
|
|
1040
|
+
cross = { color: theme.surface, length: 12, thickness: 2.4 };
|
|
1041
|
+
} else {
|
|
1042
|
+
circle = { width: 32, height: 32, borderRadius: 16, backgroundColor: theme.track };
|
|
1043
|
+
cross = { color: theme.secondaryText, length: 13, thickness: 2 };
|
|
1044
|
+
}
|
|
1045
|
+
return /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Close survey", onPress, hitSlop: 6, style: [styles.hit, style], children: ({ pressed }) => /* @__PURE__ */ jsx(View, { style: [circle, styles.center, pressed && { opacity: 0.7 }], children: [45, -45].map((deg) => /* @__PURE__ */ jsx(
|
|
1046
|
+
View,
|
|
1047
|
+
{
|
|
1048
|
+
style: {
|
|
1049
|
+
position: "absolute",
|
|
1050
|
+
width: cross.length,
|
|
1051
|
+
height: cross.thickness,
|
|
1052
|
+
borderRadius: cross.thickness / 2,
|
|
1053
|
+
backgroundColor: cross.color,
|
|
1054
|
+
transform: [{ rotate: `${deg}deg` }]
|
|
1055
|
+
}
|
|
1056
|
+
},
|
|
1057
|
+
deg
|
|
1058
|
+
)) }) });
|
|
1059
|
+
}
|
|
1060
|
+
var styles = StyleSheet.create({
|
|
1061
|
+
hit: { position: "absolute", width: 44, height: 44, alignItems: "center", justifyContent: "center" },
|
|
1062
|
+
center: { alignItems: "center", justifyContent: "center" }
|
|
1063
|
+
});
|
|
1064
|
+
|
|
1065
|
+
// src/ui/questions.tsx
|
|
1066
|
+
import { useState } from "react";
|
|
1067
|
+
import { Pressable as Pressable2, StyleSheet as StyleSheet2, Text, TextInput, View as View2 } from "react-native";
|
|
1068
|
+
|
|
1069
|
+
// src/ui/theme.ts
|
|
1070
|
+
var PALETTES = {
|
|
1071
|
+
light: {
|
|
1072
|
+
background: "#09090B",
|
|
1073
|
+
surface: "#FFFFFF",
|
|
1074
|
+
text: "#18181B",
|
|
1075
|
+
secondaryText: "#71717A",
|
|
1076
|
+
accent: "#2E7272",
|
|
1077
|
+
// Slate Teal (brand primary)
|
|
1078
|
+
accentText: "#FFFFFF",
|
|
1079
|
+
border: "#E4E4E7",
|
|
1080
|
+
track: "#F4F4F5"
|
|
1081
|
+
},
|
|
1082
|
+
dark: {
|
|
1083
|
+
background: "#000000",
|
|
1084
|
+
surface: "#1A1A1E",
|
|
1085
|
+
text: "#FAFAFA",
|
|
1086
|
+
secondaryText: "#A1A1AA",
|
|
1087
|
+
accent: "#41B2B2",
|
|
1088
|
+
accentText: "#FFFFFF",
|
|
1089
|
+
border: "#333338",
|
|
1090
|
+
track: "#27272A"
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
var WEIGHTS = { regular: "400", medium: "500", semibold: "600", bold: "700" };
|
|
1094
|
+
function resolveTheme(project, opts = {}) {
|
|
1095
|
+
const p = project ?? {};
|
|
1096
|
+
const base = PALETTES[opts.scheme ?? "light"];
|
|
1097
|
+
const accent = color(p.accent) ?? base.accent;
|
|
1098
|
+
const controlHeight = num(p.controlHeight) ?? 48;
|
|
1099
|
+
let cornerRadius = 16;
|
|
1100
|
+
let sheetCornerRadius = 28;
|
|
1101
|
+
let controlRadius = 12;
|
|
1102
|
+
const cr = num(p.cornerRadius);
|
|
1103
|
+
if (cr !== void 0) {
|
|
1104
|
+
cornerRadius = cr;
|
|
1105
|
+
sheetCornerRadius = cr;
|
|
1106
|
+
controlRadius = Math.max(0, cr - 2);
|
|
1107
|
+
}
|
|
1108
|
+
controlRadius = num(p.controlRadius) ?? controlRadius;
|
|
1109
|
+
if (p.controlPill === true) controlRadius = controlHeight / 2;
|
|
1110
|
+
let position = p.position === "center" ? "center" : "bottom";
|
|
1111
|
+
switch (opts.presentation) {
|
|
1112
|
+
case "dialog":
|
|
1113
|
+
case "center":
|
|
1114
|
+
position = "center";
|
|
1115
|
+
break;
|
|
1116
|
+
case "sheet":
|
|
1117
|
+
case "bottom":
|
|
1118
|
+
position = "bottom";
|
|
1119
|
+
break;
|
|
1120
|
+
}
|
|
1121
|
+
return {
|
|
1122
|
+
// A fixed ~40% dim of the (opaque) configured background, like iOS.
|
|
1123
|
+
scrim: withAlpha(color(p.background) ?? base.background, 0.4),
|
|
1124
|
+
surface: color(p.surface) ?? base.surface,
|
|
1125
|
+
text: color(p.text) ?? base.text,
|
|
1126
|
+
secondaryText: color(p.secondaryText) ?? base.secondaryText,
|
|
1127
|
+
accent,
|
|
1128
|
+
accentText: color(p.accentText) ?? base.accentText,
|
|
1129
|
+
border: color(p.border) ?? base.border,
|
|
1130
|
+
track: base.track,
|
|
1131
|
+
accentTint: withAlpha(accent, 0.1),
|
|
1132
|
+
accentTintStrong: withAlpha(accent, 0.12),
|
|
1133
|
+
cornerRadius,
|
|
1134
|
+
sheetCornerRadius,
|
|
1135
|
+
nativeSheetCorners: cr === void 0,
|
|
1136
|
+
dark: opts.scheme === "dark",
|
|
1137
|
+
controlRadius,
|
|
1138
|
+
controlHeight,
|
|
1139
|
+
spacing: num(p.spacing) ?? 16,
|
|
1140
|
+
textScale: Math.max(0.5, num(p.textScale) ?? 1),
|
|
1141
|
+
titleSize: num(p.titleSize) ?? 20,
|
|
1142
|
+
titleWeight: WEIGHTS[(p.titleWeight ?? "").toLowerCase()] ?? "600",
|
|
1143
|
+
titleLineHeight: num(p.titleLineHeight) ?? 1.1,
|
|
1144
|
+
titleLetterSpacing: num(p.titleLetterSpacing) ?? 0,
|
|
1145
|
+
position,
|
|
1146
|
+
align: p.alignment === "center" ? "center" : "left",
|
|
1147
|
+
fontFamily: opts.fontFamily
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
function clampRadius(radius, width, height) {
|
|
1151
|
+
return Math.min(radius, Math.min(width, height) / 2);
|
|
1152
|
+
}
|
|
1153
|
+
function num(v) {
|
|
1154
|
+
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
1155
|
+
}
|
|
1156
|
+
function color(hex) {
|
|
1157
|
+
if (typeof hex !== "string") return void 0;
|
|
1158
|
+
let h = hex.trim().replace(/^#/, "");
|
|
1159
|
+
if (h.length === 3) h = h.replace(/./g, (c) => c + c);
|
|
1160
|
+
if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(h)) return void 0;
|
|
1161
|
+
return "#" + h.toUpperCase();
|
|
1162
|
+
}
|
|
1163
|
+
function withAlpha(hex, alpha) {
|
|
1164
|
+
const h = (color(hex) ?? "#000000").slice(1);
|
|
1165
|
+
const r = parseInt(h.slice(0, 2), 16);
|
|
1166
|
+
const g = parseInt(h.slice(2, 4), 16);
|
|
1167
|
+
const b = parseInt(h.slice(4, 6), 16);
|
|
1168
|
+
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
// src/ui/questions.tsx
|
|
1172
|
+
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
1173
|
+
function QuestionInput({ question, theme, value, onChange, autoFocus }) {
|
|
1174
|
+
const cfg = question.config;
|
|
1175
|
+
switch (cfg.kind) {
|
|
1176
|
+
case "scale":
|
|
1177
|
+
return /* @__PURE__ */ jsx2(ScaleInput, { min: cfg.min, max: cfg.max, minLabel: cfg.minLabel, maxLabel: cfg.maxLabel, theme, value: numValue(value), onPick: (n) => onChange({ value: n }) });
|
|
1178
|
+
case "stars":
|
|
1179
|
+
return /* @__PURE__ */ jsx2(StarsInput, { count: cfg.count, theme, value: numValue(value), onPick: (n) => onChange({ value: n }) });
|
|
1180
|
+
case "emoji":
|
|
1181
|
+
return /* @__PURE__ */ jsx2(EmojiInput, { options: cfg.options, theme, value: strValue(value), onPick: (v) => onChange({ value: v }) });
|
|
1182
|
+
case "thumbs":
|
|
1183
|
+
return /* @__PURE__ */ jsx2(ThumbsInput, { theme, value: strValue(value), onPick: (v) => onChange({ value: v }) });
|
|
1184
|
+
case "singleChoice":
|
|
1185
|
+
return /* @__PURE__ */ jsx2(ChoiceInput, { options: cfg.options, theme, value: value && "choice" in value ? value.choice : void 0, onPick: (v) => onChange({ choice: v }) });
|
|
1186
|
+
case "openText":
|
|
1187
|
+
return /* @__PURE__ */ jsx2(
|
|
1188
|
+
OpenTextInput,
|
|
1189
|
+
{
|
|
1190
|
+
placeholder: cfg.placeholder,
|
|
1191
|
+
maxLength: cfg.maxLength,
|
|
1192
|
+
theme,
|
|
1193
|
+
autoFocus,
|
|
1194
|
+
onText: (t) => onChange(t.trim().length > 0 ? { text: t.trim() } : void 0)
|
|
1195
|
+
}
|
|
1196
|
+
);
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
function isAnswerValid(question, value) {
|
|
1200
|
+
return question.required ? value !== void 0 : true;
|
|
1201
|
+
}
|
|
1202
|
+
function numValue(v) {
|
|
1203
|
+
return v && "value" in v && typeof v.value === "number" ? v.value : void 0;
|
|
1204
|
+
}
|
|
1205
|
+
function strValue(v) {
|
|
1206
|
+
return v && "value" in v && typeof v.value === "string" ? v.value : void 0;
|
|
1207
|
+
}
|
|
1208
|
+
function font(theme, size, weight = "400") {
|
|
1209
|
+
return { fontSize: size * theme.textScale, fontWeight: weight, fontFamily: theme.fontFamily };
|
|
1210
|
+
}
|
|
1211
|
+
var MAX_FONT_SCALE = 1.6;
|
|
1212
|
+
var CHIP_GAP = 8;
|
|
1213
|
+
var CHIP_MIN_SIDE = 44;
|
|
1214
|
+
function ScaleInput({ min, max, minLabel, maxLabel, theme, value, onPick }) {
|
|
1215
|
+
const [width, setWidth] = useState(0);
|
|
1216
|
+
const lo = Math.min(min, max);
|
|
1217
|
+
const hi = Math.max(min, max);
|
|
1218
|
+
const points = [];
|
|
1219
|
+
for (let i = lo; i <= hi; i++) points.push(i);
|
|
1220
|
+
const compact = points.length <= 7;
|
|
1221
|
+
const chipWidth = compact && width > 0 ? (width - CHIP_GAP * (points.length - 1)) / points.length : CHIP_MIN_SIDE;
|
|
1222
|
+
const chipHeight = compact ? Math.min(theme.controlHeight, chipWidth) : CHIP_MIN_SIDE;
|
|
1223
|
+
const hasLabels = !!minLabel || !!maxLabel;
|
|
1224
|
+
return /* @__PURE__ */ jsxs(View2, { onLayout: (e) => setWidth(e.nativeEvent.layout.width), children: [
|
|
1225
|
+
/* @__PURE__ */ jsx2(View2, { style: [styles2.scaleRow, !compact && styles2.wrap], children: width > 0 && points.map((n) => {
|
|
1226
|
+
const on = value === n;
|
|
1227
|
+
return /* @__PURE__ */ jsx2(
|
|
1228
|
+
Pressable2,
|
|
1229
|
+
{
|
|
1230
|
+
accessibilityRole: "button",
|
|
1231
|
+
accessibilityLabel: String(n),
|
|
1232
|
+
accessibilityState: { selected: on },
|
|
1233
|
+
onPress: () => onPick(n),
|
|
1234
|
+
style: ({ pressed }) => [
|
|
1235
|
+
styles2.chip,
|
|
1236
|
+
{
|
|
1237
|
+
width: compact ? chipWidth : void 0,
|
|
1238
|
+
minWidth: compact ? void 0 : CHIP_MIN_SIDE,
|
|
1239
|
+
height: chipHeight,
|
|
1240
|
+
borderRadius: clampRadius(theme.controlRadius, compact ? chipWidth : CHIP_MIN_SIDE, chipHeight),
|
|
1241
|
+
backgroundColor: on ? theme.accent : theme.surface,
|
|
1242
|
+
borderColor: on ? theme.accent : theme.border,
|
|
1243
|
+
opacity: pressed ? 0.85 : 1
|
|
1244
|
+
}
|
|
1245
|
+
],
|
|
1246
|
+
children: /* @__PURE__ */ jsx2(Text, { maxFontSizeMultiplier: MAX_FONT_SCALE, style: [font(theme, 16, "500"), { color: on ? theme.accentText : theme.text }], children: n })
|
|
1247
|
+
},
|
|
1248
|
+
n
|
|
1249
|
+
);
|
|
1250
|
+
}) }),
|
|
1251
|
+
hasLabels && /* @__PURE__ */ jsxs(View2, { style: styles2.endLabels, children: [
|
|
1252
|
+
/* @__PURE__ */ jsx2(Text, { style: [font(theme, 13), styles2.endLabel, { color: theme.secondaryText }], numberOfLines: 2, children: minLabel }),
|
|
1253
|
+
/* @__PURE__ */ jsx2(Text, { style: [font(theme, 13), styles2.endLabel, { color: theme.secondaryText, textAlign: "right" }], numberOfLines: 2, children: maxLabel })
|
|
1254
|
+
] })
|
|
1255
|
+
] });
|
|
1256
|
+
}
|
|
1257
|
+
function StarsInput({ count, theme, value, onPick }) {
|
|
1258
|
+
const stars = [];
|
|
1259
|
+
for (let i = 1; i <= Math.max(1, count); i++) stars.push(i);
|
|
1260
|
+
return /* @__PURE__ */ jsx2(View2, { style: styles2.starsRow, children: stars.map((n) => {
|
|
1261
|
+
const on = value !== void 0 && n <= value;
|
|
1262
|
+
return /* @__PURE__ */ jsx2(
|
|
1263
|
+
Pressable2,
|
|
1264
|
+
{
|
|
1265
|
+
accessibilityRole: "button",
|
|
1266
|
+
accessibilityLabel: `${n} star${n === 1 ? "" : "s"}`,
|
|
1267
|
+
accessibilityState: { selected: value === n },
|
|
1268
|
+
onPress: () => onPick(n),
|
|
1269
|
+
hitSlop: 4,
|
|
1270
|
+
style: styles2.star,
|
|
1271
|
+
children: /* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: { fontSize: 38, lineHeight: 46, color: theme.accent }, children: on ? "\u2605" : "\u2606" })
|
|
1272
|
+
},
|
|
1273
|
+
n
|
|
1274
|
+
);
|
|
1275
|
+
}) });
|
|
1276
|
+
}
|
|
1277
|
+
function EmojiInput({ options, theme, value, onPick }) {
|
|
1278
|
+
return /* @__PURE__ */ jsx2(View2, { style: styles2.emojiRow, children: options.map((o) => {
|
|
1279
|
+
const on = value === o.value;
|
|
1280
|
+
return /* @__PURE__ */ jsxs(
|
|
1281
|
+
Pressable2,
|
|
1282
|
+
{
|
|
1283
|
+
accessibilityRole: "button",
|
|
1284
|
+
accessibilityLabel: o.label || o.value,
|
|
1285
|
+
accessibilityState: { selected: on },
|
|
1286
|
+
onPress: () => onPick(o.value),
|
|
1287
|
+
style: ({ pressed }) => [
|
|
1288
|
+
styles2.emojiCell,
|
|
1289
|
+
{
|
|
1290
|
+
borderRadius: theme.controlRadius,
|
|
1291
|
+
backgroundColor: on ? theme.accentTintStrong : theme.surface,
|
|
1292
|
+
borderColor: on ? theme.accent : theme.border,
|
|
1293
|
+
opacity: pressed ? 0.85 : 1
|
|
1294
|
+
}
|
|
1295
|
+
],
|
|
1296
|
+
children: [
|
|
1297
|
+
/* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: styles2.emojiGlyph, children: o.emoji }),
|
|
1298
|
+
!!o.label && /* @__PURE__ */ jsx2(Text, { maxFontSizeMultiplier: MAX_FONT_SCALE, style: [font(theme, 13), { color: theme.secondaryText, textAlign: "center" }], children: o.label })
|
|
1299
|
+
]
|
|
1300
|
+
},
|
|
1301
|
+
o.value
|
|
1302
|
+
);
|
|
1303
|
+
}) });
|
|
1304
|
+
}
|
|
1305
|
+
function ThumbsInput({ theme, value, onPick }) {
|
|
1306
|
+
const sides = [
|
|
1307
|
+
{ value: "up", emoji: "\u{1F44D}", label: "Thumbs up" },
|
|
1308
|
+
{ value: "down", emoji: "\u{1F44E}", label: "Thumbs down" }
|
|
1309
|
+
];
|
|
1310
|
+
return /* @__PURE__ */ jsx2(View2, { style: styles2.thumbsRow, children: sides.map((s) => {
|
|
1311
|
+
const on = value === s.value;
|
|
1312
|
+
return /* @__PURE__ */ jsx2(
|
|
1313
|
+
Pressable2,
|
|
1314
|
+
{
|
|
1315
|
+
accessibilityRole: "button",
|
|
1316
|
+
accessibilityLabel: s.label,
|
|
1317
|
+
accessibilityState: { selected: on },
|
|
1318
|
+
onPress: () => onPick(s.value),
|
|
1319
|
+
style: ({ pressed }) => [
|
|
1320
|
+
styles2.thumb,
|
|
1321
|
+
{
|
|
1322
|
+
height: theme.controlHeight,
|
|
1323
|
+
borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),
|
|
1324
|
+
backgroundColor: on ? theme.accent : theme.surface,
|
|
1325
|
+
borderColor: on ? theme.accent : theme.border,
|
|
1326
|
+
opacity: pressed ? 0.85 : 1
|
|
1327
|
+
}
|
|
1328
|
+
],
|
|
1329
|
+
children: /* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: styles2.thumbGlyph, children: s.emoji })
|
|
1330
|
+
},
|
|
1331
|
+
s.value
|
|
1332
|
+
);
|
|
1333
|
+
}) });
|
|
1334
|
+
}
|
|
1335
|
+
function ChoiceInput({ options, theme, value, onPick }) {
|
|
1336
|
+
return /* @__PURE__ */ jsx2(View2, { style: styles2.choices, children: options.map((o) => {
|
|
1337
|
+
const on = value === o.value;
|
|
1338
|
+
return /* @__PURE__ */ jsxs(
|
|
1339
|
+
Pressable2,
|
|
1340
|
+
{
|
|
1341
|
+
accessibilityRole: "radio",
|
|
1342
|
+
accessibilityLabel: o.label,
|
|
1343
|
+
accessibilityState: { checked: on },
|
|
1344
|
+
onPress: () => onPick(o.value),
|
|
1345
|
+
style: ({ pressed }) => [
|
|
1346
|
+
styles2.choice,
|
|
1347
|
+
{
|
|
1348
|
+
minHeight: theme.controlHeight,
|
|
1349
|
+
borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),
|
|
1350
|
+
backgroundColor: on ? theme.accentTint : theme.surface,
|
|
1351
|
+
borderColor: on ? theme.accent : theme.border,
|
|
1352
|
+
opacity: pressed ? 0.85 : 1
|
|
1353
|
+
}
|
|
1354
|
+
],
|
|
1355
|
+
children: [
|
|
1356
|
+
/* @__PURE__ */ jsx2(Text, { style: [font(theme, 16), styles2.choiceLabel, { color: theme.text }], children: o.label }),
|
|
1357
|
+
/* @__PURE__ */ jsx2(
|
|
1358
|
+
View2,
|
|
1359
|
+
{
|
|
1360
|
+
style: [
|
|
1361
|
+
styles2.radio,
|
|
1362
|
+
on ? { backgroundColor: theme.accent, borderColor: theme.accent } : { borderColor: theme.border }
|
|
1363
|
+
],
|
|
1364
|
+
children: on && /* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: [styles2.radioCheck, { color: theme.accentText }], children: "\u2713" })
|
|
1365
|
+
}
|
|
1366
|
+
)
|
|
1367
|
+
]
|
|
1368
|
+
},
|
|
1369
|
+
o.value
|
|
1370
|
+
);
|
|
1371
|
+
}) });
|
|
1372
|
+
}
|
|
1373
|
+
function OpenTextInput({ placeholder, maxLength, theme, autoFocus, onText }) {
|
|
1374
|
+
const [text, setText] = useState("");
|
|
1375
|
+
const [focused, setFocused] = useState(false);
|
|
1376
|
+
return /* @__PURE__ */ jsxs(View2, { children: [
|
|
1377
|
+
/* @__PURE__ */ jsx2(
|
|
1378
|
+
TextInput,
|
|
1379
|
+
{
|
|
1380
|
+
multiline: true,
|
|
1381
|
+
autoFocus,
|
|
1382
|
+
value: text,
|
|
1383
|
+
onChangeText: (t) => {
|
|
1384
|
+
setText(t);
|
|
1385
|
+
onText(t);
|
|
1386
|
+
},
|
|
1387
|
+
onFocus: () => setFocused(true),
|
|
1388
|
+
onBlur: () => setFocused(false),
|
|
1389
|
+
placeholder,
|
|
1390
|
+
placeholderTextColor: theme.secondaryText,
|
|
1391
|
+
maxLength,
|
|
1392
|
+
textAlignVertical: "top",
|
|
1393
|
+
style: [
|
|
1394
|
+
font(theme, 16),
|
|
1395
|
+
styles2.textArea,
|
|
1396
|
+
{
|
|
1397
|
+
minHeight: theme.controlHeight * 2,
|
|
1398
|
+
borderRadius: theme.controlRadius,
|
|
1399
|
+
borderColor: focused ? theme.accent : theme.border,
|
|
1400
|
+
backgroundColor: theme.surface,
|
|
1401
|
+
color: theme.text
|
|
1402
|
+
}
|
|
1403
|
+
]
|
|
1404
|
+
}
|
|
1405
|
+
),
|
|
1406
|
+
maxLength !== void 0 && /* @__PURE__ */ jsxs(Text, { style: [font(theme, 13), styles2.counter, { color: theme.secondaryText }], children: [
|
|
1407
|
+
text.length,
|
|
1408
|
+
"/",
|
|
1409
|
+
maxLength
|
|
1410
|
+
] })
|
|
1411
|
+
] });
|
|
1412
|
+
}
|
|
1413
|
+
var styles2 = StyleSheet2.create({
|
|
1414
|
+
scaleRow: { flexDirection: "row", gap: CHIP_GAP },
|
|
1415
|
+
wrap: { flexWrap: "wrap", justifyContent: "center" },
|
|
1416
|
+
chip: { borderWidth: 1, alignItems: "center", justifyContent: "center", paddingHorizontal: 10 },
|
|
1417
|
+
endLabels: { flexDirection: "row", gap: 12, marginTop: 10, paddingHorizontal: 2 },
|
|
1418
|
+
endLabel: { flex: 1 },
|
|
1419
|
+
starsRow: { flexDirection: "row", justifyContent: "center", gap: 6, height: 48, alignItems: "center" },
|
|
1420
|
+
star: { paddingHorizontal: 2 },
|
|
1421
|
+
emojiRow: { flexDirection: "row", flexWrap: "wrap", justifyContent: "center", columnGap: 10, rowGap: 12 },
|
|
1422
|
+
emojiCell: { minWidth: 64, paddingVertical: 8, paddingHorizontal: 10, borderWidth: 1, alignItems: "center", gap: 2 },
|
|
1423
|
+
emojiGlyph: { fontSize: 32, lineHeight: 40 },
|
|
1424
|
+
thumbsRow: { flexDirection: "row", gap: 16 },
|
|
1425
|
+
thumb: { flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" },
|
|
1426
|
+
thumbGlyph: { fontSize: 32, lineHeight: 40 },
|
|
1427
|
+
choices: { gap: 10 },
|
|
1428
|
+
choice: { flexDirection: "row", alignItems: "center", borderWidth: 1, paddingVertical: 14, paddingHorizontal: 16, gap: 12 },
|
|
1429
|
+
choiceLabel: { flex: 1 },
|
|
1430
|
+
radio: { width: 22, height: 22, borderRadius: 11, borderWidth: 1.5, alignItems: "center", justifyContent: "center" },
|
|
1431
|
+
radioCheck: { fontSize: 13, lineHeight: 16, fontWeight: "700" },
|
|
1432
|
+
textArea: { borderWidth: 1, paddingHorizontal: 16, paddingTop: 12, paddingBottom: 12 },
|
|
1433
|
+
counter: { marginTop: 6, textAlign: "right" }
|
|
1434
|
+
});
|
|
1435
|
+
|
|
1436
|
+
// src/ui/SurveyCard.tsx
|
|
1437
|
+
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
1438
|
+
var CLIP_ROOM = 4;
|
|
1439
|
+
var THANKS_MS = 1300;
|
|
1440
|
+
var SurveyCard = forwardRef(function SurveyCard2({ survey, theme, variant, bottomInset, onResult, onClose }, ref) {
|
|
1441
|
+
const questions = useMemo(() => [...survey.questions].sort((a, b) => a.order - b.order), [survey]);
|
|
1442
|
+
const dismissible = survey.dismissible !== false;
|
|
1443
|
+
const [index, setIndex] = useState2(0);
|
|
1444
|
+
const committed = useRef({});
|
|
1445
|
+
const [current, setCurrent] = useState2(void 0);
|
|
1446
|
+
const [done, setDone] = useState2(false);
|
|
1447
|
+
const [height, setHeight] = useState2(0);
|
|
1448
|
+
const reported = useRef(false);
|
|
1449
|
+
const closeTimer = useRef(null);
|
|
1450
|
+
useEffect(() => () => {
|
|
1451
|
+
if (closeTimer.current) clearTimeout(closeTimer.current);
|
|
1452
|
+
}, []);
|
|
1453
|
+
const question = questions[index];
|
|
1454
|
+
const isLast = index >= questions.length - 1;
|
|
1455
|
+
const valid = question ? isAnswerValid(question, current) : false;
|
|
1456
|
+
function collected() {
|
|
1457
|
+
return questions.filter((q) => committed.current[q.id] !== void 0).map((q) => ({ questionId: q.id, value: committed.current[q.id] }));
|
|
1458
|
+
}
|
|
1459
|
+
function report(completed) {
|
|
1460
|
+
if (reported.current) return false;
|
|
1461
|
+
reported.current = true;
|
|
1462
|
+
onResult({ answers: collected(), completed, dismissed: !completed });
|
|
1463
|
+
return true;
|
|
1464
|
+
}
|
|
1465
|
+
function dismiss() {
|
|
1466
|
+
if (report(false)) onClose();
|
|
1467
|
+
}
|
|
1468
|
+
useImperativeHandle(ref, () => ({ dismiss }));
|
|
1469
|
+
useEffect(() => {
|
|
1470
|
+
if (questions.length === 0) dismiss();
|
|
1471
|
+
}, []);
|
|
1472
|
+
function advance2() {
|
|
1473
|
+
if (!question || !valid) return;
|
|
1474
|
+
if (current !== void 0) committed.current[question.id] = current;
|
|
1475
|
+
if (!isLast) {
|
|
1476
|
+
setIndex(index + 1);
|
|
1477
|
+
setCurrent(void 0);
|
|
1478
|
+
return;
|
|
1479
|
+
}
|
|
1480
|
+
if (report(true)) {
|
|
1481
|
+
setDone(true);
|
|
1482
|
+
closeTimer.current = setTimeout(onClose, THANKS_MS);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
const pad = theme.spacing + 4;
|
|
1486
|
+
const topInset = variant === "sheet" ? pad + 12 : pad;
|
|
1487
|
+
const hasProgress = questions.length > 1;
|
|
1488
|
+
if (!question) return null;
|
|
1489
|
+
if (done) {
|
|
1490
|
+
const custom = survey.successMessage?.trim();
|
|
1491
|
+
return (
|
|
1492
|
+
// Keep the card's height so the sheet doesn't jump when the content swaps.
|
|
1493
|
+
/* @__PURE__ */ jsx3(View3, { style: [styles3.thanks, { minHeight: height, padding: pad }], accessibilityLiveRegion: "polite", children: /* @__PURE__ */ jsx3(FadeIn, { children: /* @__PURE__ */ jsxs2(View3, { style: styles3.thanksStack, children: [
|
|
1494
|
+
/* @__PURE__ */ jsx3(View3, { style: [styles3.check, { backgroundColor: theme.accent }], children: /* @__PURE__ */ jsx3(Text2, { allowFontScaling: false, style: [styles3.checkGlyph, { color: theme.accentText }], children: "\u2713" }) }),
|
|
1495
|
+
/* @__PURE__ */ jsx3(Text2, { style: [promptStyle(theme), { color: theme.text, textAlign: "center", marginTop: theme.spacing }], children: custom || "Thanks!" })
|
|
1496
|
+
] }) }) })
|
|
1497
|
+
);
|
|
1498
|
+
}
|
|
1499
|
+
return /* @__PURE__ */ jsxs2(View3, { onLayout: (e) => setHeight(e.nativeEvent.layout.height), style: styles3.card, children: [
|
|
1500
|
+
hasProgress && /* @__PURE__ */ jsxs2(Text2, { style: [font(theme, 13), { color: theme.secondaryText, marginTop: topInset, marginHorizontal: pad }], children: [
|
|
1501
|
+
index + 1,
|
|
1502
|
+
" of ",
|
|
1503
|
+
questions.length
|
|
1504
|
+
] }),
|
|
1505
|
+
/* @__PURE__ */ jsx3(
|
|
1506
|
+
ScrollView,
|
|
1507
|
+
{
|
|
1508
|
+
style: styles3.scroll,
|
|
1509
|
+
contentContainerStyle: { paddingHorizontal: pad, paddingTop: hasProgress ? theme.spacing : topInset, paddingBottom: CLIP_ROOM, gap: theme.spacing + 8 },
|
|
1510
|
+
keyboardShouldPersistTaps: "handled",
|
|
1511
|
+
showsVerticalScrollIndicator: false,
|
|
1512
|
+
bounces: false,
|
|
1513
|
+
children: /* @__PURE__ */ jsx3(FadeIn, { children: /* @__PURE__ */ jsxs2(View3, { style: { gap: theme.spacing + 8 }, children: [
|
|
1514
|
+
/* @__PURE__ */ jsx3(Text2, { accessibilityRole: "header", style: [promptStyle(theme), { color: theme.text, paddingRight: dismissible ? 48 : 0 }], children: question.prompt }),
|
|
1515
|
+
/* @__PURE__ */ jsx3(QuestionInput, { question, theme, value: current, onChange: setCurrent, autoFocus: variant !== "inline" })
|
|
1516
|
+
] }) }, question.id)
|
|
1517
|
+
}
|
|
1518
|
+
),
|
|
1519
|
+
/* @__PURE__ */ jsx3(
|
|
1520
|
+
Pressable3,
|
|
1521
|
+
{
|
|
1522
|
+
accessibilityRole: "button",
|
|
1523
|
+
accessibilityState: { disabled: !valid },
|
|
1524
|
+
disabled: !valid,
|
|
1525
|
+
onPress: advance2,
|
|
1526
|
+
style: ({ pressed }) => [
|
|
1527
|
+
styles3.button,
|
|
1528
|
+
{
|
|
1529
|
+
height: theme.controlHeight,
|
|
1530
|
+
marginTop: theme.spacing - CLIP_ROOM,
|
|
1531
|
+
marginHorizontal: pad,
|
|
1532
|
+
marginBottom: Math.max(pad, bottomInset ?? 0),
|
|
1533
|
+
borderRadius: Math.min(theme.controlRadius, theme.controlHeight / 2),
|
|
1534
|
+
backgroundColor: theme.accent,
|
|
1535
|
+
opacity: !valid ? 0.45 : pressed ? 0.9 : 1
|
|
1536
|
+
}
|
|
1537
|
+
],
|
|
1538
|
+
children: /* @__PURE__ */ jsx3(Text2, { maxFontSizeMultiplier: 1.6, style: [font(theme, 16, "600"), { color: theme.accentText }], children: isLast ? "Submit" : "Next" })
|
|
1539
|
+
}
|
|
1540
|
+
),
|
|
1541
|
+
dismissible && /* @__PURE__ */ jsx3(
|
|
1542
|
+
CloseButton,
|
|
1543
|
+
{
|
|
1544
|
+
theme,
|
|
1545
|
+
onPress: dismiss,
|
|
1546
|
+
style: Platform4.OS === "ios" ? { top: pad, right: pad } : { top: variant === "sheet" ? pad + 4 : pad - 6, right: pad - 6 }
|
|
1547
|
+
}
|
|
1548
|
+
)
|
|
1549
|
+
] });
|
|
1550
|
+
});
|
|
1551
|
+
function promptStyle(theme) {
|
|
1552
|
+
return {
|
|
1553
|
+
fontSize: theme.titleSize,
|
|
1554
|
+
fontWeight: theme.titleWeight,
|
|
1555
|
+
fontFamily: theme.fontFamily,
|
|
1556
|
+
// iOS applies `lineHeightMultiple` to the font's natural line height (~1.2em).
|
|
1557
|
+
lineHeight: Math.round(theme.titleSize * 1.2 * theme.titleLineHeight),
|
|
1558
|
+
letterSpacing: theme.titleLetterSpacing,
|
|
1559
|
+
textAlign: theme.align
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
function FadeIn({ children }) {
|
|
1563
|
+
const opacity = useRef(new Animated.Value(0)).current;
|
|
1564
|
+
useEffect(() => {
|
|
1565
|
+
Animated.timing(opacity, { toValue: 1, duration: 220, useNativeDriver: false }).start();
|
|
1566
|
+
}, [opacity]);
|
|
1567
|
+
return /* @__PURE__ */ jsx3(Animated.View, { style: { opacity }, children });
|
|
1568
|
+
}
|
|
1569
|
+
var styles3 = StyleSheet3.create({
|
|
1570
|
+
card: { flexShrink: 1 },
|
|
1571
|
+
scroll: { flexGrow: 0, flexShrink: 1 },
|
|
1572
|
+
button: { alignItems: "center", justifyContent: "center" },
|
|
1573
|
+
thanks: { alignItems: "center", justifyContent: "center" },
|
|
1574
|
+
thanksStack: { alignItems: "center" },
|
|
1575
|
+
check: { width: 48, height: 48, borderRadius: 24, alignItems: "center", justifyContent: "center" },
|
|
1576
|
+
checkGlyph: { fontSize: 26, fontWeight: "700", lineHeight: 30 }
|
|
1577
|
+
});
|
|
1578
|
+
|
|
1579
|
+
// src/ui/SurveyModal.tsx
|
|
1580
|
+
import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
|
|
1581
|
+
function SurveyModal({ survey, theme: projectTheme, fontFamily, onResult, onClose }) {
|
|
1582
|
+
const scheme = useColorScheme() === "dark" ? "dark" : "light";
|
|
1583
|
+
const theme = useMemo2(
|
|
1584
|
+
() => resolveTheme(projectTheme, { scheme, presentation: survey?.presentation, fontFamily }),
|
|
1585
|
+
[projectTheme, scheme, survey?.presentation, fontFamily]
|
|
1586
|
+
);
|
|
1587
|
+
const card = useRef2(null);
|
|
1588
|
+
if (!survey) return null;
|
|
1589
|
+
return /* @__PURE__ */ jsx4(
|
|
1590
|
+
Modal,
|
|
1591
|
+
{
|
|
1592
|
+
visible: true,
|
|
1593
|
+
transparent: true,
|
|
1594
|
+
animationType: "none",
|
|
1595
|
+
statusBarTranslucent: true,
|
|
1596
|
+
navigationBarTranslucent: true,
|
|
1597
|
+
onRequestClose: () => {
|
|
1598
|
+
if (survey.dismissible !== false) card.current?.dismiss();
|
|
1599
|
+
},
|
|
1600
|
+
children: /* @__PURE__ */ jsx4(SafeAreaProvider, { initialMetrics: initialWindowMetrics, children: /* @__PURE__ */ jsx4(Presentation, { card, survey, theme, onResult, onClose }, survey.id) })
|
|
1601
|
+
}
|
|
1602
|
+
);
|
|
1603
|
+
}
|
|
1604
|
+
function Presentation({ card, survey, theme, onResult, onClose }) {
|
|
1605
|
+
const insets = useSafeAreaInsets();
|
|
1606
|
+
const window = useWindowDimensions();
|
|
1607
|
+
const isSheet = theme.position === "bottom";
|
|
1608
|
+
const dismissible = survey.dismissible !== false;
|
|
1609
|
+
const floating = isSheet && usesGlassChrome && insets.bottom > 0;
|
|
1610
|
+
const floatScale = floating ? (window.width - 2 * FLOATING_SHEET_INSET) / window.width : 1;
|
|
1611
|
+
const sheetRadius = floating && theme.nativeSheetCorners ? FLOATING_SHEET_RADIUS / floatScale : theme.sheetCornerRadius;
|
|
1612
|
+
const scrim = isSheet ? Platform5.OS === "ios" ? "rgba(0, 0, 0, 0.2)" : "rgba(0, 0, 0, 0.32)" : theme.scrim;
|
|
1613
|
+
const progress = useRef2(new Animated2.Value(0)).current;
|
|
1614
|
+
const drag = useRef2(new Animated2.Value(0)).current;
|
|
1615
|
+
const [sheetHeight, setSheetHeight] = useState3(window.height);
|
|
1616
|
+
const sheetTop = useRef2(window.height);
|
|
1617
|
+
const [keyboard, setKeyboard] = useState3(0);
|
|
1618
|
+
const keyboardUp = keyboard > 0;
|
|
1619
|
+
const insetForKeyboard = isSheet && Platform5.OS === "ios";
|
|
1620
|
+
const keyboardSpacer = useRef2(new Animated2.Value(0)).current;
|
|
1621
|
+
const keyboardDuration = useRef2(250);
|
|
1622
|
+
useEffect2(() => {
|
|
1623
|
+
Animated2.timing(progress, {
|
|
1624
|
+
toValue: 1,
|
|
1625
|
+
duration: isSheet ? 320 : 280,
|
|
1626
|
+
easing: Easing.out(Easing.cubic),
|
|
1627
|
+
useNativeDriver: false
|
|
1628
|
+
}).start();
|
|
1629
|
+
}, [progress, isSheet]);
|
|
1630
|
+
useEffect2(() => {
|
|
1631
|
+
const update = (height, duration) => {
|
|
1632
|
+
if (duration) keyboardDuration.current = duration;
|
|
1633
|
+
setKeyboard(height);
|
|
1634
|
+
};
|
|
1635
|
+
const show = Keyboard.addListener(
|
|
1636
|
+
Platform5.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow",
|
|
1637
|
+
(e) => update(e.endCoordinates.height, e.duration)
|
|
1638
|
+
);
|
|
1639
|
+
const hide = Keyboard.addListener(Platform5.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide", (e) => update(0, e.duration));
|
|
1640
|
+
return () => {
|
|
1641
|
+
show.remove();
|
|
1642
|
+
hide.remove();
|
|
1643
|
+
};
|
|
1644
|
+
}, []);
|
|
1645
|
+
const spacerTarget = insetForKeyboard && keyboard > 0 ? (keyboard - (floating ? FLOATING_SHEET_INSET : 0)) / floatScale : 0;
|
|
1646
|
+
useEffect2(() => {
|
|
1647
|
+
Animated2.timing(keyboardSpacer, {
|
|
1648
|
+
toValue: spacerTarget,
|
|
1649
|
+
duration: keyboardDuration.current,
|
|
1650
|
+
easing: Easing.bezier(0.17, 0.59, 0.4, 0.77),
|
|
1651
|
+
// close to the iOS keyboard curve
|
|
1652
|
+
useNativeDriver: false
|
|
1653
|
+
}).start();
|
|
1654
|
+
}, [keyboardSpacer, spacerTarget]);
|
|
1655
|
+
function animateOut() {
|
|
1656
|
+
Keyboard.dismiss();
|
|
1657
|
+
Animated2.timing(progress, { toValue: 0, duration: 240, easing: Easing.in(Easing.cubic), useNativeDriver: false }).start(() => onClose?.());
|
|
1658
|
+
}
|
|
1659
|
+
function requestDismiss() {
|
|
1660
|
+
if (dismissible) card.current?.dismiss();
|
|
1661
|
+
}
|
|
1662
|
+
const pan = useMemo2(
|
|
1663
|
+
() => PanResponder.create({
|
|
1664
|
+
// Own touches that start in the sheet's header band (grabber, progress) from
|
|
1665
|
+
// the start: otherwise a responder higher up the tree (e.g. a draggable
|
|
1666
|
+
// dev overlay at the app root) claims them and the sheet never sees the
|
|
1667
|
+
// drag. Buttons in the band (close) are deeper and still win taps.
|
|
1668
|
+
onStartShouldSetPanResponder: (e) => isSheet && dismissible && e.nativeEvent.pageY - sheetTop.current < DRAG_HEADER_HEIGHT,
|
|
1669
|
+
// Elsewhere, take over a downward drag nothing inside wanted.
|
|
1670
|
+
onMoveShouldSetPanResponder: (_, g) => isSheet && dismissible && isDownwardDrag(g),
|
|
1671
|
+
onPanResponderTerminationRequest: () => false,
|
|
1672
|
+
onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
|
|
1673
|
+
onPanResponderRelease: (_, g) => {
|
|
1674
|
+
if (isDownwardDrag(g) && (g.dy > 120 || g.vy > 1)) requestDismiss();
|
|
1675
|
+
else Animated2.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start();
|
|
1676
|
+
},
|
|
1677
|
+
onPanResponderTerminate: () => Animated2.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start()
|
|
1678
|
+
}),
|
|
1679
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
1680
|
+
[isSheet, dismissible]
|
|
1681
|
+
);
|
|
1682
|
+
const cardContent = /* @__PURE__ */ jsx4(
|
|
1683
|
+
SurveyCard,
|
|
1684
|
+
{
|
|
1685
|
+
ref: card,
|
|
1686
|
+
survey,
|
|
1687
|
+
theme,
|
|
1688
|
+
variant: isSheet ? "sheet" : "dialog",
|
|
1689
|
+
bottomInset: isSheet && !keyboardUp ? insets.bottom : 0,
|
|
1690
|
+
onResult: (r) => onResult?.(r),
|
|
1691
|
+
onClose: animateOut
|
|
1692
|
+
}
|
|
1693
|
+
);
|
|
1694
|
+
return /* @__PURE__ */ jsxs3(View4, { style: StyleSheet4.absoluteFill, accessibilityViewIsModal: true, children: [
|
|
1695
|
+
/* @__PURE__ */ jsx4(Animated2.View, { style: [StyleSheet4.absoluteFill, { backgroundColor: scrim, opacity: progress }], children: /* @__PURE__ */ jsx4(
|
|
1696
|
+
Pressable4,
|
|
1697
|
+
{
|
|
1698
|
+
style: StyleSheet4.absoluteFill,
|
|
1699
|
+
onPress: requestDismiss,
|
|
1700
|
+
accessible: false,
|
|
1701
|
+
importantForAccessibility: "no"
|
|
1702
|
+
}
|
|
1703
|
+
) }),
|
|
1704
|
+
/* @__PURE__ */ jsx4(
|
|
1705
|
+
KeyboardAvoidingView,
|
|
1706
|
+
{
|
|
1707
|
+
behavior: insetForKeyboard ? void 0 : Platform5.OS === "ios" ? "padding" : "height",
|
|
1708
|
+
style: [styles4.fill, isSheet ? styles4.bottom : [styles4.center, { paddingTop: insets.top }]],
|
|
1709
|
+
pointerEvents: "box-none",
|
|
1710
|
+
children: isSheet ? /* @__PURE__ */ jsxs3(
|
|
1711
|
+
Animated2.View,
|
|
1712
|
+
{
|
|
1713
|
+
...pan.panHandlers,
|
|
1714
|
+
onLayout: (e) => {
|
|
1715
|
+
setSheetHeight(e.nativeEvent.layout.height);
|
|
1716
|
+
sheetTop.current = e.nativeEvent.layout.y;
|
|
1717
|
+
},
|
|
1718
|
+
style: [
|
|
1719
|
+
styles4.sheet,
|
|
1720
|
+
shadow,
|
|
1721
|
+
floating ? {
|
|
1722
|
+
borderRadius: sheetRadius,
|
|
1723
|
+
borderCurve: "continuous",
|
|
1724
|
+
borderWidth: StyleSheet4.hairlineWidth / floatScale,
|
|
1725
|
+
borderColor: theme.dark ? "rgba(255, 255, 255, 0.14)" : "rgba(0, 0, 0, 0.18)"
|
|
1726
|
+
} : { borderTopLeftRadius: sheetRadius, borderTopRightRadius: sheetRadius, borderCurve: "continuous" },
|
|
1727
|
+
{
|
|
1728
|
+
maxHeight: window.height - insets.top - 24,
|
|
1729
|
+
backgroundColor: theme.surface,
|
|
1730
|
+
transform: [
|
|
1731
|
+
{
|
|
1732
|
+
translateY: Animated2.add(
|
|
1733
|
+
progress.interpolate({
|
|
1734
|
+
inputRange: [0, 1],
|
|
1735
|
+
// Shown: scaling about the center lifts the bottom edge by
|
|
1736
|
+
// h(1-s)/2; shift so it rests FLOATING_SHEET_INSET above the screen edge.
|
|
1737
|
+
outputRange: [sheetHeight, floating ? sheetHeight * (1 - floatScale) / 2 - FLOATING_SHEET_INSET : 0]
|
|
1738
|
+
}),
|
|
1739
|
+
drag
|
|
1740
|
+
)
|
|
1741
|
+
},
|
|
1742
|
+
{ scale: floatScale }
|
|
1743
|
+
]
|
|
1744
|
+
}
|
|
1745
|
+
],
|
|
1746
|
+
children: [
|
|
1747
|
+
/* @__PURE__ */ jsx4(View4, { style: [styles4.grabber, { backgroundColor: theme.secondaryText }] }),
|
|
1748
|
+
cardContent,
|
|
1749
|
+
insetForKeyboard && /* @__PURE__ */ jsx4(Animated2.View, { style: { height: keyboardSpacer } })
|
|
1750
|
+
]
|
|
1751
|
+
}
|
|
1752
|
+
) : /* @__PURE__ */ jsx4(
|
|
1753
|
+
Animated2.View,
|
|
1754
|
+
{
|
|
1755
|
+
style: [
|
|
1756
|
+
styles4.dialog,
|
|
1757
|
+
shadow,
|
|
1758
|
+
{
|
|
1759
|
+
maxHeight: window.height - insets.top - insets.bottom - 48,
|
|
1760
|
+
marginBottom: insets.bottom,
|
|
1761
|
+
backgroundColor: theme.surface,
|
|
1762
|
+
borderRadius: theme.cornerRadius,
|
|
1763
|
+
borderCurve: "continuous",
|
|
1764
|
+
opacity: progress,
|
|
1765
|
+
transform: [{ scale: progress.interpolate({ inputRange: [0, 1], outputRange: [0.94, 1] }) }]
|
|
1766
|
+
}
|
|
1767
|
+
],
|
|
1768
|
+
children: cardContent
|
|
1769
|
+
}
|
|
1770
|
+
)
|
|
1771
|
+
}
|
|
1772
|
+
)
|
|
1773
|
+
] });
|
|
1774
|
+
}
|
|
1775
|
+
var DRAG_HEADER_HEIGHT = 72;
|
|
1776
|
+
function isDownwardDrag(g) {
|
|
1777
|
+
return g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx);
|
|
1778
|
+
}
|
|
1779
|
+
var shadow = {
|
|
1780
|
+
shadowColor: "#000",
|
|
1781
|
+
shadowOpacity: 0.18,
|
|
1782
|
+
shadowRadius: 24,
|
|
1783
|
+
shadowOffset: { width: 0, height: -4 },
|
|
1784
|
+
elevation: 16
|
|
1785
|
+
};
|
|
1786
|
+
var styles4 = StyleSheet4.create({
|
|
1787
|
+
fill: { flex: 1 },
|
|
1788
|
+
bottom: { justifyContent: "flex-end" },
|
|
1789
|
+
center: { justifyContent: "center", paddingHorizontal: 20 },
|
|
1790
|
+
sheet: { width: "100%", maxWidth: 640, alignSelf: "center" },
|
|
1791
|
+
dialog: { width: "100%", maxWidth: 480, alignSelf: "center", overflow: "hidden" },
|
|
1792
|
+
grabber: { position: "absolute", top: 6, alignSelf: "center", width: 36, height: 5, borderRadius: 3, opacity: 0.35, zIndex: 1 }
|
|
1793
|
+
});
|
|
1794
|
+
|
|
1795
|
+
// src/provider.tsx
|
|
1796
|
+
import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
|
|
1797
|
+
var MicroSurveysContext = createContext({ instance: null });
|
|
1798
|
+
function MicroSurveysProvider({ apiKey, apiBaseURL, instance, autoStart = true, fontFamily, children }) {
|
|
1799
|
+
const [owned] = useState4(() => !instance && apiKey ? new MicroSurveys({ apiKey, apiBaseURL }) : null);
|
|
1800
|
+
const ms = instance ?? owned;
|
|
1801
|
+
useEffect3(() => {
|
|
1802
|
+
if (!ms || !autoStart) return;
|
|
1803
|
+
ms.start();
|
|
1804
|
+
return () => owned?.stop();
|
|
1805
|
+
}, [ms, owned, autoStart]);
|
|
1806
|
+
const value = useMemo3(() => ({ instance: ms, fontFamily }), [ms, fontFamily]);
|
|
1807
|
+
return /* @__PURE__ */ jsxs4(MicroSurveysContext.Provider, { value, children: [
|
|
1808
|
+
children,
|
|
1809
|
+
ms && /* @__PURE__ */ jsx5(OverlayHost, { instance: ms, fontFamily })
|
|
1810
|
+
] });
|
|
1811
|
+
}
|
|
1812
|
+
function OverlayHost({ instance, fontFamily }) {
|
|
1813
|
+
const [current, setCurrent] = useState4(null);
|
|
1814
|
+
const queue = useRef3([]);
|
|
1815
|
+
const showing = useRef3(false);
|
|
1816
|
+
const nextId = useRef3(0);
|
|
1817
|
+
useEffect3(
|
|
1818
|
+
() => instance.onPresent((active) => {
|
|
1819
|
+
if (showing.current) {
|
|
1820
|
+
queue.current.push(active);
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1823
|
+
showing.current = true;
|
|
1824
|
+
setCurrent({ active, id: nextId.current++ });
|
|
1825
|
+
}),
|
|
1826
|
+
[instance]
|
|
1827
|
+
);
|
|
1828
|
+
function showNext() {
|
|
1829
|
+
const next = queue.current.shift();
|
|
1830
|
+
if (next) {
|
|
1831
|
+
setCurrent({ active: next, id: nextId.current++ });
|
|
1832
|
+
} else {
|
|
1833
|
+
showing.current = false;
|
|
1834
|
+
setCurrent(null);
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
return /* @__PURE__ */ jsx5(
|
|
1838
|
+
SurveyModal,
|
|
1839
|
+
{
|
|
1840
|
+
survey: current?.active.survey ?? null,
|
|
1841
|
+
theme: instance.getTheme(),
|
|
1842
|
+
fontFamily,
|
|
1843
|
+
onResult: (result) => current?.active.close(result),
|
|
1844
|
+
onClose: showNext
|
|
1845
|
+
},
|
|
1846
|
+
current?.id ?? "none"
|
|
1847
|
+
);
|
|
1848
|
+
}
|
|
1849
|
+
function useMicroSurveysInstance() {
|
|
1850
|
+
return useContext(MicroSurveysContext).instance;
|
|
1851
|
+
}
|
|
1852
|
+
function useMicroSurveys() {
|
|
1853
|
+
const instance = useMicroSurveysInstance();
|
|
1854
|
+
return useMemo3(
|
|
1855
|
+
() => ({
|
|
1856
|
+
instance,
|
|
1857
|
+
track: (name, properties) => instance?.track(name, properties),
|
|
1858
|
+
identify: (userId, properties) => instance?.identify(userId, properties),
|
|
1859
|
+
refresh: () => instance?.refreshConfig()
|
|
1860
|
+
}),
|
|
1861
|
+
[instance]
|
|
1862
|
+
);
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
// src/MicroSurvey.tsx
|
|
1866
|
+
import { useContext as useContext2, useEffect as useEffect4, useMemo as useMemo4, useRef as useRef4, useState as useState5 } from "react";
|
|
1867
|
+
import { View as View5, useColorScheme as useColorScheme2 } from "react-native";
|
|
1868
|
+
import { jsx as jsx6 } from "react/jsx-runtime";
|
|
1869
|
+
function MicroSurvey({ surveyId, onComplete, style }) {
|
|
1870
|
+
const { instance, fontFamily } = useContext2(MicroSurveysContext);
|
|
1871
|
+
const scheme = useColorScheme2() === "dark" ? "dark" : "light";
|
|
1872
|
+
const [survey, setSurvey] = useState5(null);
|
|
1873
|
+
const [closed, setClosed] = useState5(false);
|
|
1874
|
+
const shownAt = useRef4(null);
|
|
1875
|
+
const result = useRef4(null);
|
|
1876
|
+
useEffect4(() => {
|
|
1877
|
+
if (!instance) return;
|
|
1878
|
+
return instance.onConfigChange(() => setSurvey(instance.getSurvey(surveyId) ?? null));
|
|
1879
|
+
}, [instance, surveyId]);
|
|
1880
|
+
const projectTheme = instance?.getTheme();
|
|
1881
|
+
const theme = useMemo4(() => resolveTheme(projectTheme, { scheme, fontFamily }), [projectTheme, scheme, fontFamily]);
|
|
1882
|
+
if (!instance || !survey || closed) return null;
|
|
1883
|
+
if (!shownAt.current) shownAt.current = /* @__PURE__ */ new Date();
|
|
1884
|
+
return /* @__PURE__ */ jsx6(
|
|
1885
|
+
View5,
|
|
1886
|
+
{
|
|
1887
|
+
style: [
|
|
1888
|
+
{ backgroundColor: theme.surface, borderRadius: theme.cornerRadius, borderWidth: 1, borderColor: theme.border, overflow: "hidden" },
|
|
1889
|
+
style
|
|
1890
|
+
],
|
|
1891
|
+
children: /* @__PURE__ */ jsx6(
|
|
1892
|
+
SurveyCard,
|
|
1893
|
+
{
|
|
1894
|
+
survey,
|
|
1895
|
+
theme,
|
|
1896
|
+
variant: "inline",
|
|
1897
|
+
onResult: (r) => {
|
|
1898
|
+
result.current = r;
|
|
1899
|
+
instance.recordInline(survey, r, shownAt.current ?? /* @__PURE__ */ new Date());
|
|
1900
|
+
},
|
|
1901
|
+
onClose: () => {
|
|
1902
|
+
setClosed(true);
|
|
1903
|
+
if (result.current) onComplete?.(result.current);
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
)
|
|
1907
|
+
}
|
|
1908
|
+
);
|
|
1909
|
+
}
|
|
1910
|
+
export {
|
|
1911
|
+
MicroSurvey,
|
|
1912
|
+
MicroSurveys,
|
|
1913
|
+
MicroSurveysProvider,
|
|
1914
|
+
SurveyModal,
|
|
1915
|
+
hydrateAsyncStorage,
|
|
1916
|
+
parseConfig,
|
|
1917
|
+
useMicroSurveys,
|
|
1918
|
+
useMicroSurveysInstance
|
|
1919
|
+
};
|
|
1920
|
+
//# sourceMappingURL=index.js.map
|