@panomc/theme-core 1.1.0 → 1.2.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/assets/css/pano-fallback.css +10 -0
  2. package/lang/en-US.json +16 -0
  3. package/lang/ru.json +16 -0
  4. package/lang/tr.json +16 -0
  5. package/package.json +3 -3
  6. package/skin-contract.json +36 -2
  7. package/src/kit/__tests__/vite-config-dev-ssr.test.js +26 -0
  8. package/src/kit/vite-config.js +23 -0
  9. package/src/lib/__tests__/contentI18n.test.js +216 -0
  10. package/src/lib/__tests__/engineParts.helper.js +1 -0
  11. package/src/lib/__tests__/engineStyles.test.js +2 -2
  12. package/src/lib/__tests__/ticketFields.test.js +258 -0
  13. package/src/lib/components/Post.svelte +6 -1
  14. package/src/lib/components/Posts.svelte +6 -1
  15. package/src/lib/components/TicketFields.svelte +40 -0
  16. package/src/lib/components/TicketFieldsForm.svelte +63 -0
  17. package/src/lib/components/TicketRow.svelte +9 -1
  18. package/src/lib/contentI18n.js +227 -0
  19. package/src/lib/pages/HomePage.svelte +12 -1
  20. package/src/lib/pages/PostDetailPage.svelte +31 -2
  21. package/src/lib/pages/PreviewPostPage.svelte +14 -2
  22. package/src/lib/pages/RulesPage.svelte +14 -1
  23. package/src/lib/pages/profile/TicketsPage.svelte +22 -1
  24. package/src/lib/pages/ticket/CreateTicketPage.svelte +25 -3
  25. package/src/lib/pages/ticket/TicketDetailPage.svelte +21 -0
  26. package/src/lib/services/tickets.js +3 -0
  27. package/src/lib/siteRealtime.js +53 -1
  28. package/src/lib/ticketFields.js +354 -0
  29. package/src/lib/ui-logics/page-logics/CreateTicketPageLogics.js +40 -3
  30. package/src/lib/ui-logics/page-logics/PostDetailPageLogics.js +13 -1
  31. package/src/lib/ui-logics/page-logics/TicketDetailPageLogics.js +43 -3
  32. package/src/lib/ui-logics/page-logics/TicketsPageLogics.js +54 -5
  33. package/src/lib/views/CreateTicketView.svelte +6 -1
  34. package/src/lib/views/TicketDetailView.svelte +5 -1
  35. package/src/lib/views/parts/TicketFields.svelte +31 -0
  36. package/src/lib/views/parts/TicketFieldsForm.svelte +170 -0
  37. package/src/lib/views/parts/engine-views.generated.js +4 -2
@@ -0,0 +1,354 @@
1
+ // Custom fields of a ticket category: the pure rules shared by the create-ticket form and the ticket
2
+ // page. Visibility (section 3 of the fields contract) must match the backend and the panel exactly:
3
+ // change it in all three places together.
4
+
5
+ /** @typedef {"TEXT"|"TEXTAREA"|"NUMBER"|"EMAIL"|"URL"|"DATE"|"SELECT"|"MULTISELECT"|"CHECKBOX"} FieldType */
6
+
7
+ /**
8
+ * @typedef {object} FieldRule
9
+ * @property {string} field key of an earlier field
10
+ * @property {"EQUALS"|"NOT_EQUALS"|"CONTAINS"|"FILLED"|"EMPTY"} op
11
+ * @property {string} [value]
12
+ */
13
+
14
+ /**
15
+ * @typedef {object} FieldDefinition
16
+ * @property {string} key
17
+ * @property {string} label
18
+ * @property {FieldType} type
19
+ * @property {boolean} [required]
20
+ * @property {string} [placeholder]
21
+ * @property {string} [help]
22
+ * @property {{ value: string, label: string }[]} [options]
23
+ * @property {number|null} [min]
24
+ * @property {number|null} [max]
25
+ * @property {{ match: "ALL"|"ANY", rules: FieldRule[] } | null} [conditions]
26
+ */
27
+
28
+ /**
29
+ * Svelte context key of the create-ticket form's field state (`{ values, errors }`, both writable
30
+ * stores): the page sets it, the <TicketFieldsForm> controller reads it.
31
+ */
32
+ export const TICKET_FIELDS_CONTEXT = "pano:ticket-fields";
33
+
34
+ /** The error codes the create call answers per field (`error.fields["fields.<key>"]`). */
35
+ export const FIELD_ERROR_CODES = ["REQUIRED", "INVALID", "TOO_SHORT", "TOO_LONG", "OUT_OF_RANGE", "UNKNOWN_OPTION"];
36
+
37
+ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
38
+ const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
39
+ const HTTP_PATTERN = /^https?:\/\//i;
40
+
41
+ /** Default and hard maximum length of the text types (when `max` is null / too big). */
42
+ const TEXT_LIMITS = { TEXT: { max: 200, cap: 500 }, TEXTAREA: { max: 2000, cap: 5000 } };
43
+ const EMAIL_MAX = 254;
44
+ const URL_MAX = 500;
45
+
46
+ /**
47
+ * Empty = absent, `null`, a blank string, `[]`, or `false` for a CHECKBOX.
48
+ *
49
+ * @param {unknown} value
50
+ * @param {FieldType} [type]
51
+ * @returns {boolean}
52
+ */
53
+ export function isEmpty(value, type) {
54
+ if (value === undefined || value === null) return true;
55
+ if (typeof value === "string") return value.trim() === "";
56
+ if (Array.isArray(value)) return value.length === 0;
57
+ if (value === false) return type === "CHECKBOX";
58
+ if (typeof value === "number") return Number.isNaN(value);
59
+ return false;
60
+ }
61
+
62
+ const lower = (value) => String(value ?? "").trim().toLowerCase();
63
+
64
+ const toNumber = (value) => {
65
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
66
+ if (typeof value !== "string" || value.trim() === "") return null;
67
+ const number = Number(value.trim());
68
+ return Number.isFinite(number) ? number : null;
69
+ };
70
+
71
+ function equals(type, value, expected) {
72
+ if (type === "CHECKBOX") return String(value === true) === String(expected);
73
+ if (isEmpty(value, type)) return false;
74
+ if (type === "MULTISELECT") return Array.isArray(value) && value.includes(expected);
75
+ if (type === "NUMBER") {
76
+ const a = toNumber(value);
77
+ const b = toNumber(expected);
78
+ return a !== null && b !== null && a === b;
79
+ }
80
+ return lower(value) === lower(expected);
81
+ }
82
+
83
+ function contains(type, value, expected) {
84
+ if (type === "TEXT" || type === "TEXTAREA" || type === "EMAIL" || type === "URL") {
85
+ if (isEmpty(value, type)) return false;
86
+ return lower(value).includes(lower(expected));
87
+ }
88
+ return equals(type, value, expected);
89
+ }
90
+
91
+ /**
92
+ * Whether one rule holds. `value` is the referenced field's value, `undefined` when that field is
93
+ * hidden or missing (it counts as empty).
94
+ *
95
+ * @param {FieldRule} rule
96
+ * @param {FieldType | undefined} type the referenced field's type
97
+ * @param {unknown} value
98
+ */
99
+ export function ruleHolds(rule, type, value) {
100
+ switch (rule.op) {
101
+ case "FILLED":
102
+ return !isEmpty(value, type);
103
+ case "EMPTY":
104
+ return isEmpty(value, type);
105
+ case "EQUALS":
106
+ return equals(type, value, rule.value);
107
+ case "NOT_EQUALS":
108
+ return !equals(type, value, rule.value);
109
+ case "CONTAINS":
110
+ return contains(type, value, rule.value);
111
+ default:
112
+ return false;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * The fields that are shown for the given values, in order. A rule reads an earlier field; a field
118
+ * that is not visible (or not defined) counts as empty.
119
+ *
120
+ * @param {FieldDefinition[] | null | undefined} definitions
121
+ * @param {Record<string, unknown> | null | undefined} values
122
+ * @returns {FieldDefinition[]}
123
+ */
124
+ export function visibleFields(definitions, values) {
125
+ const shown = new Map();
126
+ const result = [];
127
+
128
+ for (const definition of definitions ?? []) {
129
+ const rules = definition.conditions?.rules ?? [];
130
+ let visible = true;
131
+
132
+ if (definition.conditions && rules.length > 0) {
133
+ const check = (rule) => {
134
+ const ref = shown.get(rule.field);
135
+ return ruleHolds(rule, ref?.type, ref ? values?.[rule.field] : undefined);
136
+ };
137
+
138
+ visible = definition.conditions.match === "ANY" ? rules.some(check) : rules.every(check);
139
+ }
140
+
141
+ if (visible) {
142
+ shown.set(definition.key, definition);
143
+ result.push(definition);
144
+ }
145
+ }
146
+
147
+ return result;
148
+ }
149
+
150
+ /**
151
+ * The bounds a field's value is checked against: the number bounds for NUMBER, the length bounds for
152
+ * the text types (with the default and hard maximum), the length limit of EMAIL / URL.
153
+ *
154
+ * @param {FieldDefinition} definition
155
+ * @returns {{ min: number | null, max: number | null }}
156
+ */
157
+ export function fieldLimits(definition) {
158
+ const min = typeof definition.min === "number" ? definition.min : null;
159
+ const max = typeof definition.max === "number" ? definition.max : null;
160
+ const text = TEXT_LIMITS[definition.type];
161
+
162
+ if (text) return { min, max: max === null ? text.max : Math.min(max, text.cap) };
163
+ if (definition.type === "NUMBER") return { min, max };
164
+ if (definition.type === "EMAIL") return { min: null, max: EMAIL_MAX };
165
+ if (definition.type === "URL") return { min: null, max: URL_MAX };
166
+ return { min: null, max: null };
167
+ }
168
+
169
+ /** Whether `YYYY-MM-DD` names a real day. */
170
+ export function isValidDate(value) {
171
+ const match = typeof value === "string" ? DATE_PATTERN.exec(value.trim()) : null;
172
+ if (!match) return false;
173
+
174
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
175
+ const date = new Date(Date.UTC(year, month - 1, day));
176
+
177
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
178
+ }
179
+
180
+ const isHttpUrl = (value) => {
181
+ if (!HTTP_PATTERN.test(value)) return false;
182
+ try {
183
+ const url = new URL(value);
184
+ return (url.protocol === "http:" || url.protocol === "https:") && url.hostname !== "";
185
+ } catch {
186
+ return false;
187
+ }
188
+ };
189
+
190
+ /**
191
+ * Checks one value of a visible field. Returns the error code the server would answer, or `null`.
192
+ *
193
+ * @param {FieldDefinition} definition
194
+ * @param {unknown} value
195
+ * @returns {string | null}
196
+ */
197
+ export function validateValue(definition, value) {
198
+ const type = definition.type;
199
+
200
+ if (isEmpty(value, type)) return definition.required ? "REQUIRED" : null;
201
+
202
+ const { min, max } = fieldLimits(definition);
203
+ const options = (definition.options ?? []).map((option) => option.value);
204
+
205
+ switch (type) {
206
+ case "TEXT":
207
+ case "TEXTAREA": {
208
+ if (typeof value !== "string") return "INVALID";
209
+ const length = value.trim().length;
210
+ if (min !== null && length < min) return "TOO_SHORT";
211
+ if (max !== null && length > max) return "TOO_LONG";
212
+ return null;
213
+ }
214
+ case "EMAIL": {
215
+ if (typeof value !== "string") return "INVALID";
216
+ const text = value.trim();
217
+ if (text.length > EMAIL_MAX) return "TOO_LONG";
218
+ return EMAIL_PATTERN.test(text) ? null : "INVALID";
219
+ }
220
+ case "URL": {
221
+ if (typeof value !== "string") return "INVALID";
222
+ const text = value.trim();
223
+ if (text.length > URL_MAX) return "TOO_LONG";
224
+ return isHttpUrl(text) ? null : "INVALID";
225
+ }
226
+ case "DATE":
227
+ return isValidDate(value) ? null : "INVALID";
228
+ case "NUMBER": {
229
+ const number = toNumber(value);
230
+ if (number === null) return "INVALID";
231
+ if ((min !== null && number < min) || (max !== null && number > max)) return "OUT_OF_RANGE";
232
+ return null;
233
+ }
234
+ case "SELECT":
235
+ if (typeof value !== "string") return "INVALID";
236
+ return options.includes(value.trim()) ? null : "UNKNOWN_OPTION";
237
+ case "MULTISELECT":
238
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) return "INVALID";
239
+ if (new Set(value).size !== value.length) return "INVALID";
240
+ return value.every((item) => options.includes(item)) ? null : "UNKNOWN_OPTION";
241
+ case "CHECKBOX":
242
+ return typeof value === "boolean" ? null : "INVALID";
243
+ default:
244
+ return "INVALID";
245
+ }
246
+ }
247
+
248
+ /** The value as it is sent: strings trimmed, numbers as numbers. */
249
+ function normalize(type, value) {
250
+ if (typeof value === "string") {
251
+ const text = value.trim();
252
+ return type === "NUMBER" ? Number(text) : text;
253
+ }
254
+ return value;
255
+ }
256
+
257
+ /**
258
+ * Checks the visible fields and builds the `fields` object of the create call: only visible,
259
+ * non-empty values. Hidden fields are dropped and not checked.
260
+ *
261
+ * @param {FieldDefinition[] | null | undefined} definitions
262
+ * @param {Record<string, unknown> | null | undefined} values
263
+ * @returns {{ fields: Record<string, unknown>, errors: Record<string, string>, valid: boolean }}
264
+ */
265
+ export function prepareFieldValues(definitions, values) {
266
+ /** @type {Record<string, unknown>} */
267
+ const fields = {};
268
+ /** @type {Record<string, string>} */
269
+ const errors = {};
270
+
271
+ for (const definition of visibleFields(definitions, values)) {
272
+ const value = values?.[definition.key];
273
+ const code = validateValue(definition, value);
274
+
275
+ if (code) errors[definition.key] = code;
276
+ else if (!isEmpty(value, definition.type)) fields[definition.key] = normalize(definition.type, value);
277
+ }
278
+
279
+ return { fields, errors, valid: Object.keys(errors).length === 0 };
280
+ }
281
+
282
+ /**
283
+ * Reads the server's `error.fields` (`{ "fields.<key>": CODE }`) into `{ <key>: CODE }`.
284
+ *
285
+ * @param {Record<string, string> | null | undefined} errorFields
286
+ * @returns {Record<string, string>}
287
+ */
288
+ export function fieldErrorsFromServer(errorFields) {
289
+ /** @type {Record<string, string>} */
290
+ const result = {};
291
+
292
+ for (const [path, code] of Object.entries(errorFields ?? {})) {
293
+ if (path.startsWith("fields.")) result[path.slice("fields.".length)] = String(code);
294
+ }
295
+
296
+ return result;
297
+ }
298
+
299
+ /**
300
+ * Whether a snapshot entry of `ticket.fields` holds a value worth showing.
301
+ *
302
+ * @param {{ type: FieldType, value: unknown }} entry
303
+ */
304
+ export function hasValue(entry) {
305
+ return !!entry && !isEmpty(entry.value, entry.type);
306
+ }
307
+
308
+ /**
309
+ * The readable form of a snapshot entry (`ticket.fields[i]`): `text` to show and, for a URL with
310
+ * http(s) or an e-mail, the `href` of a link.
311
+ *
312
+ * @param {{ type: FieldType, value: unknown, display?: string, options?: { value: string, label: string }[] }} entry
313
+ * @param {{ locale?: string | null, yes?: string, no?: string }} [options]
314
+ * @returns {{ text: string, href: string | null }}
315
+ */
316
+ export function displayValue(entry, { locale, yes = "Yes", no = "No" } = {}) {
317
+ const value = entry.value;
318
+ const display = typeof entry.display === "string" && entry.display !== "" ? entry.display : null;
319
+ const label = (optionValue) =>
320
+ (entry.options ?? []).find((option) => option.value === optionValue)?.label ?? String(optionValue);
321
+
322
+ switch (entry.type) {
323
+ case "CHECKBOX":
324
+ return { text: value === true ? yes : no, href: null };
325
+ case "DATE": {
326
+ if (isValidDate(value)) {
327
+ const [year, month, day] = String(value).trim().split("-").map(Number);
328
+ try {
329
+ const text = new Intl.DateTimeFormat(locale || undefined, { dateStyle: "medium", timeZone: "UTC" }).format(
330
+ new Date(Date.UTC(year, month - 1, day)),
331
+ );
332
+ return { text, href: null };
333
+ } catch {
334
+ /* unknown locale: fall through to the raw value */
335
+ }
336
+ }
337
+ return { text: display ?? String(value ?? ""), href: null };
338
+ }
339
+ case "URL": {
340
+ const text = String(value ?? "").trim();
341
+ return { text, href: isHttpUrl(text) ? text : null };
342
+ }
343
+ case "EMAIL": {
344
+ const text = String(value ?? "").trim();
345
+ return { text, href: EMAIL_PATTERN.test(text) ? `mailto:${text}` : null };
346
+ }
347
+ case "MULTISELECT":
348
+ return { text: display ?? (Array.isArray(value) ? value.map(label).join(", ") : String(value ?? "")), href: null };
349
+ case "SELECT":
350
+ return { text: display ?? label(value), href: null };
351
+ default:
352
+ return { text: display ?? String(value ?? ""), href: null };
353
+ }
354
+ }
@@ -4,6 +4,7 @@ import { error as throwError } from "@sveltejs/kit";
4
4
  import { goto } from "$app/navigation";
5
5
 
6
6
  import { createTicket, getTicketCategories } from "$pano/lib/services/tickets";
7
+ import { fieldErrorsFromServer, prepareFieldValues } from "$pano/lib/ticketFields.js";
7
8
 
8
9
  import { NETWORK_ERROR } from "$pano/lib/api.util";
9
10
  import { showSuccess as showSuccessToast } from "$pano/lib/components/ToastContainer.svelte";
@@ -56,19 +57,55 @@ export async function processLoad(event) {
56
57
  };
57
58
  }
58
59
 
59
- export async function submit(error, loading, title, message, categoryId) {
60
+ /**
61
+ * Sends the create-ticket request. `fieldState` (optional) carries the custom fields of the chosen
62
+ * category: `{ categories, values, errors }` (values / errors are writable stores keyed by field key).
63
+ * Only the visible, non-empty values are sent; a client-side check failure or a server
64
+ * `INVALID_FIELDS` answer fills `errors` and stops.
65
+ */
66
+ export async function submit(error, loading, title, message, categoryId, fieldState) {
60
67
  error.set(null);
68
+
69
+ let fields;
70
+
71
+ if (fieldState) {
72
+ const id = get(categoryId);
73
+ const category = (fieldState.categories ?? []).find((item) => String(item.id) === String(id));
74
+ const definitions = category?.fields ?? [];
75
+
76
+ if (definitions.length > 0) {
77
+ const prepared = prepareFieldValues(definitions, get(fieldState.values));
78
+
79
+ fieldState.errors.set(prepared.errors);
80
+
81
+ if (!prepared.valid) {
82
+ error.set("INVALID_FIELDS");
83
+
84
+ return;
85
+ }
86
+
87
+ if (Object.keys(prepared.fields).length > 0) fields = prepared.fields;
88
+ } else {
89
+ fieldState.errors.set({});
90
+ }
91
+ }
92
+
61
93
  loading.set(true);
62
94
 
63
95
  await createTicket({
64
96
  title: get(title),
65
97
  message: get(message),
66
- categoryId: get(categoryId)
98
+ categoryId: get(categoryId),
99
+ fields
67
100
  })
68
101
  .then((body) => {
69
102
  loading.set(false);
70
103
 
71
104
  if (body.error) {
105
+ if (body.error.code === "INVALID_FIELDS" && fieldState) {
106
+ fieldState.errors.set(fieldErrorsFromServer(body.error.fields));
107
+ }
108
+
72
109
  error.set(body.error.code);
73
110
 
74
111
  return;
@@ -83,4 +120,4 @@ export async function submit(error, loading, title, message, categoryId) {
83
120
 
84
121
  error.set(NETWORK_ERROR);
85
122
  });
86
- }
123
+ }
@@ -1,4 +1,8 @@
1
1
  import { error } from "@sveltejs/kit";
2
+ import { get } from "svelte/store";
3
+ import { locale } from "svelte-i18n";
4
+
5
+ import { localized } from "$pano/lib/contentI18n.js";
2
6
 
3
7
  import { getPostDetail } from "$pano/lib/services/posts";
4
8
  import { executeHookLoad, executeLifecycle } from "$pano/lib/PluginAPI.js";
@@ -52,7 +56,15 @@ export async function processLoad(event) {
52
56
  ...(await executeHookLoad("theme:post-detail:bottom", event)),
53
57
  };
54
58
 
55
- data.pageTitle = data.post.title;
59
+ data.pageTitle = postPageTitle(data.post);
56
60
 
57
61
  return { ...data };
58
62
  }
63
+
64
+ /**
65
+ * The page title of a post: its title in `code` (default: the current svelte-i18n locale), taken from
66
+ * its `i18n` (translated content) with the default title as the fallback.
67
+ */
68
+ export function postPageTitle(post, code = get(locale)) {
69
+ return localized(post?.title, post?.i18n, code, "title");
70
+ }
@@ -1,7 +1,7 @@
1
1
  import { afterUpdate, onMount } from "svelte";
2
2
  import { get, writable } from "svelte/store";
3
3
  import { error } from "@sveltejs/kit";
4
- import { _ } from "svelte-i18n";
4
+ import { _, locale } from "svelte-i18n";
5
5
 
6
6
  import { route } from "$pano/registry/routes.js";
7
7
 
@@ -16,6 +16,9 @@ import { setCallback as setCloseTicketConfirmCallback } from "$pano/lib/componen
16
16
 
17
17
  import { TicketStatuses } from "$pano/lib/components/TicketStatus.svelte";
18
18
 
19
+ import { onTicketChanged } from "$pano/lib/siteRealtime.js";
20
+ import { localized } from "$pano/lib/contentI18n.js";
21
+
19
22
  /**
20
23
  * @type {import("@sveltejs/kit").Load}
21
24
  */
@@ -65,11 +68,14 @@ const escapeHtml = (text) =>
65
68
  * The page title of a ticket: its number and title, and under it the category it was opened in (a
66
69
  * link to that category's tickets). It is the only title on the page; the view draws none of its own.
67
70
  * Translated here because the title is taken verbatim (`raw`): the ticket's own title is not a key.
71
+ * The category title is taken in `code` (default: the current svelte-i18n locale) from its `i18n`.
68
72
  */
69
- export function ticketPageTitle(ticket) {
73
+ export function ticketPageTitle(ticket, code = get(locale)) {
70
74
  const translate = get(_);
71
75
  const hasCategory = ticket.category && ticket.category !== "-";
72
- const name = hasCategory ? ticket.category.title : translate("pages.ticket-detail.no-category");
76
+ const name = hasCategory
77
+ ? localized(ticket.category.title, ticket.category.i18n, code, "title")
78
+ : translate("pages.ticket-detail.no-category");
73
79
  const link = `<a href="${route("/tickets")}?category=${encodeURIComponent(
74
80
  hasCategory ? ticket.category.url : "-",
75
81
  )}" title="${escapeHtml(translate("pages.ticket-detail.filter"))}">${escapeHtml(name)}</a>`;
@@ -94,6 +100,35 @@ export function applyTicket(stores, ticket) {
94
100
  updateSidebar(ticket);
95
101
  }
96
102
 
103
+ /**
104
+ * The ticket changed on the server (a staff reply, closed in the panel): reads it again and puts the
105
+ * new messages after the ones on the page, keeping older ones the user loaded with "load more".
106
+ */
107
+ export async function refreshTicket(stores, ticketId) {
108
+ const body = await getTicketDetail({ id: ticketId });
109
+
110
+ if (!body || body.error || !body.ticket) return;
111
+
112
+ const fresh = body.ticket;
113
+ const known = new Map(get(stores.messages).map((message) => [message.id, message]));
114
+ let added = false;
115
+
116
+ for (const message of fresh.messages ?? []) {
117
+ if (!known.has(message.id)) added = true;
118
+
119
+ known.set(message.id, message);
120
+ }
121
+
122
+ const merged = [...known.values()].sort((a, b) => a.id - b.id);
123
+
124
+ stores.ticket.set({ ...fresh, messages: merged });
125
+ stores.messages.set(merged);
126
+
127
+ if (added) stores.shouldScroll.set(true);
128
+
129
+ updateSidebar(get(stores.ticket));
130
+ }
131
+
97
132
  export async function loadMore(loadMoreLoading, messages, data) {
98
133
  loadMoreLoading.set(true);
99
134
 
@@ -170,6 +205,11 @@ export function init(data) {
170
205
 
171
206
  onMount(() => {
172
207
  shouldScroll.set(true);
208
+
209
+ // a staff reply or a status change shows up without a reload
210
+ return onTicketChanged(data.ticket.id, () => {
211
+ refreshTicket({ ticket, messages, shouldScroll }, get(ticket).id);
212
+ });
173
213
  });
174
214
 
175
215
  setCloseTicketConfirmCallback(() => {
@@ -1,5 +1,7 @@
1
1
  import { error } from "@sveltejs/kit";
2
- import { writable } from "svelte/store";
2
+ import { onMount } from "svelte";
3
+ import { get, writable } from "svelte/store";
4
+ import { locale } from "svelte-i18n";
3
5
 
4
6
  import { goto } from "$app/navigation";
5
7
 
@@ -7,6 +9,8 @@ import { buildQueryParams } from "$pano/lib/api.util";
7
9
  import { executeLifecycle, executeViewLoad, panoApiServer } from "$pano/lib/PluginAPI";
8
10
 
9
11
  import { getTickets } from "$pano/lib/services/tickets";
12
+ import { onTicketChanged } from "$pano/lib/siteRealtime.js";
13
+ import { localized } from "$pano/lib/contentI18n.js";
10
14
 
11
15
  import { TicketStatuses } from "$pano/lib/components/TicketStatus.svelte";
12
16
  import ProfileSidebar, { load as loadSidebar } from "$pano/lib/components/sidebars/ProfileSidebar.svelte";
@@ -65,14 +69,28 @@ export async function processLoad(event) {
65
69
 
66
70
  await loadSidebar(event);
67
71
 
68
- data.pageTitle = {
72
+ data.pageTitle = ticketsPageTitle(data, get(locale));
73
+
74
+ return { ...data, sidebar: ProfileSidebar, sidebarProps: { showCreateTicket: true } };
75
+ }
76
+
77
+ /**
78
+ * The page title of the tickets list; a category filter names the category in the given locale.
79
+ *
80
+ * @param {{ categoryUrl?: string | null, category?: { title?: string, i18n?: object } | null }} data
81
+ * @param {string | null | undefined} code svelte-i18n locale
82
+ */
83
+ export function ticketsPageTitle(data, code) {
84
+ const categoryUrl = data.categoryUrl;
85
+
86
+ return {
69
87
  title: categoryUrl ? "pages.category-tickets.title" : "pages.tickets.title",
70
88
  titleValues: categoryUrl ? {
71
- categoryName: `"${data.category.title}"`
89
+ categoryName: `"${data.category?.title === "-"
90
+ ? data.category.title
91
+ : localized(data.category?.title, data.category?.i18n, code, "title")}"`
72
92
  } : null
73
93
  };
74
-
75
- return { ...data, sidebar: ProfileSidebar, sidebarProps: { showCreateTicket: true } };
76
94
  }
77
95
 
78
96
  async function refreshData(data) {
@@ -104,9 +122,40 @@ export const onCloseTicketClick = (tickets, updatedTicket) => {
104
122
  showCloseTicketConfirmModal(updatedTicket);
105
123
  };
106
124
 
125
+ /** A burst of changes (several tickets closed at once) is read once. */
126
+ const LIVE_REFRESH_DELAY_MS = 300;
127
+
128
+ /** Reads the open page of the list again (a ticket changed on the server) and keeps the selection. */
129
+ export async function refreshTickets(tickets, data) {
130
+ const body = await getTickets({ page: data.page, pageType: data.pageType, categoryUrl: data.categoryUrl });
131
+
132
+ if (!body || body.error || !Array.isArray(body.tickets)) return;
133
+
134
+ tickets.update((current) => {
135
+ const selected = new Set(current.filter((ticket) => ticket.selected).map((ticket) => ticket.id));
136
+
137
+ return body.tickets.map((ticket) => ({ ...ticket, selected: selected.has(ticket.id) }));
138
+ });
139
+ }
140
+
107
141
  export function init(data) {
108
142
  const tickets = writable(data.tickets);
109
143
 
144
+ onMount(() => {
145
+ let timer;
146
+
147
+ // a staff reply or a ticket closed in the panel updates the list without a reload
148
+ const stop = onTicketChanged(null, () => {
149
+ clearTimeout(timer);
150
+ timer = setTimeout(() => refreshTickets(tickets, data), LIVE_REFRESH_DELAY_MS);
151
+ });
152
+
153
+ return () => {
154
+ clearTimeout(timer);
155
+ stop();
156
+ };
157
+ });
158
+
110
159
  setCloseTicketConfirmCallback((updatedTicket) => {
111
160
  tickets.update(tickets => {
112
161
  tickets.forEach((ticket) => {
@@ -6,7 +6,7 @@
6
6
  error writable store — submit error shown by ErrorAlert
7
7
  title writable store — ticket title field value
8
8
  message writable store — ticket message textarea value
9
- categoryId writable store — selected category id (-1 = no category)
9
+ categoryId writable store — selected category id (-1 = no category); its custom fields render in <TicketFieldsForm>
10
10
  loading writable store — request in-flight flag
11
11
  submit function — (error, loading, title, message, categoryId) sends the create-ticket request
12
12
  Override from a theme:
@@ -27,6 +27,7 @@
27
27
  import { _ } from "svelte-i18n";
28
28
 
29
29
  import ErrorAlert from "$pano/lib/components/ErrorAlert.svelte";
30
+ import TicketFieldsForm from "$pano/lib/components/TicketFieldsForm.svelte";
30
31
 
31
32
  export let data;
32
33
  export let error;
@@ -37,6 +38,7 @@
37
38
  export let submit;
38
39
 
39
40
  $: isButtonDisabled = $title === "" || $message === "";
41
+ $: selectedCategory = (data.categories ?? []).find((category) => String(category.id) === String($categoryId)) ?? null;
40
42
  </script>
41
43
 
42
44
  <div class="pano-create-ticket-view vstack gap-3">
@@ -63,6 +65,9 @@
63
65
  </select>
64
66
  </div>
65
67
 
68
+ <!-- The chosen category's custom fields (nothing when it has none) -->
69
+ <TicketFieldsForm category={selectedCategory} />
70
+
66
71
  <!-- Ticket Editor -->
67
72
 
68
73
  <textarea bind:value={$message} class="pano-create-ticket-view__input-2 form-control" rows="6"></textarea>
@@ -3,7 +3,7 @@
3
3
  Controller: $pano/lib/pages/ticket/TicketDetailPage.svelte
4
4
  Props:
5
5
  data object — page data from load (ticket, messages, sidebar config)
6
- ticket store — the ticket being viewed (id, title, category, status, date, messageCount)
6
+ ticket store — the ticket being viewed (id, title, category, status, date, messageCount, fields)
7
7
  messages store — currently loaded ticket messages, oldest first
8
8
  message store — current text of the reply textarea
9
9
  messageSendLoading store — true while a reply is being sent
@@ -28,6 +28,9 @@
28
28
  </style>
29
29
 
30
30
  <div class="pano-ticket-detail-view vstack gap-3">
31
+ <!-- The ticket's custom field values (nothing when it has none) -->
32
+ <TicketFields fields={$ticket.fields} />
33
+
31
34
  <div class="card mt-lg-0">
32
35
  <CardHeader>
33
36
  <small slot="left" class="text-body-secondary">
@@ -152,6 +155,7 @@
152
155
  TicketStatuses,
153
156
  } from "$pano/lib/components/TicketStatus.svelte";
154
157
  import CardHeader from "$pano/lib/components/CardHeader.svelte";
158
+ import TicketFields from "$pano/lib/components/TicketFields.svelte";
155
159
 
156
160
  export let data;
157
161
  export let ticket;