@logimaxx/kgrid 0.3.1 → 0.5.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.
@@ -2,16 +2,307 @@
2
2
  * Built-in field types with no external library dependency (plain HTML / jQuery DOM).
3
3
  */
4
4
  (function (CT) {
5
+ const MULTI_SELECT_VALUE_CLASS = "kgrid-multi-select-value";
6
+ const MULTI_SELECT_SEP = ";";
7
+
8
+ /**
9
+ * Normalize multi_select values to a semicolon-joined string (dbAPI `><` / IN).
10
+ * @param {*} value
11
+ * @param {string} [sep]
12
+ * @returns {string}
13
+ */
14
+ CT.normalizeMultiSelectValue = function (value, sep) {
15
+ const separator = sep || MULTI_SELECT_SEP;
16
+ if (value == null || value === "") {
17
+ return "";
18
+ }
19
+ if (Array.isArray(value)) {
20
+ return value
21
+ .filter(function (v) {
22
+ return v != null && v !== "";
23
+ })
24
+ .map(String)
25
+ .join(separator);
26
+ }
27
+ return String(value);
28
+ };
29
+
30
+ CT.parseMultiSelectValue = function (value, sep) {
31
+ const str = CT.normalizeMultiSelectValue(value, sep);
32
+ if (!str) {
33
+ return [];
34
+ }
35
+ return str.split(sep || MULTI_SELECT_SEP).filter(Boolean);
36
+ };
37
+
38
+ (function installMultiSelectValHooks() {
39
+ const prev = $.valHooks.hidden || {};
40
+ $.valHooks.hidden = {
41
+ get: function (elem) {
42
+ if (elem && elem.classList && elem.classList.contains(MULTI_SELECT_VALUE_CLASS)) {
43
+ return elem.value;
44
+ }
45
+ return prev.get ? prev.get(elem) : undefined;
46
+ },
47
+ set: function (elem, value) {
48
+ if (elem && elem.classList && elem.classList.contains(MULTI_SELECT_VALUE_CLASS)) {
49
+ const sep = $(elem).data("kgridMultiSep") || MULTI_SELECT_SEP;
50
+ elem.value = CT.normalizeMultiSelectValue(value, sep);
51
+ $(elem).triggerHandler("kgrid:multiselect:set");
52
+ return true;
53
+ }
54
+ return prev.set ? prev.set(elem, value) : undefined;
55
+ },
56
+ };
57
+ })();
58
+
59
+ function assertMultiSelectOptions(config, mode) {
60
+ if (!Array.isArray(config.options)) {
61
+ throw new Error(
62
+ "multi_select requires an options array (" +
63
+ mode +
64
+ "): " +
65
+ JSON.stringify(config, null, 2)
66
+ );
67
+ }
68
+ config.options.forEach(function (opt) {
69
+ if (!opt || typeof opt.label !== "string" || typeof opt.value !== "string") {
70
+ throw new Error(
71
+ "multi_select options need string label and value: " +
72
+ JSON.stringify(config, null, 2)
73
+ );
74
+ }
75
+ });
76
+ }
77
+
78
+ function multiSelectEmptyLabel(config) {
79
+ if (config.placeholder != null && config.placeholder !== "") {
80
+ return String(config.placeholder);
81
+ }
82
+ return "All";
83
+ }
84
+
85
+ function multiSelectSummary(selected, options, emptyLabel) {
86
+ if (!selected.length) {
87
+ return emptyLabel;
88
+ }
89
+ if (selected.length === 1) {
90
+ const match = options.find(function (opt) {
91
+ return opt.value === selected[0];
92
+ });
93
+ return match ? match.label : selected[0];
94
+ }
95
+ return selected.length + " selected";
96
+ }
97
+
98
+ function buildMultiSelectUi($input, config, mode) {
99
+ const sep = config.separator || MULTI_SELECT_SEP;
100
+ const options = config.options || [];
101
+ const emptyLabel = multiSelectEmptyLabel(config);
102
+ const compact = mode === "filter";
103
+
104
+ $input.data("kgridMultiSep", sep);
105
+ $input.addClass(MULTI_SELECT_VALUE_CLASS);
106
+
107
+ const $root = $("<div>")
108
+ .addClass("kgrid-multi-select")
109
+ .attr("data-mode", mode);
110
+ const $panel = $("<div>").addClass("kgrid-multi-select-panel");
111
+ let $toggle = null;
112
+
113
+ if (compact) {
114
+ $toggle = $("<button>")
115
+ .attr({ type: "button", "aria-expanded": "false" })
116
+ .addClass("kgrid-multi-select-toggle form-select form-select-sm");
117
+ $panel.attr("hidden", "hidden");
118
+ $root.append($toggle, $panel);
119
+ } else {
120
+ $root.addClass("kgrid-multi-select-open");
121
+ $root.append($panel);
122
+ }
123
+
124
+ options.forEach(function (opt, index) {
125
+ const uid = "kgrid_ms_" + CT.uuid() + "_" + index;
126
+ const $label = $("<label>")
127
+ .addClass("kgrid-multi-select-option")
128
+ .attr("for", uid);
129
+ $("<input>")
130
+ .attr({
131
+ type: "checkbox",
132
+ id: uid,
133
+ value: opt.value,
134
+ class: "kgrid-multi-select-check",
135
+ })
136
+ .appendTo($label);
137
+ $("<span>").addClass("kgrid-multi-select-label").text(opt.label).appendTo($label);
138
+ $panel.append($label);
139
+ });
140
+
141
+ $input.before($root);
142
+ $root.append($input);
143
+
144
+ function selectedValues() {
145
+ return CT.parseMultiSelectValue($input[0].value, sep);
146
+ }
147
+
148
+ function syncCheckboxesFromInput() {
149
+ const selected = selectedValues();
150
+ $panel.find("input[type='checkbox']").each(function () {
151
+ this.checked = selected.indexOf(this.value) !== -1;
152
+ });
153
+ if ($toggle) {
154
+ $toggle.text(multiSelectSummary(selected, options, emptyLabel));
155
+ }
156
+ }
157
+
158
+ function syncInputFromCheckboxes(triggerChange) {
159
+ const vals = [];
160
+ $panel.find("input[type='checkbox']:checked").each(function () {
161
+ vals.push(this.value);
162
+ });
163
+ const next = vals.join(sep);
164
+ if ($input[0].value !== next) {
165
+ $input[0].value = next;
166
+ if (triggerChange) {
167
+ $input.trigger("change");
168
+ }
169
+ }
170
+ if ($toggle) {
171
+ $toggle.text(multiSelectSummary(vals, options, emptyLabel));
172
+ }
173
+ }
174
+
175
+ function setOpen(open) {
176
+ if (!$toggle) {
177
+ return;
178
+ }
179
+ if (open) {
180
+ // Leave the table/card overflow context so the list is fully visible.
181
+ $panel.appendTo(document.body);
182
+ $panel.addClass("kgrid-multi-select-panel-floating");
183
+ $panel.removeAttr("hidden");
184
+ $root.addClass("kgrid-multi-select-open");
185
+ $toggle.attr("aria-expanded", "true");
186
+ positionFilterPanel();
187
+ } else {
188
+ $panel.attr("hidden", "hidden");
189
+ $root.removeClass("kgrid-multi-select-open");
190
+ $toggle.attr("aria-expanded", "false");
191
+ clearFilterPanelPosition();
192
+ $panel.removeClass("kgrid-multi-select-panel-floating");
193
+ $panel.insertAfter($toggle);
194
+ }
195
+ }
196
+
197
+ function positionFilterPanel() {
198
+ if (!$toggle) {
199
+ return;
200
+ }
201
+ const rect = $toggle[0].getBoundingClientRect();
202
+ const width = Math.max(rect.width, 12 * 16);
203
+ let left = rect.left;
204
+ const maxLeft = window.innerWidth - width - 8;
205
+ if (left > maxLeft) {
206
+ left = Math.max(8, maxLeft);
207
+ }
208
+ let top = rect.bottom + 2;
209
+ const approxHeight = Math.min(14 * 16, options.length * 28 + 16);
210
+ if (top + approxHeight > window.innerHeight - 8 && rect.top > approxHeight + 8) {
211
+ top = rect.top - approxHeight - 2;
212
+ }
213
+ $panel.css({
214
+ position: "fixed",
215
+ top: top + "px",
216
+ left: left + "px",
217
+ width: width + "px",
218
+ minWidth: width + "px",
219
+ maxWidth: "min(18rem, calc(100vw - 16px))",
220
+ zIndex: 1080,
221
+ });
222
+ }
223
+
224
+ function clearFilterPanelPosition() {
225
+ $panel.css({
226
+ position: "",
227
+ top: "",
228
+ left: "",
229
+ width: "",
230
+ minWidth: "",
231
+ maxWidth: "",
232
+ zIndex: "",
233
+ });
234
+ }
235
+
236
+ const ns = ".kgridMultiSelect_" + CT.uuid();
237
+
238
+ $panel.on("change", "input[type='checkbox']", function () {
239
+ syncInputFromCheckboxes(true);
240
+ });
241
+
242
+ $input.on("kgrid:multiselect:set", function () {
243
+ syncCheckboxesFromInput();
244
+ });
245
+
246
+ if ($toggle) {
247
+ $toggle.on("click", function (e) {
248
+ e.preventDefault();
249
+ e.stopPropagation();
250
+ setOpen(!$root.hasClass("kgrid-multi-select-open"));
251
+ });
252
+ $(document).on("mousedown" + ns, function (e) {
253
+ if (!$root.hasClass("kgrid-multi-select-open")) {
254
+ return;
255
+ }
256
+ if ($(e.target).closest($root).length || $(e.target).closest($panel).length) {
257
+ return;
258
+ }
259
+ setOpen(false);
260
+ });
261
+ $(window).on("resize" + ns + " scroll" + ns, function () {
262
+ if ($root.hasClass("kgrid-multi-select-open")) {
263
+ positionFilterPanel();
264
+ }
265
+ });
266
+ }
267
+
268
+ const formBind = function () {
269
+ const formEl = $input.prop("form") || ($input[0] && $input[0].form);
270
+ if (!formEl) {
271
+ return;
272
+ }
273
+ $(formEl).off("reset" + ns).on("reset" + ns, function () {
274
+ setTimeout(syncCheckboxesFromInput, 0);
275
+ });
276
+ };
277
+ formBind();
278
+ setTimeout(formBind, 0);
279
+
280
+ syncCheckboxesFromInput();
281
+ return $root;
282
+ }
283
+
5
284
  CT.registerFieldType("multi_select", {
285
+ filterEvents: "change",
286
+ filterDebounceMs: 0,
287
+ validate(config, mode) {
288
+ assertMultiSelectOptions(config, mode);
289
+ },
6
290
  create({ config }) {
7
- const $input = $("<select class='form-select form-select-sm' multiple>");
8
- if (Array.isArray(config.options)) {
9
- config.options.forEach((opt) => {
10
- $("<option>").text(opt.label).attr("value", opt.value).appendTo($input);
11
- });
291
+ const $input = $("<input type='hidden'>").addClass(MULTI_SELECT_VALUE_CLASS);
292
+ if (config.separator) {
293
+ $input.data("kgridMultiSep", config.separator);
12
294
  }
13
295
  return { $input, skipValueAttr: true };
14
296
  },
297
+ mount(ctx) {
298
+ buildMultiSelectUi(ctx.$input, ctx.config || {}, ctx.mode);
299
+ if (ctx.mode === "update" && ctx.item && ctx.col && ctx.col.name) {
300
+ const raw = ctx.item.attributes ? ctx.item.attributes[ctx.col.name] : null;
301
+ if (raw != null && raw !== "") {
302
+ ctx.$input.val(raw);
303
+ }
304
+ }
305
+ },
15
306
  });
16
307
 
17
308
  CT.registerFieldType("date_range", {
package/src/filters.js CHANGED
@@ -144,8 +144,9 @@
144
144
  * @param {HTMLFormElement|JQuery} filterFormEl
145
145
  * @param {Object} options
146
146
  * @param {Object} [collection] KViews collection
147
+ * @param {{ skipInitSubmit?: boolean }} [extra]
147
148
  */
148
- CT.setupDefaultFilters = function (filterFormEl, options, collection) {
149
+ CT.setupDefaultFilters = function (filterFormEl, options, collection, extra) {
149
150
  const form = $(filterFormEl)[0];
150
151
  if (!form || !options || !options.features || !options.features.filtering) {
151
152
  return;
@@ -206,7 +207,7 @@
206
207
  const missing = persisted.some(function (col) {
207
208
  return urlFilter.indexOf(col.name + "=") === -1;
208
209
  });
209
- if (missing) {
210
+ if (missing && !(extra && extra.skipInitSubmit)) {
210
211
  collection.filtering.handleSubmit(form);
211
212
  }
212
213
  };
@@ -323,16 +324,25 @@
323
324
  }
324
325
  }
325
326
 
326
- input.attr("data-operator", filter.operator);
327
+ const operator =
328
+ filter.operator ||
329
+ (filter.type === "multi_select" ? "><" : undefined);
330
+ if (operator != null) {
331
+ input.attr("data-operator", operator);
332
+ }
327
333
  input.attr("form", filterFormId);
328
334
  input.attr("name", col.name);
329
335
 
330
336
  const defVal = CT.filterDefaultValue(filter.default);
331
337
  if (defVal != null && defVal !== "" && !input.val()) {
332
- input.val(String(defVal));
333
- input.attr("data-default", String(defVal));
338
+ const normalized =
339
+ filter.type === "multi_select"
340
+ ? CT.normalizeMultiSelectValue(defVal, filter.separator)
341
+ : String(defVal);
342
+ input.val(normalized);
343
+ input.attr("data-default", normalized);
334
344
  if (input[0]) {
335
- input[0].defaultValue = String(defVal);
345
+ input[0].defaultValue = normalized;
336
346
  }
337
347
  }
338
348
 
@@ -361,6 +371,40 @@
361
371
  return filterForm;
362
372
  };
363
373
 
374
+ /** Write current form fields into collection.url.parameters.filter (same rules as KViews Filtering). */
375
+ CT.syncFormFiltersToCollectionUrl = function (form, collection) {
376
+ if (!form || !collection || !collection.url) {
377
+ return;
378
+ }
379
+ if (!collection.url.parameters) {
380
+ collection.url.parameters = {};
381
+ }
382
+ const filter = [];
383
+ const els = form.elements;
384
+ if (!els) {
385
+ return;
386
+ }
387
+ for (let i = 0; i < els.length; i++) {
388
+ const el = els[i];
389
+ if (!el || !el.name) {
390
+ continue;
391
+ }
392
+ const $el = $(el);
393
+ const value = $el.val();
394
+ if (value == null || value === "") {
395
+ continue;
396
+ }
397
+ const operator = $el.attr("data-operator") || $el.data("operator") || "=";
398
+ filter.push(el.name + operator + value);
399
+ }
400
+ collection.offset = 0;
401
+ if (filter.length) {
402
+ collection.url.parameters.filter = filter.join(",");
403
+ } else {
404
+ delete collection.url.parameters.filter;
405
+ }
406
+ };
407
+
364
408
  CT.FilterForm = function (form) {
365
409
  this.form = $(form)[0];
366
410
  this.filter = (name, value, operator = "~=~") => {
package/src/init.js CHANGED
@@ -57,9 +57,40 @@
57
57
  }
58
58
  return api.setInteraction(api.getInteraction() === "edit" ? "view" : "edit");
59
59
  },
60
+ getLayout() {
61
+ return CT.layoutFromColumns(options.columns);
62
+ },
63
+ setLayout(layout) {
64
+ CT.applyColumnLayout(api, options, layout);
65
+ CT.preferencesSaveLayout(options, api.getLayout());
66
+ return api.getLayout();
67
+ },
68
+ resetLayout() {
69
+ const byName = new Map();
70
+ options.columns.forEach(function (col) {
71
+ if (col && col.name) {
72
+ byName.set(col.name, col);
73
+ }
74
+ });
75
+ options.columns = schemaOrder
76
+ .map(function (name) {
77
+ return byName.get(name);
78
+ })
79
+ .filter(Boolean);
80
+ CT.preferencesSaveLayout(options, null);
81
+ CT.applyColumnLayout(api, options, null);
82
+ return api.getLayout();
83
+ },
60
84
  };
61
85
 
62
- options.columns = options.columns.map((col) => CT.normalizeColumnConfig(col));
86
+ options.columns = (options.columns || []).map((col) => CT.normalizeColumnConfig(col));
87
+ const schemaOrder = options.columns.map(function (col) {
88
+ return col.name;
89
+ });
90
+ options.columns = CT.mergeLayoutIntoColumns(
91
+ options.columns,
92
+ CT.preferencesLoadLayout(options)
93
+ );
63
94
 
64
95
  const handlers = options.handlers ?? {};
65
96
  delete options.handlers;
@@ -74,6 +105,14 @@
74
105
  }
75
106
  options.onClone = fn;
76
107
  }
108
+ CT.resolveRowActions(options, handlers);
109
+ {
110
+ const ra = options._resolvedRowActions;
111
+ CT.getTableInteractionHost($host).attr(
112
+ "data-has-row-menu",
113
+ ra && ra.menuItems && ra.menuItems.length ? "true" : "false"
114
+ );
115
+ }
77
116
  options.columns.forEach((col) => {
78
117
  ["insert", "update", "display"].forEach((mode) => {
79
118
  const events = col[mode].events;
@@ -127,7 +166,13 @@
127
166
  const hasActionColumn = CT.hasActionColumn(options);
128
167
  const visibleColumnsCount = labelsRow.find("th").length;
129
168
  const dataColumnCount = visibleColumnsCount - (hasActionColumn ? 1 : 0);
130
- CT.syncActionColumnColgroup(table, dataColumnCount, hasActionColumn);
169
+ CT.syncActionColumnColgroup(
170
+ table,
171
+ dataColumnCount,
172
+ hasActionColumn,
173
+ options,
174
+ CT.chooserColumns(options.columns)
175
+ );
131
176
 
132
177
  const filterForm = options.filterForm ?? CT.setupFilterHeader(table, options);
133
178
 
@@ -191,7 +236,24 @@
191
236
  if (options.insertUrl) {
192
237
  api.instance.setUrl(options.insertUrl, "insert");
193
238
  }
239
+ }
240
+
241
+ CT.setupDefaultFilters(filterForm, options, api.instance, { skipInitSubmit: true });
242
+ const filterFormEl = filterForm && (filterForm.jquery ? filterForm[0] : filterForm);
243
+ CT.applyUserFilters(
244
+ filterFormEl,
245
+ options.columns,
246
+ CT.preferencesLoadFilters(options)
247
+ );
248
+ CT.ensureUrlFiltersOnForm(filterFormEl, api.instance);
249
+ CT.setupFilterPersistence(filterFormEl, options);
250
+ CT.setupColumnChooser($host, options, api);
251
+
252
+ if (options.url) {
194
253
  try {
254
+ if (options.features && options.features.filtering && filterFormEl) {
255
+ CT.syncFormFiltersToCollectionUrl(filterFormEl, api.instance);
256
+ }
195
257
  await api.instance.loadFromRemote();
196
258
  } catch (error) {
197
259
  CT.onError(error);
@@ -203,8 +265,6 @@
203
265
  throw new Error("Invalid data: missing datasource url or data for table");
204
266
  }
205
267
 
206
- CT.setupDefaultFilters(filterForm, options, api.instance);
207
-
208
268
  return api;
209
269
  };
210
270
  })(window.KGrid);
package/src/insert-row.js CHANGED
@@ -36,7 +36,7 @@
36
36
  grid.instance.newItem(data).then(()=>{
37
37
  event.target.reset();
38
38
  if(typeof options.onNewItemCreated=="function") {
39
- options.onNewItemCreated(data);
39
+ options.onNewItemCreated(data, event.target);
40
40
  }
41
41
  }).catch(CT.onError);
42
42
  });
@@ -94,6 +94,10 @@
94
94
  case "hidden":
95
95
  input = $(`<input type='hidden' class='form-input form-control form-control-sm'/>`);
96
96
  break;
97
+ case "checkbox":
98
+ input = $("<input autocomplete='off' type='checkbox' class='form-check-input'/>");
99
+ input.attr("data-type", insertType);
100
+ break;
97
101
  default:
98
102
  if(CT.isValidInputType(insertType)) {
99
103
  input = $(`<input autocomplete='off' type='${insertType}' class='form-input form-control form-control-sm'/>`);
@@ -104,12 +108,18 @@
104
108
  }
105
109
  }
106
110
 
107
- if(insertConfig.default != null && insertConfig.default !== "" && !input.val()) {
108
- const defVal = (typeof insertConfig.default === "object" && insertConfig.default.value != null)
109
- ? insertConfig.default.value
110
- : insertConfig.default;
111
- if(String(defVal).trim()) {
112
- input.val(defVal).trigger("change");
111
+ const rawDefault = (typeof insertConfig.default === "object" && insertConfig.default && insertConfig.default.value != null)
112
+ ? insertConfig.default.value
113
+ : insertConfig.default;
114
+ if (insertType === "checkbox") {
115
+ const on = CT.isFlagOn(rawDefault);
116
+ input.prop("checked", on).prop("defaultChecked", on);
117
+ } else if(insertConfig.default != null && insertConfig.default !== "" && !input.val()) {
118
+ if(String(rawDefault).trim()) {
119
+ input.val(rawDefault).trigger("change");
120
+ if (input[0] && "defaultValue" in input[0]) {
121
+ input[0].defaultValue = input[0].value;
122
+ }
113
123
  }
114
124
  }
115
125
 
@@ -132,7 +142,8 @@
132
142
  }
133
143
 
134
144
  if(insertConfig.type!=="hidden") {
135
- const $td = $("<td>").append(input).appendTo(newRecordRow).attr("data-label", col.label);
145
+ const $control = insertType === "checkbox" ? CT.wrapFlagSwitch(input) : input;
146
+ const $td = $("<td>").append($control).appendTo(newRecordRow).attr("data-label", col.label);
136
147
  CT.applyColumnCellMeta($td, col);
137
148
  }
138
149
  CT.mountField({