@itrocks/list 0.28.3 → 0.30.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.
package/README.md CHANGED
@@ -111,20 +111,23 @@ HTML list filters interpret the first hyphen as an interval separator. Spaces ar
111
111
  - `2000 - 2010` uses inclusive `between(2000, 2010)`.
112
112
  - `-2010` means less than or equal to 2010.
113
113
  - `2000-` means greater than or equal to 2000.
114
- - A hyphen with neither bound applies no criterion.
115
-
116
- Leading `>`, `>=`, `<`, `<=`, `<>`, `!=` and `!` apply the corresponding comparison.
117
- The prefixes `<>`, `!=` and `!` mean not equal; the equals sign after `!` is optional.
118
- With `*` or `?` in their operand, these three prefixes request `NOT LIKE` instead, using the same wildcard conversion.
119
- A leading `=` requests exact equality, including an empty string. Spaces around explicit comparison operands are
120
- ignored.
114
+ - A lone hyphen matches the exact text `-` in a text column.
115
+
116
+ Leading `>`, `>=`, `<` and `<=` apply the corresponding comparison. A leading `=` compares the whole value.
117
+ On text, `!=`, `<>` and `≠` compare the whole value for inequality. Any wildcard characters in their operand are
118
+ literal. For example, `<>%Alien%` compares against the literal value `%Alien%`.
119
+ The `!` prefix excludes a text prefix or an explicit pattern. `!Alien` produces `NOT LIKE 'Alien%'` and `!*Alien*`
120
+ produces `NOT LIKE '%Alien%'`. A bare `=` finds the empty string, while `!` and `!=` find text different from the empty
121
+ string. Spaces around explicit comparison operands are ignored.
121
122
  Explicit operators take precedence over interval syntax, so `>=-10` compares with negative ten and `=A-B` matches `A-B`.
122
123
 
123
- Without an explicit comparison operator, `*` and `?` request `LIKE` for any property type, replacing all `*` with `%`
124
- and all `?` with `_`. The pattern is used as supplied without an extra trailing wildcard. Wildcards take precedence
125
- over interval syntax, so `2000-20??` becomes the pattern `2000-20__`.
124
+ Without a comparison operator, any of `*`, `%`, `?` and `_` selects `LIKE`. Date patterns follow the date rules below.
125
+ `*` and `%` stand for zero or more characters. `?` and `_` stand for a single character.
126
+ The explicit pattern supplies its own wildcards and takes precedence over interval syntax.
127
+ For example, `2000-20??` and `2000-20__` both produce the pattern `2000-20__`.
126
128
 
127
- `empty` is an alias for `!?*`; `!empty`, `!=empty` and `<>empty` mean `?*` (a non-empty value).
129
+ On text, `empty` finds the empty string and `!empty` finds non-empty values. On a numeric field or a single object
130
+ reference, they use `IS NULL` and `IS NOT NULL` respectively.
128
131
  The alias accepts the current language's translation through `trReverse()`, for example `vide` and `!vide` in French.
129
132
  Alias matching ignores case and surrounding spaces. Use `=empty` or `=vide` to match the literal word.
130
133
  For dates, these aliases use the existing empty (`!?`) and non-empty (`?`) date criteria.
@@ -193,13 +196,14 @@ Calendar periods include their full final day. Explicit comparisons use the corr
193
196
  period: `>2020` starts after 2020, and `<=2020` includes all of 2020. Not-equal comparisons exclude the whole period
194
197
  through `NOT BETWEEN`.
195
198
 
196
- Date digits may contain `%`, `?` or `*`. Patterns are reordered into SQL year-month-day order, `?` becomes `_` and `*`
197
- becomes `%`. For example `??/03/2020` becomes `2020-03-__%` in day/month order; the final `%` also permits stored times.
199
+ Date digits may contain `*`, `%`, `?` or `_`. Patterns are reordered into SQL year-month-day order, `?` becomes `_` and
200
+ `*` becomes `%`. For example, `??/03/2020` and `__/03/2020` become `2020-03-__%` in day/month order.
201
+ The final `%` also permits stored times.
198
202
  Each wildcard counts as one digit while identifying the input format and completing date fields. For example,
199
203
  `??` selects month patterns in the current year, `????` selects year patterns, and a two-character year such as `**`
200
204
  is prefixed with the current century before replacing the wildcards. One-character month and day fields are zero-padded.
201
- The prefixes `!`, `!=` and `<>` use `NOT LIKE` for these patterns.
202
- On a date property, `?` alone excludes the zero date; `!?`, `!=?` and `<>?` find zero dates.
205
+ On dates, the prefixes `!`, `!=`, `<>` and `≠` use `NOT LIKE` for these patterns.
206
+ On a date property, a lone `?` or `_` finds filled-in dates. With any of those prefixes, it finds empty dates.
203
207
  Empty dates are stored as `0000-00-00`, never SQL `NULL`.
204
208
  Invalid dates match no rows, without calendar rollover.
205
209
  Original input text is retained in session and restored for subsequent feed requests.
@@ -359,6 +363,12 @@ The same projection is used when reloading the list or adding an individual comp
359
363
  rendered values, mandatory row scope, partial selection, removal and session restoration. It creates and cleans up
360
364
  its own temporary database and server using the existing selector integration recipe.
361
365
 
366
+ ## Column widths
367
+
368
+ Drag the edge of a column heading to set its width. Double-click the same edge to return to automatic sizing.
369
+ List actions can override `canResizeColumns(request)` to disable the gesture while displaying saved widths.
370
+ Only explicit pixel widths are stored in `columnWidths`, by property path. Removing a column clears its width.
371
+
362
372
  ## Session state integration
363
373
 
364
374
  `@itrocks/list/session-state` exposes the settings independently of rendering:
@@ -372,8 +382,8 @@ replaceListState(request.request, request.type, settings)
372
382
  replaceListState(request.request, request.type)
373
383
  ```
374
384
 
375
- `listState(request: ServerRequest, type: Type): ListState` returns a deep copy of columns, filters
376
- and ordered sort tuples.
385
+ `listState(request: ServerRequest, type: Type): ListState` returns a deep copy of columns, explicit column widths,
386
+ filters and ordered sort tuples.
377
387
  `replaceListState(request, type, state?)` replaces the complete session entry;
378
388
  omitting state restores reflected defaults on the next render.
379
389
  Neither function queries business rows or changes mandatory scopes.
package/build.js CHANGED
@@ -2,6 +2,7 @@ import { build } from '@itrocks/build/build.js';
2
2
  import { TableColumnAdd } from '@itrocks/table/column-add.js';
3
3
  import { TableColumnReorderFreeze } from '@itrocks/table/column-reorder-freeze.js';
4
4
  import { TableColumnReorder } from '@itrocks/table/column-reorder.js';
5
+ import { TableColumnResize } from '@itrocks/table/column-resize.js';
5
6
  import { TableFeed } from '@itrocks/table/feed.js';
6
7
  import { TableFreeze } from '@itrocks/table/freeze.js';
7
8
  import { TableFreezeInheritBackground } from '@itrocks/table/freeze/inherit-background.js';
@@ -13,16 +14,28 @@ import './column-filter.js';
13
14
  import './search-focus.js';
14
15
  import './toolbar.js';
15
16
  build('article[data-action="list"] > form > table.objects', table => {
16
- let persistedColumns = [...table.querySelectorAll('thead th[data-property]')]
17
- .map(header => header.dataset.property).join(',');
17
+ const headers = [...table.querySelectorAll('thead th[data-property]')];
18
+ const persistedWidths = new Map();
19
+ const pendingWidths = new Map();
20
+ let persistedColumns = headers.map(header => header.dataset.property).join(',');
21
+ for (const header of headers) {
22
+ if (header.dataset.columnWidth) {
23
+ persistedWidths.set(header.dataset.property, Number(header.dataset.columnWidth));
24
+ }
25
+ }
18
26
  let saving = Promise.resolve();
19
- const request = (query, signal) => {
27
+ const request = (query, signal, method = 'GET') => {
20
28
  const form = table.closest('form');
21
- const result = saving.then(() => fetch(`${form.action}?${query}`, { keepalive: true, signal }));
29
+ const result = saving.then(() => fetch(`${form.action}?${query}`, { keepalive: true, method, signal }));
22
30
  saving = result.then(() => { }, () => { });
23
31
  void result.then(response => {
24
32
  if (response.ok && query.has('columns') && (query.get('columns') !== persistedColumns)) {
25
33
  persistedColumns = query.get('columns');
34
+ const paths = new Set(persistedColumns.split(','));
35
+ for (const path of persistedWidths.keys()) {
36
+ if (!paths.has(path))
37
+ persistedWidths.delete(path);
38
+ }
26
39
  table.dispatchEvent(new CustomEvent('itrocks:list-change', { bubbles: true }));
27
40
  }
28
41
  }, () => { });
@@ -39,6 +52,45 @@ build('article[data-action="list"] > form > table.objects', table => {
39
52
  throw new Error('Unable to save columns');
40
53
  });
41
54
  };
55
+ const saveWidth = (header, width) => {
56
+ const path = header.dataset.property;
57
+ const query = new URLSearchParams({ resizeColumn: path, columnWidth: String(width) });
58
+ const result = request(query, undefined, 'POST');
59
+ pendingWidths.set(path, result);
60
+ void result.then(response => {
61
+ if (response.status !== 204)
62
+ throw new Error('Unable to save column width');
63
+ const previous = persistedWidths.get(path) ?? 'auto';
64
+ if (width === 'auto')
65
+ persistedWidths.delete(path);
66
+ else
67
+ persistedWidths.set(path, width);
68
+ if (width !== previous) {
69
+ table.dispatchEvent(new CustomEvent('itrocks:list-change', { bubbles: true }));
70
+ }
71
+ }).catch(error => {
72
+ if (pendingWidths.get(path) === result) {
73
+ resize.setWidth(header, persistedWidths.get(path) ?? 'auto');
74
+ }
75
+ console.error(error);
76
+ }).finally(() => {
77
+ if (pendingWidths.get(path) === result)
78
+ pendingWidths.delete(path);
79
+ });
80
+ };
81
+ const resize = new TableColumnResize({
82
+ identify: header => header.dataset.property,
83
+ isInResizeZone: (header, y) => {
84
+ const filter = header.querySelector(':scope > input[data-property-filter]');
85
+ if (!filter)
86
+ return true;
87
+ const bottom = filter.getBoundingClientRect().top;
88
+ const lineHeight = parseFloat(getComputedStyle(header).lineHeight);
89
+ return (y < bottom) && (!Number.isFinite(lineHeight) || (y >= bottom - lineHeight));
90
+ },
91
+ isResizable: header => table.hasAttribute('data-column-resize') && (header.dataset.property !== undefined),
92
+ onChange: saveWidth
93
+ });
42
94
  const tableColumnReorder = new TableColumnReorder({
43
95
  isReorderable: header => header.dataset.property !== undefined,
44
96
  onRemove: () => saveColumns(),
@@ -55,8 +107,8 @@ build('article[data-action="list"] > form > table.objects', table => {
55
107
  const addition = new TableColumnAdd({ identify: header => header.dataset.property });
56
108
  const instance = tableByElement(table, {
57
109
  plugins: [
58
- tableColumnReorder, addition, TableColumnReorderFreeze, TableFeed, TableFreeze, TableFreezeInheritBackground,
59
- TableFreezeInheritBorder, tableLink
110
+ tableColumnReorder, resize, addition, TableColumnReorderFreeze, TableFeed, TableFreeze,
111
+ TableFreezeInheritBackground, TableFreezeInheritBorder, tableLink
60
112
  ]
61
113
  });
62
114
  table.dispatchEvent(new CustomEvent('itrocks:list-ready', {
@@ -0,0 +1,12 @@
1
+ import type { Request } from '@itrocks/request-response';
2
+ import type { Columns } from './columns';
3
+ import { Parameter } from './parameter';
4
+ export declare function isColumnWidth(width: unknown): width is number;
5
+ export declare class ColumnWidths<T extends object> extends Parameter {
6
+ private readonly columns;
7
+ private widths;
8
+ constructor(columns: Columns<T>);
9
+ getParams(request: Request): boolean;
10
+ serialize(): Record<string, number> | undefined;
11
+ unserialize(data: unknown): void;
12
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ColumnWidths = void 0;
4
+ exports.isColumnWidth = isColumnWidth;
5
+ const parameter_1 = require("./parameter");
6
+ function isColumnWidth(width) {
7
+ return (typeof width === 'number') && Number.isSafeInteger(width) && (width > 0);
8
+ }
9
+ class ColumnWidths extends parameter_1.Parameter {
10
+ columns;
11
+ widths = new Map();
12
+ constructor(columns) {
13
+ super();
14
+ this.columns = columns;
15
+ }
16
+ getParams(request) {
17
+ const paths = new Set(this.columns.map(column => column.name));
18
+ const { columnWidth, resizeColumn } = request.data;
19
+ if (resizeColumn !== undefined || columnWidth !== undefined) {
20
+ if ((typeof resizeColumn !== 'string') || !paths.has(resizeColumn))
21
+ return false;
22
+ if (columnWidth === 'auto') {
23
+ this.widths.delete(resizeColumn);
24
+ }
25
+ else {
26
+ if ((typeof columnWidth !== 'string') || !/^\d+$/.test(columnWidth))
27
+ return false;
28
+ const width = Number(columnWidth);
29
+ if (!isColumnWidth(width))
30
+ return false;
31
+ this.widths.set(resizeColumn, width);
32
+ }
33
+ }
34
+ for (const path of this.widths.keys()) {
35
+ if (!paths.has(path)) {
36
+ this.widths.delete(path);
37
+ }
38
+ }
39
+ for (const column of this.columns) {
40
+ column.width = this.widths.get(column.name);
41
+ }
42
+ return true;
43
+ }
44
+ serialize() {
45
+ return this.widths.size ? Object.fromEntries(this.widths) : undefined;
46
+ }
47
+ unserialize(data) {
48
+ this.widths = new Map((data && (typeof data === 'object') && !Array.isArray(data))
49
+ ? Object.entries(data).filter((entry) => isColumnWidth(entry[1]))
50
+ : []);
51
+ }
52
+ }
53
+ exports.ColumnWidths = ColumnWidths;
54
+ //# sourceMappingURL=column-widths.js.map
@@ -97,7 +97,7 @@ function datePeriod(value, format, now) {
97
97
  };
98
98
  }
99
99
  function dateSearch(value, operator = '=', now = new Date(), format = (0, translate_1.tr)('dd/MM/yyyy', { ucFirst: false })) {
100
- value = value.trim();
100
+ value = value.trim().replaceAll('_', '?');
101
101
  if (value === '?') {
102
102
  return ['!', '!=', '<>'].includes(operator)
103
103
  ? (0, sql_functions_2.equal)('0000-00-00')
package/cjs/filter.d.ts CHANGED
@@ -2,9 +2,9 @@ import { Type } from '@itrocks/class-type';
2
2
  import { Request } from '@itrocks/request-response';
3
3
  import { Option } from '@itrocks/storage';
4
4
  import { SearchType } from '@itrocks/storage';
5
+ import { SearchExpression } from './front/search-expression';
5
6
  import { Columns } from './columns';
6
7
  import { Parameter } from './parameter';
7
- import { SearchExpression } from './search-expression';
8
8
  type Search = {
9
9
  [property: string]: string;
10
10
  };
package/cjs/filter.js CHANGED
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Filter = void 0;
4
4
  const class_view_1 = require("@itrocks/class-view");
5
+ const property_type_1 = require("@itrocks/property-type");
6
+ const property_type_2 = require("@itrocks/property-type");
5
7
  const reflect_path_1 = require("@itrocks/reflect-path");
6
8
  const sql_functions_1 = require("@itrocks/sql-functions");
7
9
  const sql_functions_2 = require("@itrocks/sql-functions");
@@ -16,68 +18,98 @@ const sql_functions_10 = require("@itrocks/sql-functions");
16
18
  const sql_functions_11 = require("@itrocks/sql-functions");
17
19
  const sql_functions_12 = require("@itrocks/sql-functions");
18
20
  const sql_functions_13 = require("@itrocks/sql-functions");
21
+ const sql_functions_14 = require("@itrocks/sql-functions");
22
+ const sql_functions_15 = require("@itrocks/sql-functions");
19
23
  const translate_1 = require("@itrocks/translate");
24
+ const search_expression_1 = require("./front/search-expression");
25
+ const search_expression_2 = require("./front/search-expression");
20
26
  const date_search_1 = require("./date-search");
21
27
  const parameter_1 = require("./parameter");
22
- const search_expression_1 = require("./search-expression");
23
28
  const operators = {
24
- '!': sql_functions_11.notEqual,
25
- '!=': sql_functions_11.notEqual,
26
- '<': sql_functions_8.less,
27
- '<=': sql_functions_9.lessOrEqual,
28
- '<>': sql_functions_11.notEqual,
29
+ '!': sql_functions_13.notEqual,
30
+ '!=': sql_functions_13.notEqual,
31
+ '<': sql_functions_10.less,
32
+ '<=': sql_functions_11.lessOrEqual,
33
+ '<>': sql_functions_13.notEqual,
29
34
  '=': sql_functions_5.equal,
30
35
  '>': sql_functions_6.greater,
31
- '>=': sql_functions_7.greaterOrEqual
36
+ '>=': sql_functions_7.greaterOrEqual,
37
+ '≠': sql_functions_13.notEqual
32
38
  };
33
- function explicitSearchValue(propertyType, operator, value) {
34
- if (propertyType === Date)
35
- return (0, date_search_1.dateSearch)(value, operator === ':' ? '=' : operator);
36
- if (operator !== ':')
37
- return operators[operator](value);
38
- if (propertyType !== String)
39
+ function comparisonOperand(propertyType, value) {
40
+ if (propertyType !== Number || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim())) {
39
41
  return value;
40
- return (0, sql_functions_10.like)(value.replace(/[\\%_]/g, '\\$&') + '%');
42
+ }
43
+ const number = Number(value);
44
+ return Number.isFinite(number) && (!Number.isInteger(number) || Number.isSafeInteger(number)) ? number : value;
45
+ }
46
+ function criterionValue(propertyType, value, operator) {
47
+ if (propertyType === Date) {
48
+ const comparison = operator === ':' ? '=' : operator === '≠' ? '!=' : operator;
49
+ const trimmed = value.trim();
50
+ if (trimmed && (comparison === '!=' || comparison === '<>') && (0, translate_1.trReverse)(trimmed.toLowerCase()) === 'empty') {
51
+ return (0, date_search_1.dateSearch)('?');
52
+ }
53
+ return (0, date_search_1.dateSearch)(value, comparison);
54
+ }
55
+ const compare = operator && operator !== ':' ? operators[operator] : undefined;
56
+ if ((!compare || operator === '!') && /[*?%_]/.test(value)) {
57
+ const match = operator === '!' ? sql_functions_14.notLike : sql_functions_12.like;
58
+ return match(value.replaceAll('*', '%').replaceAll('?', '_'));
59
+ }
60
+ if (operator === '!' && propertyType === String && value)
61
+ return (0, sql_functions_14.notLike)(value + '%');
62
+ if (compare)
63
+ return compare(comparisonOperand(propertyType, value));
64
+ const separator = operator === ':' ? -1 : value.indexOf('-');
65
+ if (separator >= 0) {
66
+ const lower = value.slice(0, separator).trim();
67
+ const upper = value.slice(separator + 1).trim();
68
+ if (lower && upper)
69
+ return (0, sql_functions_4.between)(comparisonOperand(propertyType, lower), comparisonOperand(propertyType, upper));
70
+ if (lower)
71
+ return (0, sql_functions_7.greaterOrEqual)(comparisonOperand(propertyType, lower));
72
+ if (upper)
73
+ return (0, sql_functions_11.lessOrEqual)(comparisonOperand(propertyType, upper));
74
+ return propertyType === Number ? (0, sql_functions_15.or)() : (0, sql_functions_5.equal)('-');
75
+ }
76
+ if (propertyType !== String)
77
+ return comparisonOperand(propertyType, value);
78
+ if (!value)
79
+ return (0, sql_functions_5.equal)('');
80
+ return (0, sql_functions_12.like)((operator === ':' ? value.replaceAll('\\', '\\\\') : value) + '%');
81
+ }
82
+ function emptyCriterion(value, date = false) {
83
+ const alias = value.trim().match(date ? /^(!=|<>|[!≠])?\s*(.+)$/s : /^(!)?\s*(.+)$/s);
84
+ if (alias && (0, translate_1.trReverse)(alias[2].toLowerCase()) === 'empty')
85
+ return alias[1] ? 'present' : 'empty';
86
+ }
87
+ function scalarType(type) {
88
+ if (type instanceof property_type_2.UnionType) {
89
+ const members = type.types.filter(member => !(0, property_type_1.isLiteral)(member, null) && !(0, property_type_1.isLiteral)(member, undefined));
90
+ if (members.length === 1)
91
+ return members[0].type;
92
+ }
93
+ return type.type;
41
94
  }
42
95
  function searchValue(propertyType, expression) {
43
96
  if (!('value' in expression)) {
44
- const combine = (expression.operator === 'AND') ? sql_functions_3.and : sql_functions_13.or;
45
- return combine(...expression.operands.map(operand => searchValue(propertyType, operand) ?? (0, sql_functions_13.or)()));
97
+ const combine = (expression.operator === 'AND') ? sql_functions_3.and : sql_functions_15.or;
98
+ return combine(...expression.operands.map(operand => searchValue(propertyType, operand) ?? (0, sql_functions_15.or)()));
46
99
  }
47
100
  if (expression.comparison !== undefined) {
48
- return explicitSearchValue(propertyType, expression.comparison, expression.value);
101
+ return criterionValue(propertyType, expression.value, expression.comparison);
49
102
  }
50
103
  let value = expression.value;
51
- const alias = value.trim().match(/^(!=|<>|!)?\s*(.+)$/s);
52
- if (alias && ((0, translate_1.trReverse)(alias[2].toLowerCase()) === 'empty')) {
53
- value = (alias[1] ? '' : '!') + ((propertyType === Date) ? '?' : '?*');
104
+ const empty = emptyCriterion(value, propertyType === Date);
105
+ if (empty) {
106
+ if (propertyType === Number)
107
+ return empty === 'empty' ? (0, sql_functions_9.isNull)() : (0, sql_functions_8.isNotNull)();
108
+ value = (empty === 'present' ? '' : '!') + ((propertyType === Date) ? '?' : '?*');
54
109
  }
55
- const comparison = value.match(/^(>=|<=|<>|!=|>|<|=|!)(.*)$/s);
56
- const operator = comparison ? operators[comparison[1]] : undefined;
110
+ const comparison = value.match(search_expression_1.columnComparison);
57
111
  const operand = comparison ? comparison[2].trim() : value;
58
- if (propertyType === Date) {
59
- return (0, date_search_1.dateSearch)(operand, comparison?.[1]);
60
- }
61
- if (/[*?]/.test(operand) && (!operator || operator === sql_functions_11.notEqual)) {
62
- const compare = operator ? sql_functions_12.notLike : sql_functions_10.like;
63
- return compare(operand.replaceAll('*', '%').replaceAll('?', '_'));
64
- }
65
- if (operator) {
66
- return operator(operand);
67
- }
68
- const separator = value.indexOf('-');
69
- if (separator < 0) {
70
- const text = (propertyType === String);
71
- return (text ? (0, sql_functions_10.like)(value + '%') : value);
72
- }
73
- const lower = value.slice(0, separator).trim();
74
- const upper = value.slice(separator + 1).trim();
75
- if (lower && upper)
76
- return (0, sql_functions_4.between)(lower, upper);
77
- if (lower)
78
- return (0, sql_functions_7.greaterOrEqual)(lower);
79
- if (upper)
80
- return (0, sql_functions_9.lessOrEqual)(upper);
112
+ return criterionValue(propertyType, operand, comparison?.[1]);
81
113
  }
82
114
  class Filter extends parameter_1.Parameter {
83
115
  columns;
@@ -89,29 +121,32 @@ class Filter extends parameter_1.Parameter {
89
121
  columnCondition(type, property, value) {
90
122
  let expression;
91
123
  try {
92
- expression = (0, search_expression_1.searchExpression)(value);
124
+ expression = (0, search_expression_2.searchExpression)(value);
93
125
  }
94
126
  catch (error) {
95
127
  if (!(error instanceof SyntaxError))
96
128
  throw error;
97
- return { [property]: (0, sql_functions_13.or)() };
129
+ return { [property]: (0, sql_functions_15.or)() };
98
130
  }
99
- const resolved = (0, reflect_path_1.resolvePropertyPath)(type, property);
100
- if (resolved.target)
101
- return this.condition(type, property, expression);
102
- const criterion = searchValue(resolved.property.type.type, expression);
103
- return (criterion === undefined) ? {} : { [property]: criterion };
131
+ return this.condition(type, property, expression);
104
132
  }
105
133
  condition(type, property, expression, ancestors = []) {
106
134
  const resolved = (0, reflect_path_1.resolvePropertyPath)(type, property);
107
135
  if (!resolved.target) {
108
- const value = searchValue(resolved.property.type.type, expression);
109
- return { [property]: value ?? (0, sql_functions_13.or)() };
136
+ const value = searchValue(scalarType(resolved.property.type), expression);
137
+ if (value === undefined && !ancestors.length)
138
+ return {};
139
+ return { [property]: value ?? (0, sql_functions_15.or)() };
110
140
  }
111
141
  if (!('value' in expression)) {
112
142
  const operator = (expression.operator === 'AND') ? sql_functions_1.AND : sql_functions_2.OR;
113
143
  return { [operator]: expression.operands.map(operand => this.condition(type, property, operand, ancestors)) };
114
144
  }
145
+ if (resolved.targetMultiplicity === 'one' && expression.comparison === undefined) {
146
+ const empty = emptyCriterion(expression.value);
147
+ if (empty)
148
+ return { [property]: empty === 'empty' ? (0, sql_functions_9.isNull)() : (0, sql_functions_8.isNotNull)() };
149
+ }
115
150
  if (ancestors.includes(resolved.target))
116
151
  throw new Error(`Cyclic search representation: ${property}`);
117
152
  const branch = [...ancestors, resolved.target];
@@ -0,0 +1,10 @@
1
+ export type SearchComparison = ':' | '=' | '!' | '!=' | '<' | '<=' | '>' | '>=';
2
+ export type SearchExpression = {
3
+ comparison?: SearchComparison;
4
+ value: string;
5
+ } | {
6
+ operator: 'AND' | 'OR';
7
+ operands: SearchExpression[];
8
+ };
9
+ export declare const columnComparison: RegExp;
10
+ export declare function searchExpression(input: string): SearchExpression;
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.columnComparison = void 0;
4
+ exports.searchExpression = searchExpression;
5
+ exports.columnComparison = /^(>=|<=|<>|!=|[><=!≠])(.*)$/s;
6
+ function searchExpression(input) {
7
+ // Preserve ordinary input exactly, including spaces used by existing scalar criteria.
8
+ if (!/[,|&+()"\\]/.test(input))
9
+ return { value: input };
10
+ return new SearchParser(input).parse();
11
+ }
12
+ class SearchParser {
13
+ input;
14
+ position = 0;
15
+ constructor(input) {
16
+ this.input = input;
17
+ }
18
+ and() {
19
+ const operands = [this.primary()];
20
+ while (this.take('&+'))
21
+ operands.push(this.primary());
22
+ return (operands.length === 1) ? operands[0] : { operator: 'AND', operands };
23
+ }
24
+ fail(message) {
25
+ throw new SyntaxError(`${message} at position ${this.position + 1}`);
26
+ }
27
+ or() {
28
+ const operands = [this.and()];
29
+ while (this.take(',|'))
30
+ operands.push(this.and());
31
+ return (operands.length === 1) ? operands[0] : { operator: 'OR', operands };
32
+ }
33
+ parse() {
34
+ const expression = this.or();
35
+ this.space();
36
+ if (this.position !== this.input.length)
37
+ this.fail('Unexpected character');
38
+ return expression;
39
+ }
40
+ primary() {
41
+ if (this.take('(')) {
42
+ const expression = this.or();
43
+ if (!this.take(')')) {
44
+ this.fail('Missing closing parenthesis');
45
+ }
46
+ return expression;
47
+ }
48
+ let value = '';
49
+ let length = 0;
50
+ let quoted = false;
51
+ let seen = false;
52
+ while (this.position < this.input.length) {
53
+ const character = this.input[this.position];
54
+ if (!quoted && ',|&+()'.includes(character))
55
+ break;
56
+ this.position++;
57
+ if ((character === '\\')
58
+ && (this.position < this.input.length)
59
+ && ',|&+()"\\'.includes(this.input[this.position])) {
60
+ value += this.input[this.position++];
61
+ length = value.length;
62
+ seen = true;
63
+ }
64
+ else if (character === '"') {
65
+ quoted = !quoted;
66
+ seen = true;
67
+ }
68
+ else {
69
+ value += character;
70
+ if (quoted || character.trim())
71
+ length = value.length;
72
+ seen ||= !!character.trim();
73
+ }
74
+ }
75
+ if (quoted)
76
+ this.fail('Unclosed quote');
77
+ if (!seen)
78
+ this.fail('Missing criterion');
79
+ return { value: value.slice(0, length) };
80
+ }
81
+ space() {
82
+ while ((this.position < this.input.length) && /\s/.test(this.input[this.position])) {
83
+ this.position++;
84
+ }
85
+ }
86
+ take(characters) {
87
+ this.space();
88
+ if ((this.position === this.input.length) || !characters.includes(this.input[this.position])) {
89
+ return false;
90
+ }
91
+ this.position++;
92
+ return true;
93
+ }
94
+ }
95
+ //# sourceMappingURL=search-expression.js.map
package/cjs/list.d.ts CHANGED
@@ -2,6 +2,7 @@ import { Action } from '@itrocks/action';
2
2
  import { Request } from '@itrocks/action-request';
3
3
  import { SearchType } from '@itrocks/storage';
4
4
  import { ListView } from './access';
5
+ import { ColumnWidths } from './column-widths';
5
6
  import { Columns } from './columns';
6
7
  import { Feed } from './feed';
7
8
  import { Filter } from './filter';
@@ -10,9 +11,11 @@ export { listAccess, listDependsOn } from './access';
10
11
  export type { ListAccess, ListDependencies, ListView } from './access';
11
12
  export declare class List<T extends object = object> extends Action<T> {
12
13
  columns: Columns<object>;
14
+ columnWidths: ColumnWidths<object>;
13
15
  feed: Feed;
14
16
  filter: Filter<object>;
15
17
  sort: Sort<object>;
18
+ protected canResizeColumns(_request: Request<T>): boolean;
16
19
  protected filterBar(request: Request<T>): ListView;
17
20
  html(request: Request<T>, scope?: SearchType<T>): Promise<import("@itrocks/request-response").Response>;
18
21
  json(request: Request<T>, scope?: SearchType<T>): Promise<import("@itrocks/core-responses").JsonResponse>;
package/cjs/list.html CHANGED
@@ -2,6 +2,7 @@
2
2
  <html lang="en">
3
3
  <head>
4
4
  <link href="../../action-bar/action.css" rel="stylesheet">
5
+ <link href="../../table/column-resize.css" rel="stylesheet">
5
6
  <link href="../../ux-core/css/app.css" rel="stylesheet">
6
7
  <link href="../../ux-core/css/article.css" rel="stylesheet">
7
8
  <link href="../list.css" rel="stylesheet">
@@ -37,7 +38,7 @@
37
38
  <form action="app://(type.@route)/list" autocomplete="off" data-focus-column="{focusColumn}"
38
39
  method="post" target="main">
39
40
  <!--filterBar--><!--formFields-->{{template}}<!--end--><!--end-->
40
- <table class="objects" data-link="{type.@route}">
41
+ <table class="objects" data-column-resize="{?canResize}" data-link="{type.@route}">
41
42
  <thead>
42
43
  <tr class="properties">
43
44
  <th class="select" data-freeze><!--selection-->{{template}}<!--end-->
@@ -45,7 +46,7 @@
45
46
  </th>
46
47
  <!--columns-->
47
48
  <th data-property="{name}" data-reverse="{?reverse}" data-sort="{?sort}"
48
- data-sortable="{sortable}">{label}
49
+ data-sortable="{sortable}" data-column-width="{?width}">{label}
49
50
  <input aria-label="Filter {label}" data-property-filter="{name}" name="search.{field}" value="{escapedSearch}">
50
51
  </th>
51
52
  <!--end-->
package/cjs/list.js CHANGED
@@ -46,6 +46,7 @@ const storage_3 = require("@itrocks/storage");
46
46
  const access_1 = require("./access");
47
47
  const access_2 = require("./access");
48
48
  const access_3 = require("./access");
49
+ const column_widths_1 = require("./column-widths");
49
50
  const columns_1 = require("./columns");
50
51
  const columns_2 = require("./columns");
51
52
  const feed_1 = require("./feed");
@@ -80,9 +81,13 @@ let List = (() => {
80
81
  __runInitializers(_classThis, _classExtraInitializers);
81
82
  }
82
83
  columns = new columns_1.Columns;
84
+ columnWidths = new column_widths_1.ColumnWidths(this.columns);
83
85
  feed = new feed_1.Feed;
84
86
  filter = new filter_1.Filter(this.columns);
85
87
  sort = new sort_1.Sort(this.columns);
88
+ canResizeColumns(_request) {
89
+ return true;
90
+ }
86
91
  filterBar(request) {
87
92
  return (0, filter_summary_2.filterSummary)(this.filter.search, (0, filter_summary_1.filterAliases)(request.type, this.columns));
88
93
  }
@@ -99,6 +104,7 @@ let List = (() => {
99
104
  const prepared = await (0, session_state_1.prepareListSession)(request);
100
105
  if (prepared)
101
106
  return prepared;
107
+ this.columnWidths.unserialize(undefined);
102
108
  (0, persist_1.load)(this, request.request, type);
103
109
  columns.getParams(request.request, type);
104
110
  const access = await (0, access_1.listAccess)(request);
@@ -107,8 +113,17 @@ let List = (() => {
107
113
  for (const field of column.fields ?? [])
108
114
  await access.authorise(`${column.name}.${field}`);
109
115
  }
116
+ const canResize = this.canResizeColumns(request);
117
+ const resizing = ('resizeColumn' in request.request.data) || ('columnWidth' in request.request.data);
118
+ if (resizing && (request.request.method !== 'POST'))
119
+ return this.htmlResponse('', 405);
120
+ if (resizing && !canResize)
121
+ return this.htmlResponse('', 403);
122
+ if (!this.columnWidths.getParams(request.request))
123
+ return this.htmlResponse('', 400);
110
124
  const batch = typeof request.request.data.loadColumns === 'string';
111
- if (request.request.data.columns !== undefined && typeof request.request.data.column !== 'string' && !batch) {
125
+ if (resizing || (request.request.data.columns !== undefined && typeof request.request.data.column !== 'string'
126
+ && !batch)) {
112
127
  (0, persist_2.save)(this, request.request, type);
113
128
  return this.htmlResponse('', 204);
114
129
  }
@@ -204,7 +219,7 @@ let List = (() => {
204
219
  const focus = request.request.method === 'POST' ? request.request.data.focusListColumn : undefined;
205
220
  const focusColumn = [...columns].find(column => column.field === focus)?.field ?? '';
206
221
  return this.htmlTemplateResponse({
207
- columns, count, filterBar: this.filterBar(request), focusColumn, generalActions, objects,
222
+ canResize, columns, count, filterBar: this.filterBar(request), focusColumn, generalActions, objects,
208
223
  root: access.root, search: filter.search,
209
224
  selectionActions, selectorBootstrap, selectorKey: (0, selector_state_2.selectorStateKey)(request), type,
210
225
  selection: selectionActions.length ? await selection?.view(request, activeSearch, count) : undefined,
@@ -28,6 +28,7 @@ export declare class ListColumn {
28
28
  reverse: boolean;
29
29
  search: string;
30
30
  sort?: number;
31
+ width?: number;
31
32
  constructor(root: Type, name: string);
32
33
  get escapedSearch(): string;
33
34
  output(cell: ProjectionCell): Promise<string>;
package/cjs/projection.js CHANGED
@@ -57,6 +57,7 @@ class ListColumn {
57
57
  reverse = false;
58
58
  search = '';
59
59
  sort;
60
+ width;
60
61
  constructor(root, name) {
61
62
  this.root = root;
62
63
  this.name = name;
@@ -9,6 +9,7 @@ export type ListQueryState = {
9
9
  };
10
10
  export type ListState = {
11
11
  columns?: string[];
12
+ columnWidths?: Record<string, number>;
12
13
  filter?: Record<string, string>;
13
14
  listQuery?: ListQueryState;
14
15
  sort?: [string, boolean][];
@@ -7,6 +7,7 @@ exports.prepareListSession = prepareListSession;
7
7
  exports.listSessionChanged = listSessionChanged;
8
8
  exports.comparableListState = comparableListState;
9
9
  const route_1 = require("@itrocks/route");
10
+ const column_widths_1 = require("./column-widths");
10
11
  const dependencies = {
11
12
  changed: () => { },
12
13
  prepare: async () => { }
@@ -18,6 +19,7 @@ function listState(request, type) {
18
19
  const state = request.session.list?.[(0, route_1.routeOf)(type)] ?? {};
19
20
  return structuredClone({
20
21
  columns: state.columns,
22
+ ...(state.columnWidths && Object.keys(state.columnWidths).length ? { columnWidths: state.columnWidths } : {}),
21
23
  filter: state.filter,
22
24
  ...(state.listQuery ? { listQuery: state.listQuery } : {}),
23
25
  sort: state.sort
@@ -37,6 +39,9 @@ function listSessionChanged(request, type) {
37
39
  function comparableListState(state) {
38
40
  return JSON.stringify({
39
41
  columns: state.columns,
42
+ columnWidths: Object.entries(state.columnWidths ?? {})
43
+ .filter(([path, width]) => (0, column_widths_1.isColumnWidth)(width) && (state.columns?.includes(path) ?? true))
44
+ .sort(([left], [right]) => left.localeCompare(right)),
40
45
  filter: Object.entries(state.filter ?? {})
41
46
  .filter(([, value]) => value !== '')
42
47
  .sort(([left], [right]) => left.localeCompare(right)),
package/package.json CHANGED
@@ -15,6 +15,7 @@
15
15
  "@itrocks/decorator": "latest",
16
16
  "@itrocks/list-properties": "latest",
17
17
  "@itrocks/property-select": "latest",
18
+ "@itrocks/property-type": "latest",
18
19
  "@itrocks/property-view": "latest",
19
20
  "@itrocks/reflect": "latest",
20
21
  "@itrocks/reflect-path": "latest",
@@ -50,6 +51,11 @@
50
51
  "./projection": "./cjs/projection.js",
51
52
  "./property-select.js": "./property-select.js",
52
53
  "./search": "./cjs/search.js",
54
+ "./search-expression.js": {
55
+ "types": "./cjs/front/search-expression.d.ts",
56
+ "require": "./cjs/front/search-expression.js",
57
+ "default": "./search-expression.js"
58
+ },
53
59
  "./selector-state": "./cjs/selector-state.js",
54
60
  "./selector-state.js": "./selector-state.js",
55
61
  "./session-state": "./cjs/session-state.js"
@@ -103,5 +109,5 @@
103
109
  "build:front": "tsc -p src/front/tsconfig.json",
104
110
  "test": "npm run build:cjs && node --test \"test/**/*.test.mjs\""
105
111
  },
106
- "version": "0.28.3"
112
+ "version": "0.30.0"
107
113
  }
@@ -0,0 +1,10 @@
1
+ export type SearchComparison = ':' | '=' | '!' | '!=' | '<' | '<=' | '>' | '>=';
2
+ export type SearchExpression = {
3
+ comparison?: SearchComparison;
4
+ value: string;
5
+ } | {
6
+ operator: 'AND' | 'OR';
7
+ operands: SearchExpression[];
8
+ };
9
+ export declare const columnComparison: RegExp;
10
+ export declare function searchExpression(input: string): SearchExpression;
@@ -0,0 +1,90 @@
1
+ export const columnComparison = /^(>=|<=|<>|!=|[><=!≠])(.*)$/s;
2
+ export function searchExpression(input) {
3
+ // Preserve ordinary input exactly, including spaces used by existing scalar criteria.
4
+ if (!/[,|&+()"\\]/.test(input))
5
+ return { value: input };
6
+ return new SearchParser(input).parse();
7
+ }
8
+ class SearchParser {
9
+ input;
10
+ position = 0;
11
+ constructor(input) {
12
+ this.input = input;
13
+ }
14
+ and() {
15
+ const operands = [this.primary()];
16
+ while (this.take('&+'))
17
+ operands.push(this.primary());
18
+ return (operands.length === 1) ? operands[0] : { operator: 'AND', operands };
19
+ }
20
+ fail(message) {
21
+ throw new SyntaxError(`${message} at position ${this.position + 1}`);
22
+ }
23
+ or() {
24
+ const operands = [this.and()];
25
+ while (this.take(',|'))
26
+ operands.push(this.and());
27
+ return (operands.length === 1) ? operands[0] : { operator: 'OR', operands };
28
+ }
29
+ parse() {
30
+ const expression = this.or();
31
+ this.space();
32
+ if (this.position !== this.input.length)
33
+ this.fail('Unexpected character');
34
+ return expression;
35
+ }
36
+ primary() {
37
+ if (this.take('(')) {
38
+ const expression = this.or();
39
+ if (!this.take(')')) {
40
+ this.fail('Missing closing parenthesis');
41
+ }
42
+ return expression;
43
+ }
44
+ let value = '';
45
+ let length = 0;
46
+ let quoted = false;
47
+ let seen = false;
48
+ while (this.position < this.input.length) {
49
+ const character = this.input[this.position];
50
+ if (!quoted && ',|&+()'.includes(character))
51
+ break;
52
+ this.position++;
53
+ if ((character === '\\')
54
+ && (this.position < this.input.length)
55
+ && ',|&+()"\\'.includes(this.input[this.position])) {
56
+ value += this.input[this.position++];
57
+ length = value.length;
58
+ seen = true;
59
+ }
60
+ else if (character === '"') {
61
+ quoted = !quoted;
62
+ seen = true;
63
+ }
64
+ else {
65
+ value += character;
66
+ if (quoted || character.trim())
67
+ length = value.length;
68
+ seen ||= !!character.trim();
69
+ }
70
+ }
71
+ if (quoted)
72
+ this.fail('Unclosed quote');
73
+ if (!seen)
74
+ this.fail('Missing criterion');
75
+ return { value: value.slice(0, length) };
76
+ }
77
+ space() {
78
+ while ((this.position < this.input.length) && /\s/.test(this.input[this.position])) {
79
+ this.position++;
80
+ }
81
+ }
82
+ take(characters) {
83
+ this.space();
84
+ if ((this.position === this.input.length) || !characters.includes(this.input[this.position])) {
85
+ return false;
86
+ }
87
+ this.position++;
88
+ return true;
89
+ }
90
+ }