@cloudexp-io/laudro-site-kit 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,424 @@
1
+ "use client";
2
+
3
+ // src/client/form.ts
4
+ import { submitForm } from "@cloudexp-io/laudro-sdk/forms";
5
+ import { useCallback, useEffect, useRef, useState } from "react";
6
+
7
+ // src/forms.ts
8
+ var TOKEN_MAX_AGE_MS = 90 * 60 * 1e3;
9
+ var TOKEN_MIN_AGE_MS = 3500;
10
+ function clientFieldErrors(issues, body, form) {
11
+ const errs = {};
12
+ for (const issue of issues) {
13
+ const key = String(issue.path[0] ?? "");
14
+ if (!key || errs[key]) continue;
15
+ const empty = body[key] === void 0 || body[key] === "";
16
+ const short = issue.code === "too_small" && !empty && key in form.tooShort ? form.tooShort[key] : void 0;
17
+ errs[key] = empty ? form.required : short ?? form.invalid;
18
+ }
19
+ return errs;
20
+ }
21
+ function failureMessage(form, phone) {
22
+ return phone ? form.failedCall(phone) : form.failed;
23
+ }
24
+ function submitFailure(res, form, phone) {
25
+ if (res.status === 422 && Object.keys(res.fieldErrors).length > 0) {
26
+ const errors = {};
27
+ for (const key of Object.keys(res.fieldErrors)) errors[key.split(".")[0] ?? key] = form.invalid;
28
+ return { errors, message: null };
29
+ }
30
+ if (res.status === 429) return { errors: {}, message: form.rateLimited };
31
+ return { errors: {}, message: failureMessage(form, phone) };
32
+ }
33
+
34
+ // src/i18n.ts
35
+ var et = {
36
+ langName: "Eesti",
37
+ weekdays: ["esmasp\xE4ev", "teisip\xE4ev", "kolmap\xE4ev", "neljap\xE4ev", "reede", "laup\xE4ev", "p\xFChap\xE4ev"],
38
+ weekdaysShort: ["E", "T", "K", "N", "R", "L", "P"],
39
+ today: "t\xE4na",
40
+ tomorrow: "homme",
41
+ openNow: "Avatud",
42
+ closedNow: "Suletud",
43
+ closesAt: (t) => `Avatud kuni ${t}`,
44
+ opensAt: (w) => `Avatakse ${w}`,
45
+ closed: "suletud",
46
+ openingHours: "Lahtiolekuajad",
47
+ kitchen: "K\xF6\xF6k",
48
+ holiday: "riigip\xFCha",
49
+ specialDay: "Erandp\xE4evad",
50
+ lunch: "P\xE4evapakkumine",
51
+ lunchToday: "T\xE4nane p\xE4evapakkumine",
52
+ noLunch: "T\xE4na p\xE4evapakkumist ei ole.",
53
+ nextLunch: (d) => `J\xE4rgmine p\xE4evapakkumine: ${d}`,
54
+ servedBetween: (a, b) => `Pakume ${a}\u2013${b}`,
55
+ setPrice: "Komplekt",
56
+ to: "kuni",
57
+ language: "Keel",
58
+ closedOn: (ds) => `${ds.length > 1 ? `${ds.slice(0, -1).join(", ")} ja ${ds[ds.length - 1]}` : ds[0]} on suletud`,
59
+ visit: "K\xFClasta",
60
+ pages: "Leht",
61
+ menu: "Men\xFC\xFC",
62
+ openMenu: "Ava men\xFC\xFC",
63
+ bookShort: "Broneeri",
64
+ mainNav: "P\xF5himen\xFC\xFC",
65
+ soldOut: "otsas",
66
+ allergens: "Allergeenid",
67
+ mayContain: "v\xF5ib sisaldada",
68
+ ingredients: "Koostisosad",
69
+ tags: {
70
+ vegan: "vegan",
71
+ vegetarian: "taimetoit",
72
+ gluten_free: "gluteenivaba",
73
+ lactose_free: "laktoosivaba",
74
+ spicy: "v\xFCrtsikas",
75
+ new: "uus",
76
+ popular: "populaarne",
77
+ chef_choice: "koka soovitus",
78
+ kids: "lastele"
79
+ },
80
+ allergenNames: {
81
+ gluten: "gluteen",
82
+ crustaceans: "koorikloomad",
83
+ eggs: "munad",
84
+ fish: "kala",
85
+ peanuts: "maap\xE4hklid",
86
+ soybeans: "soja",
87
+ milk: "piim",
88
+ nuts: "p\xE4hklid",
89
+ celery: "seller",
90
+ mustard: "sinep",
91
+ sesame: "seesam",
92
+ sulphites: "sulfitid",
93
+ lupin: "lupiin",
94
+ molluscs: "molluskid"
95
+ },
96
+ booking: {
97
+ title: "Broneeri laud",
98
+ note: "Kinnitus tuleb SMS-iga kohe.",
99
+ fewer: "V\xE4hem inimesi",
100
+ more: "Rohkem inimesi",
101
+ fullHint: "L\xE4bikriipsutatud on t\xE4is",
102
+ today: "T\xE4na",
103
+ tomorrow: "Homme",
104
+ submit: "Broneeri laud"
105
+ },
106
+ events: {
107
+ seatsLeft: (n) => `${n} kohta vaba`,
108
+ soldOut: "V\xE4lja m\xFC\xFCdud"
109
+ },
110
+ form: {
111
+ date: "Kuup\xE4ev",
112
+ time: "Kellaaeg",
113
+ partySize: "Inimesi",
114
+ name: "Nimi",
115
+ phone: "Telefon",
116
+ email: "E-post",
117
+ emailOptional: "E-post (soovi korral)",
118
+ note: "Lisainfo",
119
+ send: "Saada p\xE4ring",
120
+ sending: "Saadan\u2026",
121
+ sent: "Ait\xE4h!",
122
+ bookingSent: "Ait\xE4h! Saime su broneeringusoovi k\xE4tte ja kinnitame selle peagi.",
123
+ eventSent: "Ait\xE4h! Saime su p\xE4ringu k\xE4tte ja v\xF5tame peagi \xFChendust.",
124
+ contactSent: "Ait\xE4h! Saime su s\xF5numi k\xE4tte.",
125
+ required: "Palun t\xE4ida see v\xE4li.",
126
+ tooShort: { phone: "Telefoninumber on liiga l\xFChike" },
127
+ invalid: "Palun kontrolli seda v\xE4lja.",
128
+ rateLimited: "Liiga palju p\xE4ringuid. Proovi m\xF5ne minuti p\xE4rast uuesti.",
129
+ failed: "Saatmine eba\xF5nnestus. Proovi uuesti.",
130
+ failedCall: (p) => `Saatmine eba\xF5nnestus. Proovi uuesti v\xF5i helista ${p}.`,
131
+ eventDate: "\xDCrituse kuup\xE4ev",
132
+ guests: "K\xFClalisi",
133
+ kind: "\xDCrituse liik",
134
+ kinds: { company: "Firma\xFCritus", birthday: "S\xFCnnip\xE4ev", wedding: "Pulm", other: "Muu" },
135
+ budget: "Eelarve (\u20AC)",
136
+ package: "Pakett",
137
+ noPackage: "Ei tea veel",
138
+ perPerson: "/ in",
139
+ company: "Ettev\xF5te",
140
+ message: "S\xF5num",
141
+ sendAnother: "Saada uus p\xE4ring"
142
+ }
143
+ };
144
+ var en = {
145
+ langName: "English",
146
+ weekdays: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
147
+ weekdaysShort: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
148
+ today: "today",
149
+ tomorrow: "tomorrow",
150
+ openNow: "Open now",
151
+ closedNow: "Closed",
152
+ closesAt: (t) => `Open until ${t}`,
153
+ opensAt: (w) => `Opens ${w}`,
154
+ closed: "closed",
155
+ openingHours: "Opening hours",
156
+ kitchen: "Kitchen",
157
+ holiday: "public holiday",
158
+ specialDay: "Special days",
159
+ lunch: "Lunch",
160
+ lunchToday: "Today's lunch",
161
+ noLunch: "No lunch offer today.",
162
+ nextLunch: (d) => `Next lunch offer: ${d}`,
163
+ servedBetween: (a, b) => `Served ${a}\u2013${b}`,
164
+ setPrice: "Set menu",
165
+ to: "to",
166
+ language: "Language",
167
+ closedOn: (ds) => `Closed on ${ds.length > 1 ? `${ds.slice(0, -1).join(", ")} and ${ds[ds.length - 1]}` : ds[0]}`,
168
+ visit: "Visit",
169
+ pages: "Pages",
170
+ menu: "Menu",
171
+ openMenu: "Open menu",
172
+ bookShort: "Book",
173
+ mainNav: "Main",
174
+ soldOut: "sold out",
175
+ allergens: "Allergens",
176
+ mayContain: "may contain",
177
+ ingredients: "Ingredients",
178
+ tags: {
179
+ vegan: "vegan",
180
+ vegetarian: "vegetarian",
181
+ gluten_free: "gluten-free",
182
+ lactose_free: "lactose-free",
183
+ spicy: "spicy",
184
+ new: "new",
185
+ popular: "popular",
186
+ chef_choice: "chef's choice",
187
+ kids: "for kids"
188
+ },
189
+ allergenNames: {
190
+ gluten: "gluten",
191
+ crustaceans: "crustaceans",
192
+ eggs: "eggs",
193
+ fish: "fish",
194
+ peanuts: "peanuts",
195
+ soybeans: "soy",
196
+ milk: "milk",
197
+ nuts: "tree nuts",
198
+ celery: "celery",
199
+ mustard: "mustard",
200
+ sesame: "sesame",
201
+ sulphites: "sulphites",
202
+ lupin: "lupin",
203
+ molluscs: "molluscs"
204
+ },
205
+ booking: {
206
+ title: "Book a table",
207
+ note: "You get an SMS confirmation right away.",
208
+ fewer: "Fewer guests",
209
+ more: "More guests",
210
+ fullHint: "Crossed out times are full",
211
+ today: "Today",
212
+ tomorrow: "Tomorrow",
213
+ submit: "Book a table"
214
+ },
215
+ events: {
216
+ seatsLeft: (n) => `${n} ${n === 1 ? "seat" : "seats"} left`,
217
+ soldOut: "Sold out"
218
+ },
219
+ form: {
220
+ date: "Date",
221
+ time: "Time",
222
+ partySize: "Guests",
223
+ name: "Name",
224
+ phone: "Phone",
225
+ email: "Email",
226
+ emailOptional: "Email (optional)",
227
+ note: "Notes",
228
+ send: "Send request",
229
+ sending: "Sending\u2026",
230
+ sent: "Thank you!",
231
+ bookingSent: "Thank you! We got your booking request and will confirm it soon.",
232
+ eventSent: "Thank you! We got your request and will be in touch soon.",
233
+ contactSent: "Thank you! We got your message.",
234
+ required: "Please fill in this field.",
235
+ tooShort: { phone: "Phone number is too short" },
236
+ invalid: "Please check this field.",
237
+ rateLimited: "Too many requests. Please try again in a few minutes.",
238
+ failed: "Sending failed. Please try again.",
239
+ failedCall: (p) => `Sending failed. Please try again or call ${p}.`,
240
+ eventDate: "Event date",
241
+ guests: "Guests",
242
+ kind: "Type of event",
243
+ kinds: { company: "Company event", birthday: "Birthday", wedding: "Wedding", other: "Other" },
244
+ budget: "Budget (\u20AC)",
245
+ package: "Package",
246
+ noPackage: "Not sure yet",
247
+ perPerson: "/ person",
248
+ company: "Company",
249
+ message: "Message",
250
+ sendAnother: "Send another request"
251
+ }
252
+ };
253
+ var DICTIONARIES = { et, en };
254
+ function dictionary(lang) {
255
+ return DICTIONARIES[lang];
256
+ }
257
+
258
+ // src/client/form.ts
259
+ async function fetchToken(url) {
260
+ try {
261
+ const res = await fetch(url, { cache: "no-store", headers: { accept: "application/json" } });
262
+ if (!res.ok) return null;
263
+ const json = await res.json();
264
+ return typeof json.t === "string" ? { t: json.t, at: Date.now() } : null;
265
+ } catch {
266
+ return null;
267
+ }
268
+ }
269
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
270
+ function useFormToken(url) {
271
+ const held = useRef(null);
272
+ useEffect(() => {
273
+ let live = true;
274
+ void fetchToken(url).then((tok) => {
275
+ if (live && tok) held.current = tok;
276
+ });
277
+ return () => {
278
+ live = false;
279
+ };
280
+ }, [url]);
281
+ return useCallback(async () => {
282
+ let tok = held.current;
283
+ if (!tok || Date.now() - tok.at > TOKEN_MAX_AGE_MS) {
284
+ tok = await fetchToken(url);
285
+ held.current = tok;
286
+ }
287
+ if (!tok) return null;
288
+ const age = Date.now() - tok.at;
289
+ if (age < TOKEN_MIN_AGE_MS) await sleep(TOKEN_MIN_AGE_MS - age);
290
+ return tok.t;
291
+ }, [url]);
292
+ }
293
+ function useRbForm(o) {
294
+ const d = dictionary(o.lang);
295
+ const getToken = useFormToken(o.tokenUrl);
296
+ const [status, setStatus] = useState("idle");
297
+ const [errors, setErrors] = useState({});
298
+ const [message, setMessage] = useState(null);
299
+ const formRef = useRef(null);
300
+ const onSubmit = useCallback(
301
+ async (e) => {
302
+ e.preventDefault();
303
+ if (status === "sending") return;
304
+ const form = e.currentTarget;
305
+ const fd = new FormData(form);
306
+ const body = {
307
+ ...o.build(fd),
308
+ lang: o.lang,
309
+ hp: String(fd.get("website") ?? "")
310
+ };
311
+ const local = o.schema.safeParse({ ...body, t: "0.0" });
312
+ if (!local.success) {
313
+ const errs = clientFieldErrors(local.error.issues, body, d.form);
314
+ setErrors(errs);
315
+ setMessage(null);
316
+ setStatus("error");
317
+ focusFirst(form, errs);
318
+ return;
319
+ }
320
+ setErrors({});
321
+ setMessage(null);
322
+ setStatus("sending");
323
+ const t = await getToken();
324
+ if (!t) {
325
+ setStatus("error");
326
+ setMessage(failureMessage(d.form, o.phone));
327
+ return;
328
+ }
329
+ const res = await submitForm(o.action, { ...body, t });
330
+ if (res.ok) {
331
+ setStatus("sent");
332
+ o.onSent?.(res.data);
333
+ return;
334
+ }
335
+ setStatus("error");
336
+ const failure = submitFailure(res, d.form, o.phone);
337
+ setErrors(failure.errors);
338
+ setMessage(failure.message);
339
+ focusFirst(form, failure.errors);
340
+ },
341
+ [d, getToken, o, status]
342
+ );
343
+ const reset = useCallback(() => {
344
+ formRef.current?.reset();
345
+ setErrors({});
346
+ setMessage(null);
347
+ setStatus("idle");
348
+ }, []);
349
+ return { d, status, errors, message, onSubmit, reset, formRef };
350
+ }
351
+ function focusFirst(form, errs) {
352
+ const first = Object.keys(errs)[0];
353
+ if (!first) return;
354
+ const el = form.elements.namedItem(first);
355
+ if (el && "focus" in el && typeof el.focus === "function") el.focus();
356
+ }
357
+
358
+ // src/client/track.ts
359
+ import { usePathname } from "next/navigation";
360
+ import { useEffect as useEffect2 } from "react";
361
+
362
+ // src/track.ts
363
+ var MOBILE_QUERY = "(max-width: 767px)";
364
+ function trackBody(input) {
365
+ const path = input.path.slice(0, 300) || "/";
366
+ let ref;
367
+ try {
368
+ const r = input.referrer ? new URL(input.referrer) : null;
369
+ if (r && r.host !== input.host) ref = r.host;
370
+ } catch {
371
+ ref = void 0;
372
+ }
373
+ return {
374
+ name: input.name,
375
+ path,
376
+ lang: input.lang,
377
+ device: input.mobile ? "mobile" : "desktop",
378
+ ...ref ? { ref } : {}
379
+ };
380
+ }
381
+
382
+ // src/client/track.ts
383
+ var DEFAULT_URL = "/api/track";
384
+ function sendTrack(name, lang, opts = {}) {
385
+ if (typeof window === "undefined") return;
386
+ const body = JSON.stringify(
387
+ trackBody({
388
+ name,
389
+ lang,
390
+ path: opts.path ?? window.location.pathname,
391
+ referrer: document.referrer,
392
+ host: window.location.host,
393
+ mobile: !!window.matchMedia?.(MOBILE_QUERY).matches
394
+ })
395
+ );
396
+ const url = opts.url ?? DEFAULT_URL;
397
+ try {
398
+ if (navigator.sendBeacon?.(url, new Blob([body], { type: "application/json" }))) return;
399
+ } catch {
400
+ }
401
+ void fetch(url, {
402
+ method: "POST",
403
+ body,
404
+ keepalive: true,
405
+ headers: { "content-type": "application/json" }
406
+ }).catch(() => {
407
+ });
408
+ }
409
+ function usePageView({
410
+ lang,
411
+ url,
412
+ name = "page_view"
413
+ }) {
414
+ const pathname = usePathname();
415
+ useEffect2(() => {
416
+ sendTrack(name, lang, { ...url ? { url } : {}, ...pathname ? { path: pathname } : {} });
417
+ }, [pathname, lang, url, name]);
418
+ }
419
+ export {
420
+ sendTrack,
421
+ useFormToken,
422
+ usePageView,
423
+ useRbForm
424
+ };