@sevtech/kit 21.1.0 → 21.2.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.
@@ -8,7 +8,7 @@ import { NgTemplateOutlet } from '@angular/common';
8
8
  import { SlotOutletDirective, HighlightPipe } from '@sevtech/kit/ui';
9
9
  import { cssDimensionAttribute, htmlBooleanAttribute, defineKitFeature, resolveConfigProviders, collectFeatureProviders } from '@sevtech/kit/ng-misc';
10
10
  import { IS_MOBILE_BREAKPOINT } from '@sevtech/kit/browser';
11
- import { HttpClient } from '@angular/common/http';
11
+ import { HttpErrorResponse, HttpClient } from '@angular/common/http';
12
12
  import * as i1 from '@angular/cdk/overlay';
13
13
  import { ScrollStrategyOptions, OverlayContainer, OverlayModule } from '@angular/cdk/overlay';
14
14
 
@@ -107,6 +107,7 @@ const ICONS = createToken('[YODA]: глифы иконок', DEFAULT_ICONS);
107
107
  const MESSAGES = createToken('[YODA]: тексты интерфейса', DEFAULT_MESSAGES);
108
108
  const CONFIG = createToken('[YODA]: конфигурация полей', DEFAULT_CONFIG);
109
109
  const Z_INDEX = createToken('[YODA]: расчёт z-index', (base) => base);
110
+ const LABEL_FORMATTERS = createToken('[YODA]: сборка подписей опций', {});
110
111
 
111
112
  var RequestType;
112
113
  (function (RequestType) {
@@ -115,16 +116,55 @@ var RequestType;
115
116
  RequestType[RequestType["Create"] = 2] = "Create";
116
117
  })(RequestType || (RequestType = {}));
117
118
 
119
+ class YodaError extends Error {
120
+ constructor(query, causeOrType) {
121
+ const reason = computeReason(causeOrType);
122
+ super(computeMessage(reason, query, causeOrType), {
123
+ cause: reason === 'request' ? causeOrType : undefined,
124
+ });
125
+ this.name = 'YodaError';
126
+ this.query = query;
127
+ this.reason = reason;
128
+ }
129
+ getPayload() {
130
+ return {
131
+ query: this.query,
132
+ reason: this.reason,
133
+ };
134
+ }
135
+ }
136
+ function computeReason(cause) {
137
+ if (RequestType.Create === cause)
138
+ return 'create';
139
+ if (RequestType.Get === cause)
140
+ return 'unresolve';
141
+ return cause instanceof Error || cause instanceof HttpErrorResponse ? 'request' : 'unknown';
142
+ }
143
+ function computeMessage(reason, query, cause) {
144
+ switch (reason) {
145
+ case 'create':
146
+ return `[YODA]: creating "${query}" returned no option`;
147
+ case 'unresolve':
148
+ return `[YODA]: form value "${query}" did not resolve`;
149
+ default: {
150
+ return cause instanceof Error || cause instanceof HttpErrorResponse
151
+ ? `[YODA]: request "${query}" failed — ${cause.message}`
152
+ : '[YODA]: unknown error';
153
+ }
154
+ }
155
+ }
156
+
118
157
  class ApiService {
119
158
  constructor() {
120
159
  this.config = inject(CONFIG);
160
+ this.formatters = inject(LABEL_FORMATTERS);
121
161
  this.httpClient = inject(HttpClient);
122
162
  }
123
163
  request(data) {
124
164
  const { url, params } = this.resolveEndpoint(data);
125
165
  return this.httpClient
126
166
  .get(url, { params })
127
- .pipe(map((rows) => this.parseResponse(rows, data.transform)));
167
+ .pipe(map((rows) => this.parseResponse(rows, data)));
128
168
  }
129
169
  resolveEndpoint(data) {
130
170
  const params = toRequestParams(data);
@@ -139,12 +179,13 @@ class ApiService {
139
179
  }
140
180
  throw new Error('[YODA]: provide either `url` or both `action` and `repository`');
141
181
  }
142
- parseResponse(rows, transform) {
182
+ parseResponse(rows, data) {
143
183
  if (!isArray(rows))
144
184
  throw new Error('[YODA]: expected array in response');
145
- if (isFunction(transform))
146
- return flattenOptions(transform(rows));
147
- return rows.map(parseResponseRaw);
185
+ if (isFunction(data.transform))
186
+ return flattenOptions(data.transform(rows));
187
+ const formatLabel = resolveFormatter(data, this.formatters);
188
+ return rows.map((row) => parseResponseRaw(row, formatLabel));
148
189
  }
149
190
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: ApiService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
150
191
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.18", ngImport: i0, type: ApiService, providedIn: 'root' }); }
@@ -155,6 +196,14 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.18", ngImpo
155
196
  providedIn: 'root',
156
197
  }]
157
198
  }] });
199
+ function resolveFormatter({ action, repository }, formatters) {
200
+ if (!isString(action))
201
+ return undefined;
202
+ if (isString(repository)) {
203
+ return formatters[`${repository}:${action}`] ?? formatters[action];
204
+ }
205
+ return formatters[action];
206
+ }
158
207
  function flattenOptions(options) {
159
208
  return options.flatMap((option, index) => {
160
209
  if (!isGroupOption(option))
@@ -167,8 +216,14 @@ function flattenOptions(options) {
167
216
  function isGroupOption(option) {
168
217
  return 'items' in option && isArray(option.items);
169
218
  }
170
- function parseResponseRaw([value, label, ...payload]) {
171
- return { kind: 'option', value, label, payload };
219
+ function parseResponseRaw(row, formatLabel) {
220
+ const [value, label, ...payload] = row;
221
+ return {
222
+ value,
223
+ payload,
224
+ kind: 'option',
225
+ label: isFunction(formatLabel) ? formatLabel(...row) : label,
226
+ };
172
227
  }
173
228
  function toRequestParams({ action, repository, type, query, parent }) {
174
229
  return { action, repository, type, query, parent };
@@ -281,7 +336,11 @@ class StateService {
281
336
  this.stateSource.set({ status: 'loading' });
282
337
  return this.api.request(request);
283
338
  }).pipe(tap((options) => this.apply(request, options, fromSearch)), catchError((error) => {
284
- this.stateSource.set({ status: 'error', request, error });
339
+ this.stateSource.set({
340
+ request,
341
+ status: 'error',
342
+ error: error instanceof YodaError ? error : new YodaError(request.query, error),
343
+ });
285
344
  return EMPTY;
286
345
  }));
287
346
  }
@@ -291,8 +350,9 @@ class StateService {
291
350
  this.optionsSource.set(options);
292
351
  }
293
352
  applySelection(request, [option]) {
294
- if (isNil(option))
295
- return;
353
+ if (isNil(option)) {
354
+ throw new YodaError(request.query, request.type);
355
+ }
296
356
  if (request.type === RequestType.Create) {
297
357
  this.optionsSource.update((current) => [option, ...(current ?? [])]);
298
358
  this.createdSource.set(option);
@@ -1061,7 +1121,7 @@ class Yoda extends BaseDirective {
1061
1121
  effect(() => this.emitOptionCreated(this.state.created$$()));
1062
1122
  effect(() => this.syncSelection(this.state.selected$$()));
1063
1123
  effect(() => this.autoSelectSingle(this.state.options$$()));
1064
- effect(() => this.syncRequestError(this.hasRequestError$$()));
1124
+ effect(() => this.syncRequestError());
1065
1125
  effect(() => this.emitRequestError());
1066
1126
  }
1067
1127
  writeValue(value) {
@@ -1070,6 +1130,8 @@ class Yoda extends BaseDirective {
1070
1130
  this.typed$$.set('');
1071
1131
  return this.state.clear();
1072
1132
  }
1133
+ /* Стор обязан совпасть с формой до ответа и эффект примет пустоту за очистку */
1134
+ this.state.select({ kind: 'option', value, label: '' });
1073
1135
  this.state.resolve(value, this.requestOptions$$());
1074
1136
  }
1075
1137
  registerOnChange(onChange) {
@@ -1190,13 +1252,14 @@ class Yoda extends BaseDirective {
1190
1252
  this.loadedParent = parent;
1191
1253
  this.load(isDefined(parent) ? String(parent) : this.preloadQuery(), this.preloadType());
1192
1254
  }
1193
- syncRequestError(hasError) {
1255
+ syncRequestError() {
1194
1256
  const control = this.control$$();
1195
1257
  if (isNil(control))
1196
1258
  return;
1259
+ const state = this.state.requestState$$();
1197
1260
  const errors = { ...(control.errors ?? {}) };
1198
- if (hasError) {
1199
- errors[REQUEST_ERROR] = true;
1261
+ if (state.status === 'error') {
1262
+ errors[REQUEST_ERROR] = state.error.getPayload();
1200
1263
  }
1201
1264
  else {
1202
1265
  delete errors[REQUEST_ERROR];
@@ -1285,6 +1348,11 @@ const withZIndex = defineKitFeature(2 /* FeatureKind.ZIndex */, (resolver) => ({
1285
1348
  provide: Z_INDEX,
1286
1349
  useValue: resolver,
1287
1350
  }));
1351
+ /** Сборка подписи опции по экшену или репозиторию и экшену в формате (`repository:action`): колонки приходят как есть */
1352
+ const withLabelFormatters = defineKitFeature(3 /* FeatureKind.LabelFormatters */, (formatters) => ({
1353
+ provide: LABEL_FORMATTERS,
1354
+ useFactory: () => resolveMaybeFn(formatters),
1355
+ }));
1288
1356
  function provideYoda(config, ...features) {
1289
1357
  const providers = resolveConfigProviders(config, (data) => ({
1290
1358
  provide: CONFIG,
@@ -1313,5 +1381,5 @@ function mergeMessages(messages) {
1313
1381
  * Generated bundle index. Do not edit.
1314
1382
  */
1315
1383
 
1316
- export { Yoda, YodaChain, RequestType as YodaRequestType, provideYoda, withIcons, withMessages, withZIndex };
1384
+ export { Yoda, YodaChain, YodaError, RequestType as YodaRequestType, provideYoda, withIcons, withLabelFormatters, withMessages, withZIndex };
1317
1385
  //# sourceMappingURL=ui-yoda.mjs.map