athena-ui-js 1.2.0 → 2.0.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.
Files changed (148) hide show
  1. package/README.md +312 -60
  2. package/docs/migration-2.0.md +83 -0
  3. package/docs/styling.md +86 -0
  4. package/package.json +109 -24
  5. package/src/athena-ui.js +61 -81
  6. package/src/chart.js +6 -0
  7. package/src/classic.js +11 -0
  8. package/src/components.js +6 -0
  9. package/src/controls.js +8 -0
  10. package/src/csv.js +6 -0
  11. package/src/dialog.js +7 -0
  12. package/src/dom.js +6 -0
  13. package/src/feedback.js +6 -0
  14. package/src/format.js +6 -0
  15. package/src/forms.js +7 -0
  16. package/src/i18n.js +6 -0
  17. package/src/inputs.js +9 -0
  18. package/src/libs/config/config.js +1 -2
  19. package/src/libs/core/controls.js +145 -0
  20. package/src/libs/core/cookies.js +55 -0
  21. package/src/libs/core/dateRange.js +121 -0
  22. package/src/libs/core/dom.js +58 -8
  23. package/src/libs/{hephaestus/HTMLElementGenerator/src/HTMLElementGenerator.js → core/elementGenerator.js} +23 -21
  24. package/src/libs/{hephaestus/HTMLElementGenerator/src → core}/errors.js +7 -5
  25. package/src/libs/core/format.js +51 -0
  26. package/src/libs/core/hungarianControls.js +41 -0
  27. package/src/libs/core/i18n.js +104 -6
  28. package/src/libs/core/theme.js +131 -0
  29. package/src/libs/core/validation.js +2 -2
  30. package/src/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.js +13 -7
  31. package/src/libs/hephaestus/LayoutGenerator/footerContentGenerator.js +2 -4
  32. package/src/libs/hephaestus/LayoutGenerator/headerContentGenerator.js +12 -5
  33. package/src/libs/hephaestus/MenuGenerator/basicMenuGenerator.js +3 -3
  34. package/src/libs/hephaestus/MenuGenerator/menuGenerator.js +265 -0
  35. package/src/libs/hephaestus/auth/authState.js +58 -0
  36. package/src/libs/hephaestus/auth/session.js +1 -1
  37. package/src/libs/hephaestus/chartGenerator/chartGenerator.js +519 -87
  38. package/src/libs/hephaestus/componentGenerator/componentGenerator.js +121 -4
  39. package/src/libs/hephaestus/componentGenerator/themePicker.js +73 -0
  40. package/src/libs/hephaestus/dialogGenerator/dialogGenerator.js +113 -25
  41. package/src/libs/hephaestus/feedbackGenerator/feedbackGenerator.js +21 -0
  42. package/src/libs/hephaestus/formGenerator/authForms.js +130 -0
  43. package/src/libs/hephaestus/formGenerator/changePasswordFormGenerator.js +4 -4
  44. package/src/libs/hephaestus/formGenerator/formUtils.js +10 -13
  45. package/src/libs/hephaestus/formGenerator/loginFormGenerator.js +10 -11
  46. package/src/libs/hephaestus/formGenerator/registrationFormGenerator.js +3 -3
  47. package/src/libs/hephaestus/hephaestus.js +0 -5
  48. package/src/libs/hephaestus/inputGenerator/dropZoneGenerator.js +1 -1
  49. package/src/libs/hephaestus/inputGenerator/inputGenerator.js +30 -1
  50. package/src/libs/hephaestus/modalGenerator/modalGenerator.js +25 -12
  51. package/src/libs/hephaestus/navigationGenerator/navigationGenerator.js +20 -24
  52. package/src/libs/hephaestus/router/router.js +54 -5
  53. package/src/libs/hephaestus/tableGenerator/tableGenerator.js +290 -16
  54. package/src/menu.js +6 -0
  55. package/src/navigation.js +6 -0
  56. package/src/res/themes/appearance.css +154 -0
  57. package/src/res/themes/default/style.css +688 -82
  58. package/src/res/themes/tokens.css +96 -0
  59. package/src/router.js +6 -0
  60. package/src/sanitize.js +6 -0
  61. package/src/session.js +8 -0
  62. package/src/table.js +6 -0
  63. package/src/testing.js +11 -1
  64. package/src/theme-boot.js +25 -0
  65. package/src/theme.js +7 -0
  66. package/src/validation.js +6 -0
  67. package/types/athena-ui.d.ts +96 -0
  68. package/types/chart.d.ts +1 -0
  69. package/types/classic.d.ts +1 -0
  70. package/types/components.d.ts +1 -0
  71. package/types/controls.d.ts +3 -0
  72. package/types/csv.d.ts +1 -0
  73. package/types/dialog.d.ts +2 -0
  74. package/types/dom.d.ts +1 -0
  75. package/types/feedback.d.ts +1 -0
  76. package/types/format.d.ts +1 -0
  77. package/types/forms.d.ts +2 -0
  78. package/types/i18n.d.ts +1 -0
  79. package/types/inputs.d.ts +4 -0
  80. package/types/libs/config/config.d.ts +96 -0
  81. package/types/libs/config/hooks.d.ts +8 -0
  82. package/types/libs/core/combobox.d.ts +10 -0
  83. package/types/libs/core/controls.d.ts +28 -0
  84. package/types/libs/core/cookies.d.ts +27 -0
  85. package/types/libs/core/csv.d.ts +12 -0
  86. package/types/libs/core/dateRange.d.ts +72 -0
  87. package/types/libs/core/dom.d.ts +65 -0
  88. package/types/libs/core/elementGenerator.d.ts +30 -0
  89. package/types/libs/core/errors.d.ts +29 -0
  90. package/types/libs/core/focus.d.ts +6 -0
  91. package/types/libs/core/format.d.ts +21 -0
  92. package/types/libs/core/hungarianControls.d.ts +2 -0
  93. package/types/libs/core/i18n.d.ts +17 -0
  94. package/types/libs/core/pagination.d.ts +5 -0
  95. package/types/libs/core/sanitize.d.ts +6 -0
  96. package/types/libs/core/tableMath.d.ts +26 -0
  97. package/types/libs/core/theme.d.ts +39 -0
  98. package/types/libs/core/validation.d.ts +56 -0
  99. package/types/libs/hephaestus/LayoutGenerator/basicLayoutGenerator.d.ts +10 -0
  100. package/types/libs/hephaestus/LayoutGenerator/footerContentGenerator.d.ts +4 -0
  101. package/types/libs/hephaestus/LayoutGenerator/headerContentGenerator.d.ts +20 -0
  102. package/types/libs/hephaestus/LayoutGenerator/wrapperContentGenerator.d.ts +1 -0
  103. package/types/libs/hephaestus/MenuGenerator/basicMenuGenerator.d.ts +14 -0
  104. package/types/libs/hephaestus/MenuGenerator/menuGenerator.d.ts +65 -0
  105. package/types/libs/hephaestus/auth/authState.d.ts +26 -0
  106. package/types/libs/hephaestus/auth/session.d.ts +26 -0
  107. package/types/libs/hephaestus/chartGenerator/chartGenerator.d.ts +91 -0
  108. package/types/libs/hephaestus/componentGenerator/componentGenerator.d.ts +222 -0
  109. package/types/libs/hephaestus/componentGenerator/themePicker.d.ts +24 -0
  110. package/types/libs/hephaestus/dialogGenerator/dialogGenerator.d.ts +120 -0
  111. package/types/libs/hephaestus/feedbackGenerator/feedbackGenerator.d.ts +86 -0
  112. package/types/libs/hephaestus/formGenerator/authForms.d.ts +122 -0
  113. package/types/libs/hephaestus/formGenerator/changePasswordFormGenerator.d.ts +6 -0
  114. package/types/libs/hephaestus/formGenerator/formBuilder.d.ts +113 -0
  115. package/types/libs/hephaestus/formGenerator/formUtils.d.ts +8 -0
  116. package/types/libs/hephaestus/formGenerator/loginFormGenerator.d.ts +11 -0
  117. package/types/libs/hephaestus/formGenerator/lostPasswordFormGenerator.d.ts +4 -0
  118. package/types/libs/hephaestus/formGenerator/registrationFormGenerator.d.ts +7 -0
  119. package/types/libs/hephaestus/hephaestus.d.ts +3 -0
  120. package/types/libs/hephaestus/inputGenerator/dropZoneGenerator.d.ts +48 -0
  121. package/types/libs/hephaestus/inputGenerator/inputGenerator.d.ts +185 -0
  122. package/types/libs/hephaestus/inputGenerator/richTextGenerator.d.ts +49 -0
  123. package/types/libs/hephaestus/modalGenerator/modalGenerator.d.ts +2 -0
  124. package/types/libs/hephaestus/navigationGenerator/navigationGenerator.d.ts +150 -0
  125. package/types/libs/hephaestus/router/matchRoute.d.ts +12 -0
  126. package/types/libs/hephaestus/router/router.d.ts +67 -0
  127. package/types/libs/hephaestus/tableGenerator/tableGenerator.d.ts +120 -0
  128. package/types/menu.d.ts +1 -0
  129. package/types/navigation.d.ts +1 -0
  130. package/types/res/themes/themes.d.ts +7 -0
  131. package/types/router.d.ts +1 -0
  132. package/types/sanitize.d.ts +1 -0
  133. package/types/session.d.ts +3 -0
  134. package/types/table.d.ts +1 -0
  135. package/types/testing.d.ts +27 -0
  136. package/types/theme-boot.d.ts +0 -0
  137. package/types/theme.d.ts +2 -0
  138. package/types/validation.d.ts +1 -0
  139. package/src/libs/crypto-js/LICENSE +0 -24
  140. package/src/libs/crypto-js/crypto-js.js +0 -6657
  141. package/src/libs/hephaestus/HTMLControlGenerator/LICENSE +0 -21
  142. package/src/libs/hephaestus/HTMLControlGenerator/src/HTMLControlGenerator.min.js +0 -5
  143. package/src/libs/hephaestus/HTMLElementGenerator/LICENSE +0 -21
  144. package/src/libs/js-cookie/LICENSE +0 -21
  145. package/src/libs/js-cookie/src/api.mjs +0 -103
  146. package/src/libs/js-cookie/src/assign.mjs +0 -10
  147. package/src/libs/js-cookie/src/converter.mjs +0 -14
  148. package/src/libs/libs.js +0 -13
@@ -0,0 +1,145 @@
1
+ //controls for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+ //Moved here from HTMLControlGenerator 0.4.1 (https://github.com/csabatibortoth/HTMLControlGenerator), which is no longer developed.
6
+ //The calls are the same; there is no jQuery in it any more (since 2.0 `create` returns the element, not a jQuery object).
7
+
8
+ import { el, resolveElement } from "./dom.js";
9
+ import { noBodyOrParentError, reportError, undefinedError, wrongInputTypeError } from "./errors.js";
10
+
11
+ // Inputs, select and lists (ul / ol with items) from a plain options object, without jQuery.
12
+
13
+ const INPUT_TYPES = [
14
+ "text", "password", "submit", "reset", "radio", "checkbox", "button",
15
+ "color", "date", "datetime-local", "email", "file", "month", "number",
16
+ "range", "search", "tel", "time", "url", "week"
17
+ ];
18
+ const WITHOUT_VALUE = new Set(["reset", "file"]); // a file input's value cannot be set, and reset keeps the browser's label
19
+ const WITH_MIN_MAX = new Set(["date", "number", "range"]);
20
+ const CHECKABLE = new Set(["radio", "checkbox"]);
21
+ const EVENTS = ["change", "click"];
22
+
23
+ // `onchange` is the option name, `change` is accepted as an alias of it.
24
+ const handlerFor = (source, event) => {
25
+ const handler = source[`on${event}`] ?? (event === "change" ? source.change : undefined);
26
+ return typeof handler === "function" ? handler : undefined;
27
+ };
28
+
29
+ function base(tag, options) {
30
+ return el(tag, { id: options.id, class: options.class });
31
+ }
32
+
33
+ function formControl(tag, options) {
34
+ const control = base(tag, options);
35
+ if (options.name != null) control.name = options.name;
36
+ if (options.readOnly != null) control.readOnly = Boolean(options.readOnly);
37
+ if (options.disabled != null) control.disabled = Boolean(options.disabled);
38
+ for (const event of EVENTS) {
39
+ const handler = handlerFor(options, event);
40
+ if (handler) control.addEventListener(event, () => handler.call(options, options.data));
41
+ }
42
+ return control;
43
+ }
44
+
45
+ function input(options) {
46
+ const type = options.inputType;
47
+ const control = formControl("input", options);
48
+ control.type = type;
49
+ if (options.value !== undefined && !WITHOUT_VALUE.has(type)) control.value = options.value;
50
+ if (WITH_MIN_MAX.has(type)) {
51
+ if (options.min != null) control.min = options.min;
52
+ if (options.max != null) control.max = options.max;
53
+ }
54
+ if (CHECKABLE.has(type)) control.checked = Boolean(options.checked);
55
+ return control;
56
+ }
57
+
58
+ function select(options) {
59
+ const control = formControl("select", options);
60
+ for (const item of options.items ?? []) {
61
+ control.append(el("option", { text: item.text, prop: { value: item.value, selected: Boolean(item.selected) } }));
62
+ }
63
+ return control;
64
+ }
65
+
66
+ function list(options) {
67
+ const items = [...(options.items ?? [])];
68
+ const control = base(options.inputType, options);
69
+ for (const item of items) control.append(el("li", { id: item.id, class: item.class, text: item.text }));
70
+ // One listener per event on the list: an item's own handler wins, otherwise the handler of the list is called.
71
+ for (const event of EVENTS) {
72
+ if (![options, ...items].some(source => handlerFor(source, event))) continue;
73
+ control.addEventListener(event, e => {
74
+ const li = e.target.closest?.("li");
75
+ if (!li || li.parentElement !== control) return;
76
+ const item = items[[...control.children].indexOf(li)];
77
+ const source = item && handlerFor(item, event) ? item : options;
78
+ handlerFor(source, event)?.call(source, source.data);
79
+ });
80
+ }
81
+ return control;
82
+ }
83
+
84
+ const factories = new Map([...INPUT_TYPES.map(type => [type, input]), ["select", select], ["ul", list], ["ol", list]]);
85
+
86
+ /** Builds the control described by `options` without appending it. Returns the element, or null (an error is reported). */
87
+ export function buildControl(options) {
88
+ if (options === undefined) return reportError(undefinedError("options", "HTMLControlGenerator"));
89
+ const factory = factories.get(options.inputType);
90
+ if (!factory) return reportError(wrongInputTypeError("options", "HTMLControlGenerator", options));
91
+ return factory(options);
92
+ }
93
+
94
+ /**
95
+ * Registers a new input type. `factory(options)` returns the element to append.
96
+ * Addons use this to plug in their controls, see registerHungarianInputControls.
97
+ */
98
+ export function registerControl(inputType, factory) {
99
+ factories.set(inputType, factory);
100
+ }
101
+
102
+ /**
103
+ * Builds a control from `{ inputType, id, class, name, value, items, onclick, onchange, ... }` and appends it to the element given as
104
+ * `parent` (an id or an element; without one, to the body).
105
+ *
106
+ * @returns {HTMLElement|undefined} the control, or undefined when the input type is not known
107
+ */
108
+ export function generateControl(options = {}) {
109
+ const control = buildControl(options);
110
+ if (!control) return undefined;
111
+ (resolveElement(options.parent) ?? document.body).append(control);
112
+ return control;
113
+ }
114
+
115
+ /**
116
+ * The HTMLControlGenerator of the standalone project (0.4.1), so code written for it keeps working.
117
+ * `HTMLControlGenerator(options)` builds the control and appends it to the element with the id `options.parent`
118
+ * (an unknown id appends it, in a div, to the body). It is also a global once Athena UI is loaded.
119
+ */
120
+ export function HTMLControlGenerator(options) {
121
+ const control = buildControl(options);
122
+ if (!control) return;
123
+ if (options.parent === undefined) {
124
+ reportError(undefinedError("options.parent", "HTMLControlGenerator"));
125
+ return;
126
+ }
127
+ const parent = document.getElementById(options.parent);
128
+ if (parent) {
129
+ parent.append(control);
130
+ } else if (document.body) {
131
+ const wrapper = document.createElement("div");
132
+ wrapper.append(control);
133
+ document.body.append(wrapper);
134
+ } else {
135
+ reportError(noBodyOrParentError("parent", "HTMLControlGenerator"));
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Builds the control without appending it and returns the element (the standalone project returned a jQuery object: wrap it yourself with
141
+ * `$(HTMLControlGenerator.create(options))` if you still need one). Undefined when the options are not valid.
142
+ */
143
+ HTMLControlGenerator.create = options => buildControl(options) ?? undefined;
144
+
145
+ HTMLControlGenerator.register = registerControl;
@@ -0,0 +1,55 @@
1
+ //cookies for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ // A small cookie helper (it replaces js-cookie, which Athena UI used to bundle). Same calls for what Athena needs:
7
+ // Cookies.get(name), Cookies.set(name, value, attributes), Cookies.remove(name, attributes).
8
+
9
+ const encode = value => encodeURIComponent(String(value)).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, decodeURIComponent);
10
+ const decode = value => value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
11
+
12
+ /**
13
+ * @param {string} name
14
+ * @param {string} value
15
+ * @param {object} [attributes]
16
+ * @param {number|Date} [attributes.expires] days from now, or a Date. Without it the cookie ends with the browser session.
17
+ * @param {string} [attributes.path="/"]
18
+ * @param {string} [attributes.domain]
19
+ * @param {"strict"|"lax"|"none"} [attributes.sameSite]
20
+ * @param {boolean} [attributes.secure]
21
+ */
22
+ function set(name, value, attributes = {}) {
23
+ const { expires, path = "/", domain, sameSite, secure } = attributes;
24
+ let text = `${encode(name)}=${encode(value)}`;
25
+ if (expires != null) {
26
+ const date = expires instanceof Date ? expires : new Date(Date.now() + expires * 864e5);
27
+ text += `; expires=${date.toUTCString()}`;
28
+ }
29
+ if (path) text += `; path=${path}`;
30
+ if (domain) text += `; domain=${domain}`;
31
+ if (sameSite) text += `; samesite=${sameSite}`;
32
+ if (secure) text += "; secure";
33
+ document.cookie = text;
34
+ }
35
+
36
+ /** The value of a cookie, or undefined. Without a name: all cookies as an object. */
37
+ function get(name) {
38
+ const all = {};
39
+ for (const part of document.cookie ? document.cookie.split("; ") : []) {
40
+ const at = part.indexOf("=");
41
+ const key = decode(part.slice(0, at));
42
+ if (name === undefined || key === name) all[key] = decode(part.slice(at + 1));
43
+ if (key === name) break;
44
+ }
45
+ return name === undefined ? all : all[name];
46
+ }
47
+
48
+ /** Removes a cookie. Give the same path, domain and sameSite it was set with. */
49
+ function remove(name, attributes = {}) {
50
+ set(name, "", { ...attributes, expires: -1 });
51
+ }
52
+
53
+ const Cookies = { get, set, remove };
54
+ export default Cookies;
55
+ export { Cookies };
@@ -48,3 +48,124 @@ export function createDateRange(options = {}) {
48
48
  validate: () => validateDateRange(from.input.value, to.input.value, { min: options.min, max: options.max })
49
49
  };
50
50
  }
51
+
52
+ /* ------------------DATE AND TIME RANGE------------------- */
53
+
54
+ const pad = n => String(n).padStart(2, "0");
55
+
56
+ /** A Date as the value of a datetime-local input, in the local time of the person: "2026-11-19T10:30". */
57
+ export function toLocalInput(date, seconds = false) {
58
+ const d = date instanceof Date ? date : new Date(date);
59
+ if (Number.isNaN(d.getTime())) return "";
60
+ const base = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
61
+ return seconds ? `${base}:${pad(d.getSeconds())}` : base;
62
+ }
63
+
64
+ /** The value of a datetime-local input as a Date (local time), or null when it is empty or not valid. */
65
+ export function fromLocalInput(value) {
66
+ if (!value) return null;
67
+ const d = new Date(value);
68
+ return Number.isNaN(d.getTime()) ? null : d;
69
+ }
70
+
71
+ /** The presets of generateDateTimeRange: a name, and how far back from now they reach. */
72
+ export const DEFAULT_RANGE_PRESETS = [
73
+ { id: "15m", labelKey: "range.last15m", minutes: 15 },
74
+ { id: "1h", labelKey: "range.last1h", minutes: 60 },
75
+ { id: "24h", labelKey: "range.last24h", minutes: 24 * 60 },
76
+ { id: "7d", labelKey: "range.last7d", minutes: 7 * 24 * 60 },
77
+ { id: "30d", labelKey: "range.last30d", minutes: 30 * 24 * 60 }
78
+ ];
79
+
80
+ /**
81
+ * Internal: two datetime-local inputs and a list of presets (last 15 minutes, hour, 24 hours, 7 days). Choosing a preset fills
82
+ * both inputs; changing an input switches the preset to "Custom". A preset is remembered as a preset: getRange() works out
83
+ * "now" when it is called, so a screen that refreshes asks again and gets the moving window.
84
+ *
85
+ * @param {object} options
86
+ * @param {string} [options.id]
87
+ * @param {string} [options.from] initial start (datetime-local value)
88
+ * @param {string} [options.to] initial end
89
+ * @param {string} [options.preset] id of the preset to start with
90
+ * @param {object[]} [options.presets] default DEFAULT_RANGE_PRESETS; { id, label | labelKey, minutes }
91
+ * @param {boolean} [options.seconds=false] the inputs ask for seconds too
92
+ * @param {string} [options.min]
93
+ * @param {string} [options.max]
94
+ * @param {boolean} [options.disabled]
95
+ * @param {(value: {from: string, to: string, preset: string}) => void} [options.onChange]
96
+ */
97
+ export function createDateTimeRange(options = {}) {
98
+ const id = options.id ?? uid("datetimerange");
99
+ const presets = options.presets ?? DEFAULT_RANGE_PRESETS;
100
+ const step = options.seconds ? 1 : 60;
101
+ const labelOf = preset => preset.label ?? translate(preset.labelKey);
102
+ let preset = "";
103
+
104
+ const select = el("select", { id: `${id}-preset`, attrs: { "aria-label": translate("range.preset") }, prop: { disabled: Boolean(options.disabled) } },
105
+ el("option", { text: translate("range.custom"), prop: { value: "" } }),
106
+ ...presets.map(p => el("option", { text: labelOf(p), prop: { value: p.id } })));
107
+ const make = (suffix, labelKey) => {
108
+ const input = el("input", { id: `${id}-${suffix}`, attrs: { type: "datetime-local", step, min: options.min, max: options.max }, prop: { disabled: Boolean(options.disabled) } });
109
+ return { input, label: el("label", { class: "daterange-part" }, el("span", { text: translate(labelKey) }), input) };
110
+ };
111
+ const from = make("from", "dateFrom");
112
+ const to = make("to", "dateTo");
113
+ const element = el("div", { class: cx("daterange datetimerange", options.class), attrs: { role: "group" } },
114
+ el("label", { class: "daterange-part" }, el("span", { text: translate("range.preset") }), select), from.label, to.label);
115
+
116
+ const presetRange = id2 => {
117
+ const found = presets.find(p => p.id === id2);
118
+ if (!found) return null;
119
+ const now = new Date();
120
+ return { from: new Date(now.getTime() - found.minutes * 60000), to: now };
121
+ };
122
+ const getValue = () => ({ from: from.input.value, to: to.input.value, preset });
123
+ const apply = id2 => {
124
+ preset = id2;
125
+ select.value = id2;
126
+ const range = presetRange(id2);
127
+ if (range) {
128
+ from.input.value = toLocalInput(range.from, options.seconds);
129
+ to.input.value = toLocalInput(range.to, options.seconds);
130
+ }
131
+ };
132
+ select.addEventListener("change", () => {
133
+ apply(select.value);
134
+ options.onChange?.(getValue());
135
+ });
136
+ for (const part of [from, to]) {
137
+ part.input.addEventListener("change", () => {
138
+ preset = "";
139
+ select.value = "";
140
+ options.onChange?.(getValue());
141
+ });
142
+ }
143
+ const setValue = value => {
144
+ if (value?.preset) apply(value.preset);
145
+ else {
146
+ preset = "";
147
+ select.value = "";
148
+ from.input.value = value?.from ?? "";
149
+ to.input.value = value?.to ?? "";
150
+ }
151
+ };
152
+ setValue({ from: options.from, to: options.to, preset: options.preset });
153
+ const validate = () => {
154
+ const a = fromLocalInput(from.input.value);
155
+ const b = fromLocalInput(to.input.value);
156
+ if (a && b && b < a) return translate("validation.dateRange");
157
+ return "";
158
+ };
159
+ return {
160
+ element,
161
+ inputs: [select, from.input, to.input],
162
+ getValue,
163
+ setValue,
164
+ /** The range as Dates: a preset is measured from now (when this is called), a custom range is what the inputs hold. */
165
+ getRange() {
166
+ const moving = presetRange(preset);
167
+ return moving ?? { from: fromLocalInput(from.input.value), to: fromLocalInput(to.input.value) };
168
+ },
169
+ validate
170
+ };
171
+ }
@@ -3,13 +3,23 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
+ import { isSafeUrl } from "./sanitize.js";
7
+
6
8
  let counter = 0;
7
9
 
10
+ // What el() refuses, so that data can never turn into script: event handler attributes (on*), inline style (a strict
11
+ // Content-Security-Policy forbids it anyway), srcdoc, and DOM properties that parse HTML.
12
+ const BLOCKED_ATTRIBUTE = /^(on|style$|srcdoc$)/i;
13
+ const BLOCKED_PROPERTY = /^(on|innerHTML$|outerHTML$|srcdoc$|insertAdjacentHTML$)/i;
14
+ const URL_ATTRIBUTE = new Set(["href", "src", "action", "formaction", "poster", "xlink:href", "cite", "data"]);
15
+
8
16
  // Unique element id, for label / aria wiring.
9
17
  export const uid = (prefix = "athena") => `${prefix}-${++counter}`;
10
18
 
11
19
  /**
12
- * Creates an element.
20
+ * Creates an element. This is the safe way to write pages: text is only ever inserted as text, attributes that run code
21
+ * (on*, style, srcdoc) and unsafe addresses (javascript:, data:, ...) in href / src / action are refused, listeners have to be
22
+ * functions, and children can be given as nested lists.
13
23
  *
14
24
  * @param {string} tag
15
25
  * @param {object} [props]
@@ -17,9 +27,9 @@ export const uid = (prefix = "athena") => `${prefix}-${++counter}`;
17
27
  * @param {string} [props.id]
18
28
  * @param {string} [props.text] set as textContent (never parsed as HTML)
19
29
  * @param {Object<string, string|boolean|number>} [props.attrs] attributes, false / null / undefined are skipped
20
- * @param {Object<string, Function>} [props.on] event listeners
21
- * @param {Object<string, *>} [props.prop] DOM properties (value, checked, disabled, ...)
22
- * @param {...(Node|string)} children
30
+ * @param {Object<string, Function>} [props.on] event listeners (a value that is not a function throws a TypeError)
31
+ * @param {Object<string, *>} [props.prop] DOM properties (value, checked, disabled, ...), not the ones that parse HTML
32
+ * @param {...(Node|string|number|Array|null|false)} children text, nodes, or lists of them
23
33
  */
24
34
  export function el(tag, props = {}, ...children) {
25
35
  const node = document.createElement(tag);
@@ -27,11 +37,26 @@ export function el(tag, props = {}, ...children) {
27
37
  if (props.id) node.id = props.id;
28
38
  if (props.text != null) node.textContent = props.text;
29
39
  for (const [name, value] of Object.entries(props.attrs ?? {})) {
30
- if (value !== false && value != null) node.setAttribute(name, value === true ? "" : value);
40
+ if (value === false || value == null) continue;
41
+ if (BLOCKED_ATTRIBUTE.test(name)) {
42
+ console.warn(`Athena UI: the attribute "${name}" is not allowed in el()`);
43
+ continue;
44
+ }
45
+ if (URL_ATTRIBUTE.has(name.toLowerCase()) && !isSafeUrl(value)) {
46
+ console.warn(`Athena UI: an unsafe address was refused in "${name}"`);
47
+ continue;
48
+ }
49
+ node.setAttribute(name, value === true ? "" : value);
50
+ }
51
+ for (const [name, handler] of Object.entries(props.on ?? {})) {
52
+ if (typeof handler !== "function") throw new TypeError(`Athena UI: the "${name}" listener has to be a function`);
53
+ node.addEventListener(name, handler);
31
54
  }
32
- for (const [name, handler] of Object.entries(props.on ?? {})) node.addEventListener(name, handler);
33
- Object.assign(node, props.prop);
34
- node.append(...children);
55
+ for (const [name, value] of Object.entries(props.prop ?? {})) {
56
+ if (BLOCKED_PROPERTY.test(name)) throw new TypeError(`Athena UI: the property "${name}" is not allowed in el()`);
57
+ node[name] = value;
58
+ }
59
+ for (const child of children) setContent(node, child);
35
60
  return node;
36
61
  }
37
62
 
@@ -82,3 +107,28 @@ export function asHandle(handle, { element = handle.element, also } = {}) {
82
107
  }
83
108
 
84
109
  export const cx = (...classes) => classes.filter(Boolean).join(" ");
110
+
111
+ /**
112
+ * A stricter el(): only the tags and attributes on your lists are allowed, everything else is refused (a tag throws, an attribute is
113
+ * skipped with a warning). For pages that are built from data you do not control, such as a plugin API. The refusals of el() still apply.
114
+ *
115
+ * @param {object} allow
116
+ * @param {string[]} [allow.tags] allowed tag names (default: any)
117
+ * @param {string[]} allow.attributes allowed attribute names, lower case: ["class", "title", "href"]
118
+ * @param {boolean} [allow.dataAndAria=true] data-* and aria-* attributes are allowed too
119
+ * @returns {typeof el}
120
+ */
121
+ export function createSafeBuilder({ tags, attributes = [], dataAndAria = true } = {}) {
122
+ const allowedTags = tags ? new Set(tags.map(tag => tag.toLowerCase())) : null;
123
+ const allowedAttributes = new Set(attributes.map(name => name.toLowerCase()));
124
+ return (tag, props = {}, ...children) => {
125
+ if (allowedTags && !allowedTags.has(String(tag).toLowerCase())) throw new TypeError(`Athena UI: the tag "${tag}" is not allowed here`);
126
+ const attrs = {};
127
+ for (const [name, value] of Object.entries(props.attrs ?? {})) {
128
+ const lower = name.toLowerCase();
129
+ if (allowedAttributes.has(lower) || (dataAndAria && (lower.startsWith("data-") || lower.startsWith("aria-")))) attrs[name] = value;
130
+ else console.warn(`Athena UI: the attribute "${name}" is not on the allow-list`);
131
+ }
132
+ return el(tag, { ...props, attrs }, ...children);
133
+ };
134
+ }
@@ -1,27 +1,29 @@
1
+ //elementGenerator for Athena UI
1
2
  //Author: Csaba Tóth https://github.com/csabatibortoth/
2
3
  //LICENCE: MIT
3
- //Repository: https://github.com/csabatibortoth/HTMLElementGenerator
4
- //Version: 0.3.0
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+ //Moved here from HTMLElementGenerator 0.3.1 (https://github.com/csabatibortoth/HTMLElementGenerator), which is no longer developed.
6
+ //The function, its options and its return value are the same.
5
7
 
6
8
  import {
7
9
  noBodyOrParentError,
8
10
  reportError,
9
11
  undefinedError,
10
12
  wrongInputTypeError,
11
- } from './errors.js';
13
+ } from "./errors.js";
12
14
 
13
15
  // Supported element types, each mapped to the extra options copied onto it as attributes.
14
16
  const ELEMENT_ATTRIBUTES = new Map([
15
- ['div', []],
16
- ['span', []],
17
- ['p', []],
18
- ['h1', []],
19
- ['h2', []],
20
- ['h3', []],
21
- ['h4', []],
22
- ['h5', []],
23
- ['h6', []],
24
- ['img', ['src', 'alt']],
17
+ ["div", []],
18
+ ["span", []],
19
+ ["p", []],
20
+ ["h1", []],
21
+ ["h2", []],
22
+ ["h3", []],
23
+ ["h4", []],
24
+ ["h5", []],
25
+ ["h6", []],
26
+ ["img", ["src", "alt"]],
25
27
  ]);
26
28
 
27
29
  export const supportedElements = Object.freeze([...ELEMENT_ATTRIBUTES.keys()]);
@@ -38,11 +40,11 @@ function createElement(options, attributes) {
38
40
  }
39
41
 
40
42
  // Listeners are only attached when a handler was actually provided.
41
- if (typeof onclick === 'function') {
42
- element.addEventListener('click', () => onclick(data));
43
+ if (typeof onclick === "function") {
44
+ element.addEventListener("click", () => onclick(data));
43
45
  }
44
- if (typeof onchange === 'function') {
45
- element.addEventListener('change', () => onchange(data));
46
+ if (typeof onchange === "function") {
47
+ element.addEventListener("change", () => onchange(data));
46
48
  }
47
49
  return element;
48
50
  }
@@ -65,18 +67,18 @@ function createElement(options, attributes) {
65
67
  */
66
68
  export function HTMLElementGenerator(options) {
67
69
  if (options == null) {
68
- return reportError(undefinedError('options', 'HTMLElementGenerator'));
70
+ return reportError(undefinedError("options", "HTMLElementGenerator"));
69
71
  }
70
72
 
71
73
  const attributes = ELEMENT_ATTRIBUTES.get(options.elementType);
72
74
  if (!attributes) {
73
- return reportError(wrongInputTypeError('options', 'HTMLElementGenerator', options));
75
+ return reportError(wrongInputTypeError("options", "HTMLElementGenerator", options));
74
76
  }
75
77
 
76
78
  const { body } = document;
77
79
  const parent = options.parent ? document.getElementById(options.parent) : body;
78
80
  if (!parent && !body) {
79
- return reportError(noBodyOrParentError('parent', 'HTMLElementGenerator'));
81
+ return reportError(noBodyOrParentError("parent", "HTMLElementGenerator"));
80
82
  }
81
83
 
82
84
  const element = createElement(options, attributes);
@@ -84,7 +86,7 @@ export function HTMLElementGenerator(options) {
84
86
  parent.append(element);
85
87
  } else {
86
88
  // Unknown parent id: fall back to a wrapper div on the body.
87
- const wrapper = document.createElement('div');
89
+ const wrapper = document.createElement("div");
88
90
  wrapper.append(element);
89
91
  body.append(wrapper);
90
92
  }
@@ -1,6 +1,8 @@
1
+ //errors of the element and control generators for Athena UI
1
2
  //Author: Csaba Tóth https://github.com/csabatibortoth/
2
3
  //LICENCE: MIT
3
- //Repository: https://github.com/csabatibortoth/HTMLElementGenerator
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+ //Moved here from HTMLElementGenerator 0.3.1 (https://github.com/csabatibortoth/HTMLElementGenerator), which is no longer developed.
4
6
 
5
7
  export const ErrorCode = Object.freeze({
6
8
  UNDEFINED: 0,
@@ -10,14 +12,14 @@ export const ErrorCode = Object.freeze({
10
12
 
11
13
  export const undefinedError = (variable, functionName) => ({
12
14
  errorCode: ErrorCode.UNDEFINED,
13
- errorString: 'undefined',
15
+ errorString: "undefined",
14
16
  errorVariable: variable,
15
17
  errorFunction: functionName,
16
18
  });
17
19
 
18
20
  export const wrongInputTypeError = (variable, functionName, inputOptions) => ({
19
21
  errorCode: ErrorCode.WRONG_INPUT_TYPE,
20
- errorString: 'Wrong Input Type defined',
22
+ errorString: "Wrong Input Type defined",
21
23
  errorVariable: variable,
22
24
  errorFunction: functionName,
23
25
  errorMiscInfo: inputOptions,
@@ -25,7 +27,7 @@ export const wrongInputTypeError = (variable, functionName, inputOptions) => ({
25
27
 
26
28
  export const noBodyOrParentError = (variable, functionName) => ({
27
29
  errorCode: ErrorCode.NO_BODY_OR_PARENT,
28
- errorString: 'No body or parent to append input!',
30
+ errorString: "No body or parent to append input!",
29
31
  errorVariable: variable,
30
32
  errorFunction: functionName,
31
33
  });
@@ -38,7 +40,7 @@ export function reportError(error) {
38
40
  console.error(error);
39
41
  const { body } = document;
40
42
  if (body) {
41
- const div = document.createElement('div');
43
+ const div = document.createElement("div");
42
44
  div.textContent = `Error Code: ${error.errorCode}, Error description: ${error.errorString}! For more information see console!`;
43
45
  body.append(div);
44
46
  }
@@ -3,6 +3,8 @@
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
5
 
6
+ import { getLocale } from "./i18n.js";
7
+
6
8
  // 1536 -> "1.5 KB"
7
9
  export function formatBytes(bytes) {
8
10
  if (!Number.isFinite(bytes) || bytes < 0) return "";
@@ -29,3 +31,52 @@ export function matchesAccept(file, accept) {
29
31
  : rule.endsWith("/*") ? type.startsWith(rule.slice(0, -1))
30
32
  : type === rule);
31
33
  }
34
+
35
+ /** 1234567.891 -> "1,234,567.89" (the separators of the current language). */
36
+ export function formatNumber(value, options = {}) {
37
+ if (!Number.isFinite(value)) return "";
38
+ return new Intl.NumberFormat(getLocale(), { maximumFractionDigits: 2, ...options }).format(value);
39
+ }
40
+
41
+ const DURATION_UNITS = [["day", 86400000], ["hour", 3600000], ["minute", 60000], ["second", 1000]];
42
+
43
+ /**
44
+ * A length of time in milliseconds as short text: 350 -> "350 ms", 45000 -> "45 sec", 7500000 -> "2 hr, 5 min".
45
+ * At most `parts` units are shown (default 2). The unit names follow the current language.
46
+ */
47
+ export function formatDuration(ms, { parts = 2 } = {}) {
48
+ if (!Number.isFinite(ms) || ms < 0) return "";
49
+ const unit = (value, name) => new Intl.NumberFormat(getLocale(), { style: "unit", unit: name, unitDisplay: "short", maximumFractionDigits: 0 }).format(value);
50
+ if (ms < 1000) return unit(Math.round(ms), "millisecond");
51
+ let rest = Math.round(ms / 1000) * 1000;
52
+ const out = [];
53
+ for (const [name, size] of DURATION_UNITS) {
54
+ const count = Math.floor(rest / size);
55
+ if (count > 0 && out.length < parts) {
56
+ out.push(unit(count, name));
57
+ rest -= count * size;
58
+ }
59
+ }
60
+ return out.join(", ");
61
+ }
62
+
63
+ const RELATIVE_UNITS = [["year", 31536000000], ["month", 2592000000], ["week", 604800000], ["day", 86400000], ["hour", 3600000], ["minute", 60000], ["second", 1000]];
64
+
65
+ /** "2 min ago", "in 3 days", "yesterday": the time between `date` and `now`, in the current language. */
66
+ export function formatRelativeTime(date, now = Date.now()) {
67
+ const time = date instanceof Date ? date.getTime() : typeof date === "number" ? date : Date.parse(date);
68
+ if (!Number.isFinite(time)) return "";
69
+ const diff = time - now;
70
+ const format = new Intl.RelativeTimeFormat(getLocale(), { numeric: "auto" });
71
+ for (const [unit, size] of RELATIVE_UNITS) {
72
+ if (Math.abs(diff) >= size || unit === "second") return format.format(Math.round(diff / size), unit);
73
+ }
74
+ return "";
75
+ }
76
+
77
+ /** A date (and time) for people: formatDate(d) -> "Nov 19, 2026"; formatDate(d, { time: true }) adds the time. */
78
+ export function formatDate(date, { time = false, style = "medium" } = {}) {
79
+ const value = date instanceof Date ? date : new Date(date);
80
+ if (Number.isNaN(value.getTime())) return "";
81
+ return new Intl.DateTimeFormat(getLocale(), time ? { dateStyle: style, timeStyle: style === "full" || style === "long" ? "medium" : "short" } : { dateStyle: style }).format(value);
82
+ }
@@ -0,0 +1,41 @@
1
+ //hungarianControls for Athena UI
2
+ //Author: Csaba Tóth https://github.com/csabatibortoth/
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+ //Moved here from the hungarianInputControls addon of HTMLControlGenerator (https://github.com/csabatibortoth/HTMLControlGenerator).
6
+
7
+ import { el } from "./dom.js";
8
+ import { buildControl, registerControl } from "./controls.js";
9
+
10
+ // Number of digits in each field of the control.
11
+ const SEGMENTS = {
12
+ hunPIN: [3, 3, 3], // personal insurance number
13
+ hunCRID: [2, 2, 6], // company registration ID
14
+ hunTID: [8, 1, 2] // TAX number
15
+ };
16
+
17
+ function segmentedInput(options, lengths) {
18
+ const value = String(options.value ?? "");
19
+ const group = el("span", { id: options.id, class: options.class });
20
+ let offset = 0;
21
+ lengths.forEach((length, index) => {
22
+ if (index > 0) group.append(el("span", { id: `${options.id}_spacer_${index - 1}`, class: `${options.id}SpacerClass`, text: " - " }));
23
+ group.append(buildControl({
24
+ inputType: "number",
25
+ id: `${options.id}_${index}`,
26
+ class: options.inputClass,
27
+ value: value.slice(offset, offset + length),
28
+ min: 0,
29
+ max: 10 ** length - 1
30
+ }));
31
+ offset += length;
32
+ });
33
+ return group;
34
+ }
35
+
36
+ /** Adds the input types hunPIN, hunCRID and hunTID (Hungarian personal insurance, company registration and tax numbers, in segments). */
37
+ export function registerHungarianInputControls() {
38
+ for (const [inputType, lengths] of Object.entries(SEGMENTS)) {
39
+ registerControl(inputType, options => segmentedInput(options, lengths));
40
+ }
41
+ }