@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,258 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import {
4
+ displayValue,
5
+ fieldErrorsFromServer,
6
+ fieldLimits,
7
+ hasValue,
8
+ isEmpty,
9
+ isValidDate,
10
+ prepareFieldValues,
11
+ validateValue,
12
+ visibleFields,
13
+ } from "../ticketFields.js";
14
+
15
+ const field = (key, type, extra = {}) => ({
16
+ key,
17
+ label: key,
18
+ type,
19
+ required: false,
20
+ placeholder: "",
21
+ help: "",
22
+ options: [],
23
+ min: null,
24
+ max: null,
25
+ conditions: null,
26
+ ...extra,
27
+ });
28
+
29
+ const rule = (fieldKey, op, value) => ({ field: fieldKey, op, ...(value === undefined ? {} : { value }) });
30
+ const when = (match, ...rules) => ({ conditions: { match, rules } });
31
+ const keys = (definitions, values) => visibleFields(definitions, values).map((definition) => definition.key);
32
+
33
+ const topic = field("topic", "SELECT", {
34
+ options: [
35
+ { value: "appeal", label: "Ban appeal" },
36
+ { value: "bug", label: "Bug" },
37
+ ],
38
+ });
39
+ const banId = field("ban-id", "TEXT", when("ALL", rule("topic", "EQUALS", "appeal")));
40
+ const reason = field("reason", "TEXTAREA", when("ALL", rule("ban-id", "FILLED")));
41
+ const chain = [topic, banId, reason];
42
+
43
+ describe("isEmpty", () => {
44
+ test("absent, null, blank, [] and an unticked checkbox are empty", () => {
45
+ expect(isEmpty(undefined)).toBe(true);
46
+ expect(isEmpty(null)).toBe(true);
47
+ expect(isEmpty(" ")).toBe(true);
48
+ expect(isEmpty([])).toBe(true);
49
+ expect(isEmpty(false, "CHECKBOX")).toBe(true);
50
+ expect(isEmpty(0, "NUMBER")).toBe(false);
51
+ expect(isEmpty("x")).toBe(false);
52
+ expect(isEmpty(true, "CHECKBOX")).toBe(false);
53
+ });
54
+ });
55
+
56
+ describe("visibleFields", () => {
57
+ test("chained conditions: A=appeal shows B, B filled shows C", () => {
58
+ expect(keys(chain, {})).toEqual(["topic"]);
59
+ expect(keys(chain, { topic: "bug" })).toEqual(["topic"]);
60
+ expect(keys(chain, { topic: "appeal" })).toEqual(["topic", "ban-id"]);
61
+ expect(keys(chain, { topic: "APPEAL " })).toEqual(["topic", "ban-id"]);
62
+ expect(keys(chain, { topic: "appeal", "ban-id": "123" })).toEqual(["topic", "ban-id", "reason"]);
63
+ });
64
+
65
+ test("a rule on a hidden field reads it as empty", () => {
66
+ // ban-id still holds a value, but it is hidden once the topic changes: reason hides too
67
+ expect(keys(chain, { topic: "bug", "ban-id": "123" })).toEqual(["topic"]);
68
+
69
+ const ifHiddenEmpty = field("note", "TEXT", when("ALL", rule("ban-id", "EMPTY")));
70
+ expect(keys([topic, banId, ifHiddenEmpty], { topic: "bug", "ban-id": "123" })).toEqual(["topic", "note"]);
71
+ });
72
+
73
+ test("ANY needs one rule, ALL needs every rule", () => {
74
+ const a = field("a", "TEXT");
75
+ const b = field("b", "TEXT");
76
+ const any = field("any", "TEXT", when("ANY", rule("a", "FILLED"), rule("b", "FILLED")));
77
+ const all = field("all", "TEXT", when("ALL", rule("a", "FILLED"), rule("b", "FILLED")));
78
+ const list = [a, b, any, all];
79
+
80
+ expect(keys(list, {})).toEqual(["a", "b"]);
81
+ expect(keys(list, { a: "x" })).toEqual(["a", "b", "any"]);
82
+ expect(keys(list, { a: "x", b: "y" })).toEqual(["a", "b", "any", "all"]);
83
+ });
84
+
85
+ test("MULTISELECT EQUALS and CONTAINS test membership", () => {
86
+ const tags = field("tags", "MULTISELECT", {
87
+ options: [
88
+ { value: "pvp", label: "PvP" },
89
+ { value: "chat", label: "Chat" },
90
+ ],
91
+ });
92
+ const eq = field("eq", "TEXT", when("ALL", rule("tags", "EQUALS", "pvp")));
93
+ const has = field("has", "TEXT", when("ALL", rule("tags", "CONTAINS", "chat")));
94
+ const not = field("not", "TEXT", when("ALL", rule("tags", "NOT_EQUALS", "pvp")));
95
+ const list = [tags, eq, has, not];
96
+
97
+ expect(keys(list, { tags: ["pvp"] })).toEqual(["tags", "eq"]);
98
+ expect(keys(list, { tags: ["chat", "pvp"] })).toEqual(["tags", "eq", "has"]);
99
+ expect(keys(list, { tags: [] })).toEqual(["tags", "not"]);
100
+ });
101
+
102
+ test('CHECKBOX compares "true" / "false"; an unticked box is false', () => {
103
+ const box = field("box", "CHECKBOX");
104
+ const on = field("on", "TEXT", when("ALL", rule("box", "EQUALS", "true")));
105
+ const off = field("off", "TEXT", when("ALL", rule("box", "EQUALS", "false")));
106
+ const list = [box, on, off];
107
+
108
+ expect(keys(list, { box: true })).toEqual(["box", "on"]);
109
+ expect(keys(list, { box: false })).toEqual(["box", "off"]);
110
+ expect(keys(list, {})).toEqual(["box", "off"]);
111
+ });
112
+
113
+ test("NOT_EQUALS on an empty value is true, EQUALS is false", () => {
114
+ const a = field("a", "TEXT");
115
+ const ne = field("ne", "TEXT", when("ALL", rule("a", "NOT_EQUALS", "x")));
116
+ const eq = field("eq", "TEXT", when("ALL", rule("a", "EQUALS", "x")));
117
+
118
+ expect(keys([a, ne, eq], {})).toEqual(["a", "ne"]);
119
+ expect(keys([a, ne, eq], { a: " " })).toEqual(["a", "ne"]);
120
+ expect(keys([a, ne, eq], { a: "X" })).toEqual(["a", "eq"]);
121
+ });
122
+
123
+ test("TEXT CONTAINS is a case-insensitive substring, NUMBER EQUALS compares numbers", () => {
124
+ const text = field("text", "TEXT");
125
+ const num = field("num", "NUMBER");
126
+ const sub = field("sub", "TEXT", when("ALL", rule("text", "CONTAINS", "hack")));
127
+ const five = field("five", "TEXT", when("ALL", rule("num", "EQUALS", "5")));
128
+ const list = [text, num, sub, five];
129
+
130
+ expect(keys(list, { text: "Someone HACKED me", num: "5.0" })).toEqual(["text", "num", "sub", "five"]);
131
+ expect(keys(list, { text: "hello", num: 6 })).toEqual(["text", "num"]);
132
+ });
133
+
134
+ test("a rule on a later or unknown field counts as empty", () => {
135
+ const first = field("first", "TEXT", when("ALL", rule("second", "FILLED")));
136
+ const second = field("second", "TEXT");
137
+
138
+ expect(keys([first, second], { second: "x" })).toEqual(["second"]);
139
+ expect(keys([field("x", "TEXT", when("ALL", rule("nope", "EMPTY")))], {})).toEqual(["x"]);
140
+ });
141
+
142
+ test("no definitions shows nothing", () => {
143
+ expect(visibleFields(undefined, {})).toEqual([]);
144
+ expect(visibleFields([], undefined)).toEqual([]);
145
+ });
146
+ });
147
+
148
+ describe("validateValue", () => {
149
+ test("required is enforced on empty values; a required checkbox must be ticked", () => {
150
+ expect(validateValue(field("a", "TEXT", { required: true }), " ")).toBe("REQUIRED");
151
+ expect(validateValue(field("a", "TEXT"), "")).toBeNull();
152
+ expect(validateValue(field("c", "CHECKBOX", { required: true }), false)).toBe("REQUIRED");
153
+ expect(validateValue(field("c", "CHECKBOX", { required: true }), true)).toBeNull();
154
+ });
155
+
156
+ test("number bounds, decimals and numeric strings", () => {
157
+ const number = field("n", "NUMBER", { min: 1, max: 10.5 });
158
+
159
+ expect(validateValue(number, 1)).toBeNull();
160
+ expect(validateValue(number, "10.5")).toBeNull();
161
+ expect(validateValue(number, 0.99)).toBe("OUT_OF_RANGE");
162
+ expect(validateValue(number, 11)).toBe("OUT_OF_RANGE");
163
+ expect(validateValue(number, "abc")).toBe("INVALID");
164
+ expect(validateValue(field("n", "NUMBER", { min: 0 }), 999999)).toBeNull();
165
+ });
166
+
167
+ test("text length bounds and the default maximum", () => {
168
+ const text = field("t", "TEXT", { min: 3, max: 5 });
169
+
170
+ expect(validateValue(text, " ab ")).toBe("TOO_SHORT");
171
+ expect(validateValue(text, "abcd")).toBeNull();
172
+ expect(validateValue(text, "abcdef")).toBe("TOO_LONG");
173
+ expect(validateValue(field("t", "TEXT"), "x".repeat(201))).toBe("TOO_LONG");
174
+ expect(validateValue(field("t", "TEXTAREA"), "x".repeat(2000))).toBeNull();
175
+ expect(fieldLimits(field("t", "TEXT", { max: 9999 })).max).toBe(500);
176
+ });
177
+
178
+ test("dates must be real days", () => {
179
+ const date = field("d", "DATE");
180
+
181
+ expect(validateValue(date, "2026-02-28")).toBeNull();
182
+ expect(validateValue(date, "2026-02-30")).toBe("INVALID");
183
+ expect(validateValue(date, "2024-02-29")).toBeNull();
184
+ expect(validateValue(date, "2026-13-01")).toBe("INVALID");
185
+ expect(validateValue(date, "26-1-1")).toBe("INVALID");
186
+ expect(isValidDate("2025-02-29")).toBe(false);
187
+ });
188
+
189
+ test("email and url", () => {
190
+ const email = field("e", "EMAIL");
191
+ const url = field("u", "URL");
192
+
193
+ expect(validateValue(email, " a@b.co ")).toBeNull();
194
+ expect(validateValue(email, "a@b")).toBe("INVALID");
195
+ expect(validateValue(email, "a b@c.de")).toBe("INVALID");
196
+ expect(validateValue(email, `${"a".repeat(250)}@b.co`)).toBe("TOO_LONG");
197
+ expect(validateValue(url, "https://example.com/x")).toBeNull();
198
+ expect(validateValue(url, "http://example.com")).toBeNull();
199
+ expect(validateValue(url, "ftp://example.com")).toBe("INVALID");
200
+ expect(validateValue(url, "javascript:alert(1)")).toBe("INVALID");
201
+ expect(validateValue(url, "example.com")).toBe("INVALID");
202
+ expect(validateValue(url, `https://e.com/${"x".repeat(500)}`)).toBe("TOO_LONG");
203
+ });
204
+
205
+ test("select and multiselect options", () => {
206
+ expect(validateValue(topic, "appeal")).toBeNull();
207
+ expect(validateValue(topic, "other")).toBe("UNKNOWN_OPTION");
208
+
209
+ const multi = field("m", "MULTISELECT", { options: topic.options });
210
+ expect(validateValue(multi, ["appeal", "bug"])).toBeNull();
211
+ expect(validateValue(multi, ["appeal", "appeal"])).toBe("INVALID");
212
+ expect(validateValue(multi, ["nope"])).toBe("UNKNOWN_OPTION");
213
+ });
214
+ });
215
+
216
+ describe("prepareFieldValues", () => {
217
+ test("sends only visible, non-empty values, trimmed; hidden fields are not checked", () => {
218
+ const required = field("must", "TEXT", { required: true, ...when("ALL", rule("topic", "EQUALS", "bug")) });
219
+ const count = field("count", "NUMBER");
220
+ const result = prepareFieldValues([topic, banId, required, count], {
221
+ topic: "appeal",
222
+ "ban-id": " 42 ",
223
+ must: "",
224
+ count: " 7 ",
225
+ unknown: "x",
226
+ });
227
+
228
+ expect(result).toEqual({ fields: { topic: "appeal", "ban-id": "42", count: 7 }, errors: {}, valid: true });
229
+ });
230
+
231
+ test("reports the errors of visible fields", () => {
232
+ const result = prepareFieldValues([topic, field("must", "TEXT", { required: true })], { topic: "x" });
233
+
234
+ expect(result.valid).toBe(false);
235
+ expect(result.errors).toEqual({ topic: "UNKNOWN_OPTION", must: "REQUIRED" });
236
+ });
237
+ });
238
+
239
+ describe("server errors and display", () => {
240
+ test("fieldErrorsFromServer strips the fields. prefix", () => {
241
+ expect(fieldErrorsFromServer({ "fields.ban-id": "REQUIRED", other: "X" })).toEqual({ "ban-id": "REQUIRED" });
242
+ expect(fieldErrorsFromServer(undefined)).toEqual({});
243
+ });
244
+
245
+ test("displayValue links only http(s) and e-mail, localises yes/no and dates", () => {
246
+ expect(displayValue({ type: "URL", value: "https://a.co" })).toEqual({ text: "https://a.co", href: "https://a.co" });
247
+ expect(displayValue({ type: "URL", value: "javascript:x" }).href).toBeNull();
248
+ expect(displayValue({ type: "EMAIL", value: "a@b.co" }).href).toBe("mailto:a@b.co");
249
+ expect(displayValue({ type: "CHECKBOX", value: true }, { yes: "Evet", no: "Hayır" }).text).toBe("Evet");
250
+ expect(displayValue({ type: "DATE", value: "2026-03-04" }, { locale: "en-US" }).text).toBe("Mar 4, 2026");
251
+ expect(
252
+ displayValue({ type: "MULTISELECT", value: ["appeal", "bug"], display: "", options: topic.options }).text,
253
+ ).toBe("Ban appeal, Bug");
254
+ expect(displayValue({ type: "SELECT", value: "appeal", display: "Ban appeal" }).text).toBe("Ban appeal");
255
+ expect(hasValue({ type: "TEXT", value: null })).toBe(false);
256
+ expect(hasValue({ type: "CHECKBOX", value: false })).toBe(false);
257
+ });
258
+ });
@@ -4,18 +4,23 @@
4
4
  -->
5
5
  <svelte:component
6
6
  this={getOverride("Post") ?? PostView}
7
- {post}
7
+ post={localizePost(post, $locale)}
8
8
  {detail}
9
9
  {themeSettings}
10
10
  {avatarVersion} />
11
11
 
12
12
  <script>
13
13
  import { getContext } from "svelte";
14
+ import { locale } from "svelte-i18n";
15
+
16
+ import { localizePost } from "$pano/lib/contentI18n.js";
14
17
 
15
18
  import { getOverride } from "$pano/registry/index.js";
16
19
  import { avatarVersion } from "$pano/lib/Store";
17
20
  import PostView from "$pano/lib/views/parts/Post.svelte";
18
21
 
22
+ // The post in the site's current language (translated content, `i18n`); an already localized post
23
+ // is localized again from its original.
19
24
  export let post;
20
25
  export let detail = false;
21
26
 
@@ -2,11 +2,16 @@
2
2
  Controller of the engine's <Posts>. The markup lives in views/parts/Posts.svelte; a theme may
3
3
  replace it with the "Posts" entry of theme.config.js views (see skin-contract.json for the props).
4
4
  -->
5
- <svelte:component this={getOverride("Posts") ?? PostsView} {posts} />
5
+ <svelte:component this={getOverride("Posts") ?? PostsView} posts={localizePosts(posts, $locale)} />
6
6
 
7
7
  <script>
8
+ import { locale } from "svelte-i18n";
9
+
10
+ import { localizePosts } from "$pano/lib/contentI18n.js";
8
11
  import { getOverride } from "$pano/registry/index.js";
9
12
  import PostsView from "$pano/lib/views/parts/Posts.svelte";
10
13
 
14
+ // Posts in the site's current language (translated content, `i18n`); posts that are already
15
+ // localized are localized again from their original, so a page may hand in either.
11
16
  export let posts;
12
17
  </script>
@@ -0,0 +1,40 @@
1
+ <!--
2
+ Controller of the engine's <TicketFields>: the custom field values of a ticket (its `fields` snapshot) on
3
+ the ticket page. It keeps the entries that have a value and makes them readable (option labels, the date
4
+ in the UI language, Yes / No, links for http(s) URLs and e-mails); the markup lives in
5
+ views/parts/TicketFields.svelte, and a theme may replace it with the "TicketFields" entry of
6
+ theme.config.js views (see skin-contract.json for the props).
7
+
8
+ Props:
9
+ fields array | null — `ticket.fields`: [{ key, label, type, options, min, max, value, display, i18n }]
10
+ -->
11
+ <svelte:component this={getOverride("TicketFields") ?? TicketFieldsView} {entries} />
12
+
13
+ <script>
14
+ import { _, locale } from "svelte-i18n";
15
+
16
+ import { getOverride } from "$pano/registry/index.js";
17
+ import { displayValue, hasValue } from "$pano/lib/ticketFields.js";
18
+ import { localized, localizedDisplay } from "$pano/lib/contentI18n.js";
19
+ import TicketFieldsView from "$pano/lib/views/parts/TicketFields.svelte";
20
+
21
+ export let fields = [];
22
+
23
+ // Labels and SELECT / MULTISELECT values in the site's current language (the entry's `i18n`).
24
+ $: entries = (Array.isArray(fields) ? fields : []).filter(hasValue).map((entry) => {
25
+ const readable = displayValue(entry, {
26
+ locale: $locale,
27
+ yes: $_("pages.ticket-detail.fields.yes"),
28
+ no: $_("pages.ticket-detail.fields.no"),
29
+ });
30
+
31
+ return {
32
+ key: entry.key,
33
+ label: localized(entry.label, entry.i18n, $locale, "label"),
34
+ type: entry.type,
35
+ value: entry.value,
36
+ ...readable,
37
+ ...(entry.type === "SELECT" || entry.type === "MULTISELECT" ? { text: localizedDisplay(entry, $locale) } : {}),
38
+ };
39
+ });
40
+ </script>
@@ -0,0 +1,63 @@
1
+ <!--
2
+ Controller of the engine's <TicketFieldsForm>: the custom fields of the chosen ticket category on the
3
+ create-ticket page. It applies the visibility rules live and hands the visible fields to the markup in
4
+ views/parts/TicketFieldsForm.svelte; a theme may replace that with the "TicketFieldsForm" entry of
5
+ theme.config.js views (see skin-contract.json for the props).
6
+
7
+ Props:
8
+ category object | null — the chosen category (its `fields` are the definitions, translated texts in
9
+ their `i18n` are applied for the current language); null = none
10
+ values writable store — field key -> value (default: the create-ticket page's, from context)
11
+ errors writable store — field key -> error code (default: the create-ticket page's, from context)
12
+ -->
13
+ <svelte:component this={getOverride("TicketFieldsForm") ?? TicketFieldsFormView} fields={shown} {values} errors={$errors} />
14
+
15
+ <script>
16
+ import { getContext } from "svelte";
17
+ import { writable } from "svelte/store";
18
+ import { locale } from "svelte-i18n";
19
+
20
+ import { getOverride } from "$pano/registry/index.js";
21
+ import { TICKET_FIELDS_CONTEXT, visibleFields } from "$pano/lib/ticketFields.js";
22
+ import { localizeField } from "$pano/lib/contentI18n.js";
23
+ import TicketFieldsFormView from "$pano/lib/views/parts/TicketFieldsForm.svelte";
24
+
25
+ const state = getContext(TICKET_FIELDS_CONTEXT);
26
+
27
+ export let category = null;
28
+ export let values = state?.values ?? writable({});
29
+ export let errors = state?.errors ?? writable({});
30
+
31
+ // Another category has other fields: start it empty.
32
+ let shownCategoryId = category?.id ?? null;
33
+
34
+ $: if ((category?.id ?? null) !== shownCategoryId) {
35
+ shownCategoryId = category?.id ?? null;
36
+ values.set({});
37
+ errors.set({});
38
+ }
39
+
40
+ // An edited field loses its error until the next submit.
41
+ // (a bound input mutates the same object, so the previous values are kept as a copy)
42
+ let lastValues = { ...($values ?? {}) };
43
+
44
+ function clearEditedErrors(current) {
45
+ const before = lastValues;
46
+ lastValues = { ...(current ?? {}) };
47
+
48
+ const edited = Object.keys($errors ?? {}).filter((key) => current?.[key] !== before[key]);
49
+
50
+ if (edited.length > 0) {
51
+ errors.update((existing) => {
52
+ const next = { ...existing };
53
+ edited.forEach((key) => delete next[key]);
54
+ return next;
55
+ });
56
+ }
57
+ }
58
+
59
+ $: clearEditedErrors($values);
60
+
61
+ // The markup gets label, placeholder, help and option labels in the site's current language.
62
+ $: shown = visibleFields(category?.fields ?? [], $values).map((field) => localizeField(field, $locale));
63
+ </script>
@@ -3,16 +3,24 @@
3
3
  replace it with the "TicketRow" entry of theme.config.js views (see skin-contract.json for the props).
4
4
  Dispatches `closeTicket` with { ticket }.
5
5
  -->
6
- <svelte:component this={getOverride("TicketRow") ?? TicketRowView} {ticket} {onCloseTicket} />
6
+ <svelte:component this={getOverride("TicketRow") ?? TicketRowView} ticket={shownTicket} {onCloseTicket} />
7
7
 
8
8
  <script>
9
9
  import { createEventDispatcher } from "svelte";
10
+ import { locale } from "svelte-i18n";
10
11
 
11
12
  import { getOverride } from "$pano/registry/index.js";
12
13
  import TicketRowView from "$pano/lib/views/parts/TicketRow.svelte";
14
+ import { localizeCategory } from "$pano/lib/contentI18n.js";
13
15
 
14
16
  export let ticket;
15
17
 
18
+ // The markup gets the category title in the site's current language (the event keeps the original).
19
+ $: shownTicket =
20
+ ticket?.category && typeof ticket.category === "object"
21
+ ? { ...ticket, category: localizeCategory(ticket.category, $locale) }
22
+ : ticket;
23
+
16
24
  const dispatch = createEventDispatcher();
17
25
 
18
26
  function onCloseTicket() {
@@ -0,0 +1,227 @@
1
+ // Translatable admin content (ticket categories, ticket fields, the registration agreement, posts and
2
+ // post categories): picks the text of the UI's current language from an object's optional `i18n` (locale code -> { prop: text }).
3
+ // The rule must match the panel and the backend: the exact locale, then its language part ("tr" for
4
+ // "tr-TR"), then the default text. A blank or missing translation means "use the default".
5
+ // Without `i18n` (an older backend) every helper returns the default text.
6
+
7
+ const isFilled = (value) => typeof value === "string" && value.trim() !== "";
8
+
9
+ /**
10
+ * The locale codes to try, in order: the exact code, then its language part.
11
+ *
12
+ * @param {string | null | undefined} locale
13
+ * @returns {string[]}
14
+ */
15
+ function candidates(locale) {
16
+ if (typeof locale !== "string" || locale === "") return [];
17
+
18
+ const language = locale.split(/[-_]/)[0];
19
+
20
+ return language && language !== locale ? [locale, language] : [locale];
21
+ }
22
+
23
+ /**
24
+ * The first non-blank `pick(texts[code])` over the candidate codes, or `undefined`.
25
+ *
26
+ * @param {Record<string, unknown> | null | undefined} texts
27
+ * @param {string | null | undefined} locale
28
+ * @param {(entry: any) => unknown} pick
29
+ */
30
+ function lookup(texts, locale, pick) {
31
+ if (!texts || typeof texts !== "object") return undefined;
32
+
33
+ for (const code of candidates(locale)) {
34
+ const value = pick(texts[code]);
35
+
36
+ if (isFilled(value)) return /** @type {string} */ (value);
37
+ }
38
+
39
+ return undefined;
40
+ }
41
+
42
+ /**
43
+ * A flat translation map (locale code -> text, e.g. `registerAgreementI18n`).
44
+ *
45
+ * @param {string | null | undefined} defaultText
46
+ * @param {Record<string, string> | null | undefined} texts
47
+ * @param {string | null | undefined} locale
48
+ * @returns {string}
49
+ */
50
+ export function localizedString(defaultText, texts, locale) {
51
+ return lookup(texts, locale, (entry) => entry) ?? defaultText ?? "";
52
+ }
53
+
54
+ /**
55
+ * `i18n[locale][prop]`, else `i18n[<language part>][prop]`, else the default text.
56
+ *
57
+ * @param {string | null | undefined} defaultText
58
+ * @param {Record<string, Record<string, unknown>> | null | undefined} i18n
59
+ * @param {string | null | undefined} locale
60
+ * @param {string} prop
61
+ * @returns {string}
62
+ */
63
+ export function localized(defaultText, i18n, locale, prop) {
64
+ return lookup(i18n, locale, (entry) => entry?.[prop]) ?? defaultText ?? "";
65
+ }
66
+
67
+ /**
68
+ * The label of one option: `i18n[locale].options[value]` with the same fallback, else its own label.
69
+ *
70
+ * @param {{ value: string, label?: string }} option
71
+ * @param {Record<string, Record<string, unknown>> | null | undefined} i18n
72
+ * @param {string | null | undefined} locale
73
+ * @returns {string}
74
+ */
75
+ export function localizedOption(option, i18n, locale) {
76
+ const value = option?.value;
77
+
78
+ return lookup(i18n, locale, (entry) => entry?.options?.[value]) ?? option?.label ?? String(value ?? "");
79
+ }
80
+
81
+ /**
82
+ * The readable value of a SELECT / MULTISELECT snapshot entry (`ticket.fields[i]`) in the given locale,
83
+ * rebuilt from the option values in `value` (MULTISELECT joined with ", "). Other types (and an entry
84
+ * none of whose values has a translation) keep the server's `display`.
85
+ *
86
+ * @param {{ type: string, value: unknown, display?: string, options?: { value: string, label: string }[],
87
+ * i18n?: Record<string, Record<string, unknown>> }} entry
88
+ * @param {string | null | undefined} locale
89
+ * @returns {string}
90
+ */
91
+ export function localizedDisplay(entry, locale) {
92
+ if (!entry) return "";
93
+
94
+ const display = isFilled(entry.display) ? entry.display : null;
95
+
96
+ if (entry.type !== "SELECT" && entry.type !== "MULTISELECT") return display ?? String(entry.value ?? "");
97
+
98
+ const values = entry.type === "MULTISELECT" ? (Array.isArray(entry.value) ? entry.value : []) : [entry.value];
99
+ const translated = values.some((value) => lookup(entry.i18n, locale, (item) => item?.options?.[value]) !== undefined);
100
+
101
+ if (!translated && display !== null) return display;
102
+
103
+ return values
104
+ .map((value) => {
105
+ const option = (entry.options ?? []).find((item) => item.value === value) ?? { value, label: String(value ?? "") };
106
+
107
+ return localizedOption(option, entry.i18n, locale);
108
+ })
109
+ .join(", ");
110
+ }
111
+
112
+ /** A localized copy -> the object it was made from, so localizing again never stacks languages. */
113
+ const sources = new WeakMap();
114
+
115
+ const sourceOf = (object) => sources.get(object) ?? object;
116
+
117
+ const remember = (copy, source) => {
118
+ sources.set(copy, source);
119
+ return copy;
120
+ };
121
+
122
+ // Object keys, not string literals: the engine's fallback-CSS scanner reads string literals as class
123
+ // names (and "placeholder" is a Bootstrap class).
124
+ const OPTIONAL_FIELD_TEXTS = Object.keys({ placeholder: 0, help: 0 });
125
+
126
+ /**
127
+ * A field definition with `label`, `placeholder`, `help` and the option labels in the given locale
128
+ * (`i18n` is kept).
129
+ *
130
+ * @template {{ label?: string, placeholder?: string, help?: string, options?: { value: string, label: string }[],
131
+ * i18n?: Record<string, Record<string, unknown>> }} T
132
+ * @param {T} definition
133
+ * @param {string | null | undefined} locale
134
+ * @returns {T}
135
+ */
136
+ export function localizeField(definition, locale) {
137
+ if (!definition || typeof definition !== "object") return definition;
138
+
139
+ const source = sourceOf(definition);
140
+ const i18n = source.i18n;
141
+ const copy = { ...source, label: localized(source.label, i18n, locale, "label") };
142
+
143
+ for (const prop of OPTIONAL_FIELD_TEXTS) {
144
+ if (prop in source) copy[prop] = localized(source[prop], i18n, locale, prop);
145
+ }
146
+ if (Array.isArray(source.options)) {
147
+ copy.options = source.options.map((option) => ({ ...option, label: localizedOption(option, i18n, locale) }));
148
+ }
149
+
150
+ return remember(copy, source);
151
+ }
152
+
153
+ /**
154
+ * A ticket category with `title`, `description` and its `fields` in the given locale. A missing
155
+ * category or the "-" placeholder of "no category" is returned as is.
156
+ *
157
+ * @template {{ title?: string, description?: string, fields?: any[], i18n?: Record<string, Record<string, unknown>> }} T
158
+ * @param {T} category
159
+ * @param {string | null | undefined} locale
160
+ * @returns {T}
161
+ */
162
+ export function localizeCategory(category, locale) {
163
+ if (!category || typeof category !== "object") return category;
164
+
165
+ const source = sourceOf(category);
166
+ const copy = { ...source };
167
+
168
+ if ("title" in source && source.title !== "-") copy.title = localized(source.title, source.i18n, locale, "title");
169
+ if ("description" in source) copy.description = localized(source.description, source.i18n, locale, "description");
170
+ if (Array.isArray(source.fields)) copy.fields = source.fields.map((field) => localizeField(field, locale));
171
+
172
+ return remember(copy, source);
173
+ }
174
+
175
+ /**
176
+ * @param {any[] | null | undefined} categories
177
+ * @param {string | null | undefined} locale
178
+ * @returns {any[]}
179
+ */
180
+ export function localizeCategories(categories, locale) {
181
+ return Array.isArray(categories) ? categories.map((category) => localizeCategory(category, locale)) : [];
182
+ }
183
+
184
+ /**
185
+ * A post category with `title` and `description` in the given locale (`i18n` is kept). The "-"
186
+ * placeholder of "no category" (a string or a `{ title: "-" }` object) is returned as is.
187
+ *
188
+ * @template T
189
+ * @param {T} category
190
+ * @param {string | null | undefined} locale
191
+ * @returns {T}
192
+ */
193
+ export function localizePostCategory(category, locale) {
194
+ return localizeCategory(category, locale);
195
+ }
196
+
197
+ /**
198
+ * A post with `title`, `text` (HTML, or the list's excerpt) and its `category` in the given locale.
199
+ * `i18n` is kept, and localizing a localized copy again starts from the original post. A post-like
200
+ * value that is not an object (the "-" of "no previous post") is returned as is.
201
+ *
202
+ * @template {{ title?: string, text?: string, category?: any, i18n?: Record<string, Record<string, unknown>> }} T
203
+ * @param {T} post
204
+ * @param {string | null | undefined} locale
205
+ * @returns {T}
206
+ */
207
+ export function localizePost(post, locale) {
208
+ if (!post || typeof post !== "object") return post;
209
+
210
+ const source = sourceOf(post);
211
+ const copy = { ...source };
212
+
213
+ if ("title" in source) copy.title = localized(source.title, source.i18n, locale, "title");
214
+ if ("text" in source) copy.text = localized(source.text, source.i18n, locale, "text");
215
+ if ("category" in source) copy.category = localizePostCategory(source.category, locale);
216
+
217
+ return remember(copy, source);
218
+ }
219
+
220
+ /**
221
+ * @param {any[] | null | undefined} posts
222
+ * @param {string | null | undefined} locale
223
+ * @returns {any[]}
224
+ */
225
+ export function localizePosts(posts, locale) {
226
+ return Array.isArray(posts) ? posts.map((post) => localizePost(post, locale)) : [];
227
+ }