basklee-nuxt 0.9.4 → 0.9.6

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.
Files changed (35) hide show
  1. package/README.md +4 -0
  2. package/package.json +2 -2
  3. package/templates/app/components/basklee/account/StorefrontLogout.README.md +2 -0
  4. package/templates/app/components/basklee/blog/BlogArticle.README.md +2 -0
  5. package/templates/app/components/basklee/blog/BlogArticle.vue +21 -1
  6. package/templates/app/components/basklee/orders/OrderDetails.README.md +2 -0
  7. package/templates/app/components/basklee/orders/OrderDetails.vue +5 -0
  8. package/templates/app/components/basklee/storefront/StorefrontFooter.README.md +6 -0
  9. package/templates/app/components/basklee/storefront/StorefrontFooter.vue +21 -4
  10. package/templates/app/components/basklee/stores/StorefrontStores.README.md +2 -0
  11. package/templates/app/components/basklee/stores/StorefrontStores.vue +2 -1
  12. package/templates/app/composables/useBaskleeCart.ts +356 -2
  13. package/templates/app/layouts/default.vue +2 -1
  14. package/templates/app/pages/browse.vue +2 -2
  15. package/templates/app/utils/basklee/activityLabels.ts +15 -0
  16. package/templates/app/utils/basklee/blogMediaFallback.ts +322 -0
  17. package/templates/app/utils/basklee/browseLabels.ts +12 -0
  18. package/templates/app/utils/basklee/cartLabels.ts +125 -1
  19. package/templates/app/utils/basklee/cartMemory.ts +614 -0
  20. package/templates/app/utils/basklee/contactLabels.ts +13 -1
  21. package/templates/app/utils/basklee/directoryLabels.ts +3 -0
  22. package/templates/app/utils/basklee/featureLabels.ts +12 -0
  23. package/templates/app/utils/basklee/footerLabels.ts +3 -0
  24. package/templates/app/utils/basklee/headerLabels.ts +1 -1
  25. package/templates/app/utils/basklee/photoDetail.ts +59 -0
  26. package/templates/app/utils/basklee/productActions.ts +8 -0
  27. package/templates/app/utils/basklee/profile.ts +52 -0
  28. package/templates/app/utils/basklee/profileLabels.ts +15 -0
  29. package/templates/app/utils/basklee/reviewLabels.ts +6 -0
  30. package/templates/app/utils/basklee/sellerDirectory.ts +112 -0
  31. package/templates/app/utils/basklee/sessionLabels.ts +6 -6
  32. package/templates/app/utils/basklee/storeDirectory.ts +26 -0
  33. package/templates/app/utils/basklee/subscriptionLabels.ts +3 -0
  34. package/templates/app/utils/basklee/tabLocation.ts +37 -0
  35. package/templates/app/utils/basklee/ticketDraft.ts +56 -0
@@ -36,6 +36,7 @@ const en = {
36
36
  activity: 'My activity',
37
37
  },
38
38
  logout: 'Logout',
39
+ logoutScope: 'on all devices',
39
40
  addresses: {
40
41
  title: 'My addresses',
41
42
  description: 'Saved addresses for delivery.',
@@ -97,6 +98,9 @@ const en = {
97
98
  paid_subs: 'Subscriptions',
98
99
  empty: 'No payments in this category yet.',
99
100
  unavailable: 'No payment methods are available.',
101
+ unavailableHint:
102
+ 'The wallet cannot be topped up from your account right now: the shop offers no payment method for it. Orders can still be paid at checkout. If you expected to see a method here, write to the shop.',
103
+ contactShop: 'Write to the shop',
100
104
  pay: 'Pay',
101
105
  cancelInvoice: 'Cancel',
102
106
  cancelQuestion: 'Cancel this unpaid invoice?',
@@ -171,6 +175,7 @@ const ru: typeof en = {
171
175
  activity: 'Моя активность',
172
176
  },
173
177
  logout: 'Выйти',
178
+ logoutScope: 'на всех устройствах',
174
179
  addresses: {
175
180
  title: 'Мои адреса',
176
181
  description: 'Сохранённые адреса для доставки.',
@@ -232,6 +237,9 @@ const ru: typeof en = {
232
237
  paid_subs: 'Подписки',
233
238
  empty: 'В этой категории пока нет платежей.',
234
239
  unavailable: 'Нет доступных способов оплаты.',
240
+ unavailableHint:
241
+ 'Сейчас пополнить кошелёк с вашего аккаунта нельзя: магазин не предлагает для этого способа оплаты. Заказы по-прежнему можно оплатить при оформлении. Если способ оплаты здесь должен быть, напишите магазину.',
242
+ contactShop: 'Написать магазину',
235
243
  pay: 'Оплатить',
236
244
  cancelInvoice: 'Отменить',
237
245
  cancelQuestion: 'Отменить этот неоплаченный счёт?',
@@ -304,6 +312,7 @@ const es: typeof en = {
304
312
  activity: 'Mi actividad',
305
313
  },
306
314
  logout: 'Cerrar sesión',
315
+ logoutScope: 'en todos los dispositivos',
307
316
  addresses: {
308
317
  title: 'Mis direcciones',
309
318
  description: 'Direcciones guardadas para la entrega.',
@@ -365,6 +374,9 @@ const es: typeof en = {
365
374
  paid_subs: 'Suscripciones',
366
375
  empty: 'Todavía no hay pagos en esta categoría.',
367
376
  unavailable: 'No hay métodos de pago disponibles.',
377
+ unavailableHint:
378
+ 'Ahora no se puede recargar el monedero desde su cuenta: la tienda no ofrece ningún método de pago para ello. Los pedidos se pueden pagar al finalizar la compra. Si esperaba ver un método aquí, escriba a la tienda.',
379
+ contactShop: 'Escribir a la tienda',
368
380
  pay: 'Pagar',
369
381
  cancelInvoice: 'Cancelar',
370
382
  cancelQuestion: '¿Cancelar esta factura sin pagar?',
@@ -12,6 +12,7 @@ export function footerLabels(locale: string) {
12
12
  profile: 'Личный кабинет',
13
13
  journal: 'Журнал',
14
14
  rights: 'Все права защищены.',
15
+ powered: 'Работает на Basklee',
15
16
  products: 'Товары',
16
17
  discounts: 'Скидки',
17
18
  new: 'Новинки',
@@ -29,6 +30,7 @@ export function footerLabels(locale: string) {
29
30
  profile: 'Mi cuenta',
30
31
  journal: 'Blog',
31
32
  rights: 'Todos los derechos reservados.',
33
+ powered: 'Funciona con Basklee',
32
34
  products: 'Productos',
33
35
  discounts: 'Descuentos',
34
36
  new: 'Novedades',
@@ -45,6 +47,7 @@ export function footerLabels(locale: string) {
45
47
  profile: 'My account',
46
48
  journal: 'Journal',
47
49
  rights: 'All rights reserved.',
50
+ powered: 'Powered by Basklee',
48
51
  products: 'Products',
49
52
  discounts: 'Discounts',
50
53
  new: 'New arrivals',
@@ -73,7 +73,7 @@ const labels = {
73
73
  close: 'Cerrar el catálogo',
74
74
  back: 'Atrás',
75
75
  viewCategory: 'Ver',
76
- highlights: 'Categorías destacadas',
76
+ highlights: 'Productos destacados',
77
77
  empty: 'No hay categorías disponibles',
78
78
  emptyProducts: 'No hay productos representativos',
79
79
  saved: 'Favoritos',
@@ -0,0 +1,59 @@
1
+ // Does a larger view of a picture show more than the page already does?
2
+ //
3
+ // A product photograph opens full screen when it is pressed. That helps only
4
+ // when the file holds more than the page paints: a 480 px file painted
5
+ // 870 px wide is already stretched, and a larger view of it shows the same
6
+ // blur larger. So the page offers the larger view only for a picture whose
7
+ // file is larger than its painted size — by a margin, because a few more
8
+ // pixels show nothing new.
9
+
10
+ export interface PhotoSize {
11
+ width: number;
12
+ height: number;
13
+ }
14
+
15
+ /** How much larger than painted the file must be, on its longer fit, to be worth opening. */
16
+ export const PHOTO_DETAIL_MARGIN = 1.1;
17
+
18
+ /**
19
+ * `natural` is the file's size in pixels, `box` the box the page paints it
20
+ * into (CSS pixels); the picture is painted whole inside the box, as with
21
+ * `object-fit: contain`. Unknown or empty sizes answer `false`: a picture
22
+ * that is not loaded yet offers nothing.
23
+ */
24
+ export function photoHoldsMore(natural: PhotoSize, box: PhotoSize) {
25
+ if (
26
+ !(natural.width > 0) ||
27
+ !(natural.height > 0) ||
28
+ !(box.width > 0) ||
29
+ !(box.height > 0)
30
+ ) {
31
+ return false;
32
+ }
33
+
34
+ const painted = Math.min(box.width / natural.width, box.height / natural.height);
35
+
36
+ return painted * PHOTO_DETAIL_MARGIN < 1;
37
+ }
38
+
39
+ /**
40
+ * The pictures of `root` marked `data-photo="<address>"` that hold more than
41
+ * the page paints, by address. A picture still loading is left out.
42
+ */
43
+ export function photosHoldingMore(root: ParentNode | null | undefined) {
44
+ const found: Record<string, boolean> = {};
45
+
46
+ for (const picture of root?.querySelectorAll<HTMLImageElement>('img[data-photo]') ?? []) {
47
+ const address = picture.dataset.photo;
48
+
49
+ if (address && picture.complete && picture.naturalWidth > 0) {
50
+ const box = picture.getBoundingClientRect();
51
+
52
+ found[address] = photoHoldsMore(
53
+ { width: picture.naturalWidth, height: picture.naturalHeight },
54
+ { width: box.width, height: box.height },
55
+ );
56
+ }
57
+ }
58
+ return found;
59
+ }
@@ -6,6 +6,14 @@ import type {
6
6
  import { productWithSellerPermission } from '@/utils/basklee/productSeller';
7
7
  import type { useBaskleeStore } from '@/stores/basklee';
8
8
 
9
+ /**
10
+ * How long the words about a finished product action («Added to the cart.»)
11
+ * stay, in milliseconds — the same in the layout's message for shelves and
12
+ * lists and beside the buy controls of the product page. Every new action
13
+ * starts the time again; an error stays until the next action.
14
+ */
15
+ export const PRODUCT_NOTICE_TIME = 4000;
16
+
9
17
  export type ProductActionStore = Pick<
10
18
  ReturnType<typeof useBaskleeStore>,
11
19
  'getProduct' | 'getProductAvailability' | 'setProduct'
@@ -146,3 +146,55 @@ export function applyProfileAuthenticationData(
146
146
  state.authEmail = '';
147
147
  }
148
148
  }
149
+
150
+ /**
151
+ * A language by its code, named in the language of the page («English»,
152
+ * «Español», «Русский»). The shop's own short names («Eng») do not tell a
153
+ * customer which language their order letters come in; `fallback` is used
154
+ * when the browser has no name for the code.
155
+ */
156
+ export function profileLanguageName(code: string, locale: string, fallback: string) {
157
+ try {
158
+ const name = new Intl.DisplayNames([locale], { type: 'language' }).of(code);
159
+
160
+ if (name && name.toLowerCase() !== code.toLowerCase()) {
161
+ return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
162
+ }
163
+ } catch {
164
+ // An unknown code keeps the shop's own name.
165
+ }
166
+ return fallback;
167
+ }
168
+
169
+ // Personal details typed and not saved yet. They stay in the page's memory
170
+ // while the customer visits other pages, so coming back to the profile shows
171
+ // what was typed. Memory only: a reload starts from the saved profile, the
172
+ // server keeps nothing, and a draft belongs to one customer ID.
173
+ export interface ProfileDetailsDraft {
174
+ first_name: string;
175
+ last_name: string;
176
+ dob: string;
177
+ }
178
+
179
+ const profileDrafts = new Map<number, ProfileDetailsDraft>();
180
+
181
+ export function readProfileDraft(customerId: number | undefined) {
182
+ return typeof window !== 'undefined' && customerId
183
+ ? profileDrafts.get(customerId)
184
+ : undefined;
185
+ }
186
+
187
+ // `null` drops the draft: the details were saved or the customer discarded them.
188
+ export function keepProfileDraft(
189
+ customerId: number | undefined,
190
+ draft: ProfileDetailsDraft | null,
191
+ ) {
192
+ if (typeof window === 'undefined' || !customerId) {
193
+ return;
194
+ }
195
+ if (draft) {
196
+ profileDrafts.set(customerId, { ...draft });
197
+ } else {
198
+ profileDrafts.delete(customerId);
199
+ }
200
+ }
@@ -27,6 +27,11 @@ const en = {
27
27
  email: 'Email address',
28
28
  emailHint:
29
29
  'Verify your address before receiving order updates and email notifications.',
30
+ emailConfirmed: 'Confirmed',
31
+ emailConfirmedHint:
32
+ 'Order updates and notifications are sent to this address. To change it, type a new address and send a code.',
33
+ unsaved: 'You have unsaved changes.',
34
+ discard: 'Discard',
30
35
  sendCode: 'Send',
31
36
  sendCodeHint: 'Send verification code',
32
37
  code: 'Verification code',
@@ -102,6 +107,11 @@ const ru: typeof en = {
102
107
  email: 'Электронная почта',
103
108
  emailHint:
104
109
  'Подтвердите адрес для получения уведомлений о заказах и рассылки.',
110
+ emailConfirmed: 'Подтверждён',
111
+ emailConfirmedHint:
112
+ 'На этот адрес приходят письма о заказах и уведомления. Чтобы сменить его, введите новый адрес и отправьте код.',
113
+ unsaved: 'Есть несохранённые изменения.',
114
+ discard: 'Отменить изменения',
105
115
  sendCode: 'Отправить',
106
116
  sendCodeHint: 'Отправить код подтверждения',
107
117
  code: 'Код подтверждения',
@@ -178,6 +188,11 @@ const es: typeof en = {
178
188
  email: 'Dirección de correo',
179
189
  emailHint:
180
190
  'Verifica tu dirección antes de recibir novedades de pedidos y notificaciones por correo.',
191
+ emailConfirmed: 'Confirmada',
192
+ emailConfirmedHint:
193
+ 'Los avisos de pedidos y las notificaciones llegan a esta dirección. Para cambiarla, escriba una nueva y envíe un código.',
194
+ unsaved: 'Hay cambios sin guardar.',
195
+ discard: 'Descartar',
181
196
  sendCode: 'Enviar',
182
197
  sendCodeHint: 'Enviar código de verificación',
183
198
  code: 'Código de verificación',
@@ -24,6 +24,8 @@ const en = {
24
24
  productPhotos: 'Product photos',
25
25
  openProductPhoto: 'Open the photo full screen',
26
26
  empty: 'No reviews yet.',
27
+ emptyFiltered: 'No reviews match these filters.',
28
+ showAll: 'Show all reviews',
27
29
  emptyImages: 'No customer photos yet.',
28
30
  send: 'Submit',
29
31
  save: 'Save',
@@ -103,6 +105,8 @@ const ru: typeof en = {
103
105
  productPhotos: 'Фотографии товара',
104
106
  openProductPhoto: 'Открыть фотографию на весь экран',
105
107
  empty: 'Отзывов пока нет.',
108
+ emptyFiltered: 'Под эти фильтры не подходит ни один отзыв.',
109
+ showAll: 'Показать все отзывы',
106
110
  emptyImages: 'Покупатели ещё не добавили фотографии.',
107
111
  send: 'Отправить',
108
112
  save: 'Сохранить',
@@ -183,6 +187,8 @@ const es: typeof en = {
183
187
  productPhotos: 'Fotos del producto',
184
188
  openProductPhoto: 'Abrir la foto a pantalla completa',
185
189
  empty: 'Aún no hay reseñas.',
190
+ emptyFiltered: 'Ninguna reseña coincide con estos filtros.',
191
+ showAll: 'Ver todas las reseñas',
186
192
  emptyImages: 'Aún no hay fotos de clientes.',
187
193
  send: 'Enviar',
188
194
  save: 'Guardar',
@@ -41,6 +41,103 @@ export function hasSellerFilters(filters: ISellerDirectoryFilters) {
41
41
  );
42
42
  }
43
43
 
44
+ // Where the seller directory is: its filters, order and page. The directory
45
+ // keeps it in the URL as `?name&rating&cats&sort&page`, so Back from a seller,
46
+ // a reload and a copied address return to the same list.
47
+ export interface SellerDirectoryLocation {
48
+ filters: ISellerDirectoryFilters;
49
+ page: number;
50
+ }
51
+
52
+ type SellerQueryValue = string | null | undefined | readonly (string | null)[];
53
+
54
+ const sellerLocationKeys = ['name', 'rating', 'cats', 'sort', 'page'];
55
+
56
+ function firstSellerQueryValue(
57
+ value: SellerQueryValue,
58
+ ): string | null | undefined {
59
+ return typeof value === 'string' || value === null || value === undefined
60
+ ? value
61
+ : value[0];
62
+ }
63
+
64
+ function positiveSellerQueryNumber(value: string | null | undefined) {
65
+ const number = Number(value);
66
+
67
+ return Number.isSafeInteger(number) && number > 0 ? number : undefined;
68
+ }
69
+
70
+ // Unknown or damaged values fall back to the full list in the default order.
71
+ export function sellerLocationFromQuery(
72
+ query: Record<string, SellerQueryValue>,
73
+ ): SellerDirectoryLocation {
74
+ const filters = emptySellerFilters();
75
+ const rating = positiveSellerQueryNumber(firstSellerQueryValue(query.rating));
76
+ const cats = (firstSellerQueryValue(query.cats) ?? '')
77
+ .split(',')
78
+ .map((part) => positiveSellerQueryNumber(part))
79
+ .filter((id): id is number => id !== undefined);
80
+
81
+ filters.seller_name = (firstSellerQueryValue(query.name) ?? '').slice(0, 200);
82
+ if (rating !== undefined && rating <= SELLER_RATING_MAXIMUM) {
83
+ filters.seller_rating_from = rating;
84
+ }
85
+ filters.seller_categories = [...new Set(cats)];
86
+ if (firstSellerQueryValue(query.sort) === 'low') {
87
+ filters.ordering = 'seller_raiting';
88
+ }
89
+
90
+ return {
91
+ filters,
92
+ page: positiveSellerQueryNumber(firstSellerQueryValue(query.page)) ?? 1,
93
+ };
94
+ }
95
+
96
+ // The query of `next`: other parameters such as `locale` stay and defaults
97
+ // are left out, so the plain directory keeps its plain address.
98
+ export function sellerLocationQuery(
99
+ query: Record<string, SellerQueryValue>,
100
+ next: SellerDirectoryLocation,
101
+ ) {
102
+ const result: Record<string, string> = {};
103
+ const name = next.filters.seller_name.trim();
104
+
105
+ for (const [key, value] of Object.entries(query)) {
106
+ const text = firstSellerQueryValue(value);
107
+
108
+ if (typeof text === 'string' && !sellerLocationKeys.includes(key)) {
109
+ result[key] = text;
110
+ }
111
+ }
112
+ if (name) {
113
+ result.name = name;
114
+ }
115
+ if (next.filters.seller_rating_from !== null) {
116
+ result.rating = String(next.filters.seller_rating_from);
117
+ }
118
+ if (next.filters.seller_categories.length) {
119
+ result.cats = next.filters.seller_categories.join(',');
120
+ }
121
+ if (next.filters.ordering === 'seller_raiting') {
122
+ result.sort = 'low';
123
+ }
124
+ if (next.page > 1) {
125
+ result.page = String(next.page);
126
+ }
127
+
128
+ return result;
129
+ }
130
+
131
+ export function sameSellerLocation(
132
+ left: SellerDirectoryLocation,
133
+ right: SellerDirectoryLocation,
134
+ ) {
135
+ return (
136
+ left.page === right.page &&
137
+ JSON.stringify(left.filters) === JSON.stringify(right.filters)
138
+ );
139
+ }
140
+
44
141
  export function sellerDirectoryRequest(
45
142
  filters: ISellerDirectoryFilters,
46
143
  page: number,
@@ -116,6 +213,21 @@ export function sellerLogo(seller: ISellerDirectoryEntry) {
116
213
  return seller.seller_logo || seller.logo || '';
117
214
  }
118
215
 
216
+ /**
217
+ * The first letters of a seller's name, two at most («Folio Editions» → «FE»):
218
+ * what stands in the logo's place when the seller has none, so the card
219
+ * still shows whose it is instead of an empty picture frame.
220
+ */
221
+ export function sellerInitials(name: string | null | undefined) {
222
+ return (name ?? '')
223
+ .split(/[\s\-–—_.,&+/]+/u)
224
+ .map((word) => [...word.replace(/[^\p{L}\p{N}]/gu, '')][0] ?? '')
225
+ .filter(Boolean)
226
+ .slice(0, 2)
227
+ .join('')
228
+ .toLocaleUpperCase();
229
+ }
230
+
119
231
  // Approved seller images in the seller's display order; images without a
120
232
  // usable public URL are omitted so the gallery never shows empty tiles.
121
233
  export function sellerGalleryImages(images: ISellerDirectoryImage[]) {
@@ -2,37 +2,37 @@ export function sessionLabels(locale: string) {
2
2
  return locale.toLowerCase().startsWith('ru')
3
3
  ? {
4
4
  title: 'Выход из аккаунта',
5
- pending: 'Завершаем сеанс…',
5
+ pending: 'Завершаем сеансы на всех устройствах…',
6
6
  hint: 'После выхода вы вернётесь на главную страницу.',
7
7
  failed: 'Не удалось завершить выход',
8
8
  retryHint:
9
9
  'Повторите попытку. Выход подтверждается только ответом сервера.',
10
10
  refreshFailed: 'Сеанс завершён. Не удалось загрузить магазин.',
11
11
  retry: 'Повторить',
12
- done: 'Вы вышли из аккаунта',
12
+ done: 'Вы вышли из аккаунта на всех устройствах',
13
13
  home: 'Главная',
14
14
  }
15
15
  : locale.toLowerCase().startsWith('es') ? {
16
16
  title: 'Cerrando sesión',
17
- pending: 'Terminando tu sesión…',
17
+ pending: 'Cerrando tu sesión en todos los dispositivos…',
18
18
  hint: 'Volverás a la página de inicio de la tienda.',
19
19
  failed: 'No se ha podido cerrar la sesión',
20
20
  retryHint: 'Inténtalo de nuevo. El cierre de sesión lo confirma el servidor.',
21
21
  refreshFailed:
22
22
  'Tu sesión ha terminado. No se ha podido recargar la tienda.',
23
23
  retry: 'Reintentar',
24
- done: 'Has cerrado la sesión',
24
+ done: 'Has cerrado la sesión en todos los dispositivos',
25
25
  home: 'Inicio',
26
26
  } : {
27
27
  title: 'Signing out',
28
- pending: 'Ending your session…',
28
+ pending: 'Ending your sessions on all devices…',
29
29
  hint: 'You will return to the storefront home page.',
30
30
  failed: 'Could not finish signing out',
31
31
  retryHint: 'Please try again. Sign-out is confirmed by the server.',
32
32
  refreshFailed:
33
33
  'Your session has ended. The storefront could not be reloaded.',
34
34
  retry: 'Retry',
35
- done: 'You are signed out',
35
+ done: 'You are signed out on all devices',
36
36
  home: 'Home',
37
37
  };
38
38
  }
@@ -48,3 +48,29 @@ export function storeMapMarkers(
48
48
  export function storePhoneLink(value: string) {
49
49
  return `tel:${value.replace(/[^+0-9]/g, '')}`;
50
50
  }
51
+
52
+ /**
53
+ * A store's telephone as people read it. A number typed with its own spaces,
54
+ * brackets or dashes is shown as typed; a bare run of digits («+78120000078»)
55
+ * is grouped from the end («+7 812 000 00 78»), the way the shop's contact
56
+ * page writes its number. The dial link keeps using `storePhoneLink`.
57
+ */
58
+ export function storePhoneText(value: string) {
59
+ const text = value.trim();
60
+
61
+ if (!/^\+?\d{7,15}$/.test(text)) {
62
+ return text;
63
+ }
64
+ const digits = text.replace('+', '');
65
+ const groups = [digits.slice(-2), digits.slice(-4, -2)];
66
+ let rest = digits.slice(0, -4);
67
+
68
+ while (rest.length > 3) {
69
+ groups.push(rest.slice(-3));
70
+ rest = rest.slice(0, -3);
71
+ }
72
+ if (rest) {
73
+ groups.push(rest);
74
+ }
75
+ return `${text.startsWith('+') ? '+' : ''}${groups.reverse().join(' ')}`;
76
+ }
@@ -21,6 +21,7 @@ const en = {
21
21
  intro:
22
22
  'Choose a plan and a subscription period. Paid periods are charged to the account balance.',
23
23
  noOffers: 'No subscription plans are available yet.',
24
+ toCatalog: 'Browse the catalogue',
24
25
  reset: 'Reset',
25
26
  support: 'Subscription support',
26
27
  wallet: 'Top up balance',
@@ -53,6 +54,7 @@ const ru: typeof en = {
53
54
  intro:
54
55
  'Выберите тариф и период подписки. Платные периоды оплачиваются с баланса аккаунта.',
55
56
  noOffers: 'Тарифов подписок пока нет.',
57
+ toCatalog: 'Открыть каталог',
56
58
  reset: 'Сбросить',
57
59
  support: 'Поддержка по подписке',
58
60
  wallet: 'Пополнить баланс',
@@ -86,6 +88,7 @@ const es: typeof en = {
86
88
  intro:
87
89
  'Elige un plan y un periodo de suscripción. Los periodos de pago se cobran del saldo de la cuenta.',
88
90
  noOffers: 'Todavía no hay planes de suscripción disponibles.',
91
+ toCatalog: 'Ver el catálogo',
89
92
  reset: 'Restablecer',
90
93
  support: 'Soporte de suscripciones',
91
94
  wallet: 'Recargar saldo',
@@ -0,0 +1,37 @@
1
+ // The chosen tab of an account page lives in the address as `?tab=`, so a
2
+ // reload, the browser's Back and a copied link open the view the customer
3
+ // chose. The first tab is the default and leaves the address plain.
4
+ type TabQueryValue = string | null | undefined | readonly (string | null)[];
5
+
6
+ // `tab` from the address; an unknown or missing value is the first tab.
7
+ export function tabFromQuery<T extends string>(
8
+ query: Record<string, TabQueryValue>,
9
+ tabs: readonly T[],
10
+ ): T {
11
+ const raw = query.tab;
12
+ const value = Array.isArray(raw) ? raw[0] : raw;
13
+
14
+ return tabs.find((tab) => tab === value) ?? tabs[0]!;
15
+ }
16
+
17
+ // The query with `tab` chosen: other parameters such as `locale` stay.
18
+ export function tabQuery<T extends string>(
19
+ query: Record<string, TabQueryValue>,
20
+ tab: T,
21
+ tabs: readonly T[],
22
+ ) {
23
+ const result: Record<string, string> = {};
24
+
25
+ for (const [key, raw] of Object.entries(query)) {
26
+ const value = Array.isArray(raw) ? raw[0] : raw;
27
+
28
+ if (typeof value === 'string' && key !== 'tab' && key !== 'page') {
29
+ result[key] = value;
30
+ }
31
+ }
32
+ if (tab !== tabs[0]) {
33
+ result.tab = tab;
34
+ }
35
+
36
+ return result;
37
+ }
@@ -0,0 +1,56 @@
1
+ // An unsent support message: its text, the attached files and the defect
2
+ // mark. It is kept in the page's memory while the customer moves around the
3
+ // shop, so leaving Support for another page and coming back does not lose
4
+ // what was written (the message form reads it when it opens).
5
+ //
6
+ // Memory only, on purpose: nothing is written to browser storage, so a
7
+ // reload or a closed tab starts clean and a shared computer keeps no text.
8
+ // On the server the memory belongs to every visitor at once, so there the
9
+ // functions keep nothing. A draft is the customer's own: its key starts
10
+ // with their ID, and another customer signing in on the same tab never
11
+ // sees it.
12
+ export interface TicketDraft {
13
+ text: string;
14
+ files: File[];
15
+ isDefect: boolean;
16
+ }
17
+
18
+ const drafts = new Map<string, TicketDraft>();
19
+ const inBrowser = typeof window !== 'undefined';
20
+
21
+ // `place` names the form: `new` for a common question, `new:item:15` for a
22
+ // conversation about an order item, `ticket:8` for a reply.
23
+ export function ticketDraftKey(customerId: number | undefined, place: string) {
24
+ return customerId ? `${customerId}:${place}` : '';
25
+ }
26
+
27
+ export function emptyTicketDraft(): TicketDraft {
28
+ return { text: '', files: [], isDefect: false };
29
+ }
30
+
31
+ export function isEmptyTicketDraft(draft: TicketDraft) {
32
+ return !draft.text.trim() && !draft.files.length && !draft.isDefect;
33
+ }
34
+
35
+ export function readTicketDraft(key: string): TicketDraft {
36
+ const draft = inBrowser && key ? drafts.get(key) : undefined;
37
+
38
+ return draft ? { ...draft, files: [...draft.files] } : emptyTicketDraft();
39
+ }
40
+
41
+ // An emptied form leaves no draft behind.
42
+ export function keepTicketDraft(key: string, draft: TicketDraft) {
43
+ if (!inBrowser || !key) {
44
+ return;
45
+ }
46
+ if (isEmptyTicketDraft(draft)) {
47
+ drafts.delete(key);
48
+ } else {
49
+ drafts.set(key, { ...draft, files: [...draft.files] });
50
+ }
51
+ }
52
+
53
+ // The message was sent or the customer pressed Cancel.
54
+ export function dropTicketDraft(key: string) {
55
+ drafts.delete(key);
56
+ }