@wawjs/ngx-bos 22.0.5 → 22.0.7

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 (41) hide show
  1. package/README.md +1 -1
  2. package/RELEASES.md +38 -0
  3. package/ai/code-style.md +15 -0
  4. package/fesm2022/file.service-C8Erkqrm.mjs +48 -0
  5. package/fesm2022/file.service-C8Erkqrm.mjs.map +1 -0
  6. package/fesm2022/{wawjs-ngx-bos-ngx-bos.config-B6tWU_X3.mjs → ngx-bos.config-DjtgUjR8.mjs} +3 -5
  7. package/fesm2022/ngx-bos.config-DjtgUjR8.mjs.map +1 -0
  8. package/fesm2022/user-crud.component-B1_SlIDS.mjs +317 -0
  9. package/fesm2022/user-crud.component-B1_SlIDS.mjs.map +1 -0
  10. package/fesm2022/wawjs-ngx-bos.mjs +206 -187
  11. package/fesm2022/wawjs-ngx-bos.mjs.map +1 -1
  12. package/package.json +11 -9
  13. package/src/feature/file/file.component.html +1 -0
  14. package/src/feature/file/file.component.ts +265 -239
  15. package/src/feature/file/file.service.ts +36 -36
  16. package/src/feature/file/file.util.ts +9 -2
  17. package/src/feature/file/pages/files/files.component.html +12 -12
  18. package/src/feature/file/pages/files/files.component.ts +116 -116
  19. package/src/feature/user/guards/admins.guard.ts +21 -21
  20. package/src/feature/user/guards/authenticated.guard.ts +15 -15
  21. package/src/feature/user/guards/guest.guard.ts +15 -15
  22. package/src/feature/user/pages/clients/clients.component.ts +19 -45
  23. package/src/feature/user/pages/user-crud.component.ts +119 -0
  24. package/src/feature/user/pages/users/users.component.ts +33 -86
  25. package/src/feature/user/user.service.ts +120 -21
  26. package/src/feature/user/user.storage.ts +31 -31
  27. package/src/form-components/ace/ace.component.ts +15 -1
  28. package/src/form-components/file/file.component.html +2 -2
  29. package/src/form-components/form-config-cache.ts +70 -0
  30. package/src/form-components/input/input.form.ts +1 -1
  31. package/src/form-components/select/select.component.html +24 -24
  32. package/src/form-components/tinymce/tinymce.component.ts +12 -0
  33. package/src/icons/spider/spider.component.ts +4 -4
  34. package/src/ngx-bos.config.ts +7 -5
  35. package/src/pages/form/form.component.ts +137 -100
  36. package/src/pages/forms/forms.component.ts +14 -2
  37. package/src/public-api.ts +1 -1
  38. package/types/wawjs-ngx-bos.d.ts +52 -15
  39. package/fesm2022/wawjs-ngx-bos-ngx-bos.config-B6tWU_X3.mjs.map +0 -1
  40. package/fesm2022/wawjs-ngx-bos-user.service-BL0vq7J4.mjs +0 -181
  41. package/fesm2022/wawjs-ngx-bos-user.service-BL0vq7J4.mjs.map +0 -1
@@ -3,10 +3,19 @@ import { Router } from '@angular/router';
3
3
  import { AlertService } from '@wawjs/ngx-ui';
4
4
  import { CrudService } from '@wawjs/ngx-crud';
5
5
  import { EmitterService } from '@wawjs/ngx-core';
6
+ import { FormcomponentService, FormService } from '@wawjs/ngx-form';
6
7
  import { HttpService } from '@wawjs/ngx-http';
7
8
  import { NGX_BOS_CONFIG } from '../../ngx-bos.config';
9
+ import { FileService } from '../file/file.service';
10
+ import { NEW_USER } from './user.const';
8
11
  import { User } from './user.interface';
9
12
  import { readStoredUser, USER_STORAGE_KEY } from './user.storage';
13
+
14
+ /** Signed-out user: no `_id`, no roles. A fresh copy so nested objects are never shared. */
15
+ function guestUser(): User {
16
+ return { ...NEW_USER, data: {}, is: {}, roles: [] };
17
+ }
18
+
10
19
  @Service()
11
20
  export class UserService extends CrudService<User> {
12
21
  private readonly _userHttpService = inject(HttpService);
@@ -19,6 +28,13 @@ export class UserService extends CrudService<User> {
19
28
 
20
29
  private readonly _bosConfig = inject(NGX_BOS_CONFIG);
21
30
 
31
+ /** Other CRUD collections whose cached documents and queued mutations belong to one user. */
32
+ private readonly _userScopedServices: Pick<CrudService<User>, 'checkUser' | 'clearDocs'>[] = [
33
+ inject(FileService),
34
+ inject(FormService),
35
+ inject(FormcomponentService),
36
+ ];
37
+
22
38
  readonly url = this._bosConfig.url;
23
39
 
24
40
  roles = this._bosConfig.roles.concat(['admin']);
@@ -27,7 +43,7 @@ export class UserService extends CrudService<User> {
27
43
 
28
44
  readonly users = this.documents;
29
45
 
30
- user = signal<User>(readStoredUser() ?? this.prepareDocument()());
46
+ user = signal<User>(readStoredUser() ?? guestUser());
31
47
 
32
48
  thumb = computed(() => {
33
49
  const thumb = this.user().thumb;
@@ -43,6 +59,36 @@ export class UserService extends CrudService<User> {
43
59
  return !!(this.user().is || {})[role];
44
60
  }
45
61
 
62
+ /** True when the user has at least one role (admin or any configured staff role). */
63
+ hasAnyRole(user: User = this.user()): boolean {
64
+ const is = user.is || {};
65
+
66
+ return Object.keys(is).some((role) => !!is[role]);
67
+ }
68
+
69
+ private _usersRequested = false;
70
+
71
+ /**
72
+ * Loads the user list once. The backend only gives it to users with a role (it holds emails
73
+ * and phones, and anyone can register), so plain accounts do not request it at all.
74
+ */
75
+ loadUsers(): void {
76
+ if (this._usersRequested || !this.hasAnyRole()) {
77
+ return;
78
+ }
79
+
80
+ this._usersRequested = true;
81
+
82
+ this.get({
83
+ query: this._bosConfig.appId ? 'appId=' + this._bosConfig.appId : '',
84
+ }).subscribe({
85
+ error: () => {
86
+ // Allow a retry, for example after the session or the roles are refreshed.
87
+ this._usersRequested = false;
88
+ },
89
+ });
90
+ }
91
+
46
92
  readonly usersByRole = computed<Record<string, User[]>>(() => {
47
93
  const splitted: Record<string, User[]> = {};
48
94
 
@@ -79,23 +125,50 @@ export class UserService extends CrudService<User> {
79
125
  });
80
126
 
81
127
  if (localStorage.getItem(USER_STORAGE_KEY)) {
82
- this.fetch({}, { name: 'me' }).subscribe((user: User) => {
83
- if (user) {
84
- this.setUser(user);
85
- } else if (localStorage.getItem(USER_STORAGE_KEY)) {
86
- this.logout();
87
- }
88
- });
128
+ this.fetch({}, { name: 'me' }).subscribe({
129
+ next: (user: User) => {
130
+ if (user) {
131
+ this.setUser(user);
132
+ // The stored roles may be stale; a role granted since the last visit counts.
133
+ this.loadUsers();
134
+ } else if (localStorage.getItem(USER_STORAGE_KEY)) {
135
+ this.logout();
136
+ }
137
+ },
138
+ error: (error: unknown) => {
139
+ // Keep the saved user while offline or while the API is down; any other error
140
+ // means the session is no longer valid.
141
+ const status = (error as { status?: number } | null)?.status;
89
142
 
90
- this.get({
91
- query: this._bosConfig.appId ? 'appId=' + this._bosConfig.appId : '',
143
+ if (status === 0 || status === 502 || status === 503 || status === 504) {
144
+ this._emitterService.complete('us.user');
145
+
146
+ return;
147
+ }
148
+
149
+ if (localStorage.getItem(USER_STORAGE_KEY)) {
150
+ this.logout();
151
+ }
152
+ },
92
153
  });
154
+
155
+ this.loadUsers();
93
156
  }
94
157
  }
95
158
 
96
159
  setUser(user: User) {
97
160
  this.user.set(user);
98
161
 
162
+ // Cached CRUD documents and queued mutations belong to the previous user on this browser:
163
+ // each collection drops them when the stored owner differs from this user.
164
+ if (user._id) {
165
+ void this.checkUser(user._id);
166
+
167
+ for (const service of this._userScopedServices) {
168
+ void service.checkUser(user._id);
169
+ }
170
+ }
171
+
99
172
  localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(user));
100
173
 
101
174
  this._emitterService.complete('us.user');
@@ -104,10 +177,17 @@ export class UserService extends CrudService<User> {
104
177
  updateMe() {
105
178
  this.setUser(this.user());
106
179
 
107
- return this.update(this.user()).subscribe(() => {
108
- this._alertService.info({
109
- text: 'Profile information has been updated',
110
- });
180
+ return this.update(this.user()).subscribe({
181
+ next: () => {
182
+ this._alertService.info({
183
+ text: 'Profile information has been updated',
184
+ });
185
+ },
186
+ error: () => {
187
+ this._alertService.error({
188
+ text: 'Something went wrong',
189
+ });
190
+ },
111
191
  });
112
192
  }
113
193
 
@@ -139,19 +219,38 @@ export class UserService extends CrudService<User> {
139
219
  }
140
220
 
141
221
  logout() {
142
- this.user.set(this.prepareDocument()());
222
+ this.user.set(guestUser());
143
223
 
144
224
  localStorage.removeItem(USER_STORAGE_KEY);
145
225
 
146
- this._userHttpService.remove('token');
226
+ // Do not leave this user's cached documents and queued mutations to the next person.
227
+ this.clearDocs();
228
+
229
+ for (const service of this._userScopedServices) {
230
+ service.clearDocs();
231
+ }
232
+
233
+ // Reload only after the server has cleared the session cookie: reloading right away can
234
+ // cancel the request and leave the session alive. Do not wait longer than 3s if the API is down.
235
+ let finished = false;
236
+
237
+ const finish = () => {
238
+ if (finished) return;
147
239
 
148
- this._userHttpService.get('/api/user/logout');
240
+ finished = true;
149
241
 
150
- this._router.navigateByUrl(this._bosConfig.signPath);
242
+ this._router.navigateByUrl(this._bosConfig.signPath);
243
+
244
+ setTimeout(() => {
245
+ location.reload();
246
+ }, 100);
247
+ };
248
+
249
+ this._userHttpService.get('/api/user/logout', finish, { err: finish });
250
+
251
+ this._userHttpService.remove('token');
151
252
 
152
- setTimeout(() => {
153
- location.reload();
154
- }, 100);
253
+ setTimeout(finish, 3000);
155
254
  }
156
255
 
157
256
  updateAdmin(user: User) {
@@ -1,31 +1,31 @@
1
- import { User } from './user.interface';
2
-
3
- /** localStorage key holding the signed-in user snapshot. */
4
- export const USER_STORAGE_KEY = 'waw_user';
5
-
6
- /**
7
- * Reads the stored user snapshot. Returns `null` when nothing is stored or when the
8
- * stored value is corrupted; a corrupted value is removed so it cannot break guards
9
- * or service initialization again.
10
- */
11
- export function readStoredUser(): User | null {
12
- const stored = localStorage.getItem(USER_STORAGE_KEY);
13
-
14
- if (!stored) {
15
- return null;
16
- }
17
-
18
- try {
19
- const user = JSON.parse(stored) as User | null;
20
-
21
- if (user && typeof user === 'object') {
22
- return user;
23
- }
24
- } catch {
25
- // fall through to cleanup
26
- }
27
-
28
- localStorage.removeItem(USER_STORAGE_KEY);
29
-
30
- return null;
31
- }
1
+ import { User } from './user.interface';
2
+
3
+ /** localStorage key holding the signed-in user snapshot. */
4
+ export const USER_STORAGE_KEY = 'waw_user';
5
+
6
+ /**
7
+ * Reads the stored user snapshot. Returns `null` when nothing is stored or when the
8
+ * stored value is corrupted; a corrupted value is removed so it cannot break guards
9
+ * or service initialization again.
10
+ */
11
+ export function readStoredUser(): User | null {
12
+ const stored = localStorage.getItem(USER_STORAGE_KEY);
13
+
14
+ if (!stored) {
15
+ return null;
16
+ }
17
+
18
+ try {
19
+ const user = JSON.parse(stored) as User | null;
20
+
21
+ if (user && typeof user === 'object') {
22
+ return user;
23
+ }
24
+ } catch {
25
+ // fall through to cleanup
26
+ }
27
+
28
+ localStorage.removeItem(USER_STORAGE_KEY);
29
+
30
+ return null;
31
+ }
@@ -8,6 +8,7 @@ import {
8
8
  import { AceComponent, AceConfigInterface } from '@wawjs/ngx-ace';
9
9
  import { FormService } from '@wawjs/ngx-form';
10
10
  import { FormBridgeData } from '../form-bridge.interface';
11
+ import { FormConfigCache } from '../form-config-cache';
11
12
 
12
13
  interface Interface {}
13
14
 
@@ -91,8 +92,22 @@ export class AceFormComponent implements OnInit {
91
92
 
92
93
  /* ------------ config / props helpers ------------ */
93
94
 
95
+ /** The same inputs must give back the same config object, or ace re-applies every option. */
96
+ private readonly _configCache = new FormConfigCache<AceConfigInterface>();
97
+
94
98
  getConfig(data: FormBridgeData): AceConfigInterface {
95
99
  const props = (data?.props ?? {}) as Record<string, unknown>;
100
+ const fieldConfig = data?.field?.['Config'];
101
+
102
+ return this._configCache.get([props, fieldConfig], () =>
103
+ this._buildConfig(props, fieldConfig),
104
+ );
105
+ }
106
+
107
+ private _buildConfig(
108
+ props: Record<string, unknown>,
109
+ fieldConfig: unknown,
110
+ ): AceConfigInterface {
96
111
  const config: AceConfigInterface = { ...DEFAULT_ACE_CONFIG };
97
112
 
98
113
  const toNumber = (v: unknown): number | undefined => {
@@ -145,7 +160,6 @@ export class AceFormComponent implements OnInit {
145
160
  }
146
161
 
147
162
  // Per-field config (code-level override)
148
- const fieldConfig = data?.field?.['Config'];
149
163
  if (
150
164
  fieldConfig &&
151
165
  typeof fieldConfig === 'object' &&
@@ -48,7 +48,7 @@
48
48
  [cropHeight]="data.props.cropHeight ?? fileDefaults.cropHeight"
49
49
  [container]="data.props.container ?? fileDefaults.container"
50
50
  [name]="data.props.name ?? fileDefaults.name"
51
- [wImages]="getValue(data)"
51
+ [wImages]="getValue(data) ?? []"
52
52
  (wImagesChange)="onValueChange(data, $event)"
53
53
  ></ngx-file>
54
54
  } @default {
@@ -66,7 +66,7 @@
66
66
  [cropHeight]="data.props.cropHeight ?? fileDefaults.cropHeight"
67
67
  [container]="data.props.container ?? fileDefaults.container"
68
68
  [name]="data.props.name ?? fileDefaults.name"
69
- [wFiles]="getValue(data)"
69
+ [wFiles]="getValue(data) ?? []"
70
70
  (wFilesChange)="onValueChange(data, $event)"
71
71
  ></ngx-file>
72
72
  } }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Keeps one config object per distinct set of inputs, so editors bound to `getConfig(data)` in a
3
+ * template do not get a new config (and re-apply or re-create) on every change detection run.
4
+ *
5
+ * Plain-data inputs are matched by JSON value. Inputs that hold functions, or that cannot be
6
+ * serialized, are matched by object identity instead, because JSON drops functions and would let
7
+ * fields that differ only in callbacks share one config.
8
+ */
9
+ export class FormConfigCache<T> {
10
+ private readonly _byValue = new Map<string, T>();
11
+
12
+ private readonly _byRef = new WeakMap<object, { sources: unknown[]; config: T }[]>();
13
+
14
+ get(sources: unknown[], build: () => T): T {
15
+ const valueKey = this._valueKey(sources);
16
+
17
+ if (valueKey !== null) {
18
+ if (!this._byValue.has(valueKey)) {
19
+ this._byValue.set(valueKey, build());
20
+ }
21
+
22
+ return this._byValue.get(valueKey) as T;
23
+ }
24
+
25
+ const anchor = sources.find(
26
+ (source) => !!source && (typeof source === 'object' || typeof source === 'function'),
27
+ ) as object | undefined;
28
+
29
+ if (!anchor) {
30
+ return build();
31
+ }
32
+
33
+ const entries = this._byRef.get(anchor) ?? [];
34
+ const cached = entries.find(
35
+ (entry) =>
36
+ entry.sources.length === sources.length &&
37
+ entry.sources.every((source, index) => source === sources[index]),
38
+ );
39
+
40
+ if (cached) {
41
+ return cached.config;
42
+ }
43
+
44
+ const config = build();
45
+
46
+ entries.push({ sources: [...sources], config });
47
+ this._byRef.set(anchor, entries);
48
+
49
+ return config;
50
+ }
51
+
52
+ /** JSON key of the inputs, or `null` when they hold functions or cannot be serialized. */
53
+ private _valueKey(sources: unknown[]): string | null {
54
+ let hasFunction = false;
55
+
56
+ try {
57
+ const key = JSON.stringify(sources, (_key, value: unknown) => {
58
+ if (typeof value === 'function') {
59
+ hasFunction = true;
60
+ }
61
+
62
+ return value;
63
+ });
64
+
65
+ return hasFunction ? null : key;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+ }
@@ -1,5 +1,5 @@
1
1
  export const inputForm = {
2
- formId: 'form',
2
+ formId: 'input',
3
3
  title: 'Form',
4
4
  components: [
5
5
  {
@@ -1,24 +1,24 @@
1
- <ng-template #templateRef let-data>
2
- <wselect
3
- [formField]="data.field"
4
- [items]="data.props.items ?? selectDefaults.items"
5
- [placeholder]="
6
- data.props.placeholder ?? selectDefaults.placeholder
7
- "
8
- [label]="data.props.label ?? selectDefaults.label"
9
- [bindLabel]="data.props.bindLabel ?? selectDefaults.bindLabel"
10
- [bindValue]="data.props.bindValue ?? selectDefaults.bindValue"
11
- [multiple]="data.props.multiple ?? selectDefaults.multiple"
12
- [clearable]="data.props.clearable ?? selectDefaults.clearable"
13
- [searchable]="data.props.searchable ?? selectDefaults.searchable"
14
- [searchableBy]="
15
- data.props.searchableBy ?? selectDefaults.searchableBy
16
- "
17
- [buttons]="data.props.buttons ?? selectDefaults.buttons"
18
- [disabled]="
19
- data.props.disabled === true ||
20
- data.component.disabled === true
21
- "
22
- (wChange)="data.props.onChange?.($event); data.wChange?.()"
23
- ></wselect>
24
- </ng-template>
1
+ <ng-template #templateRef let-data>
2
+ <wselect
3
+ [formField]="data.field"
4
+ [items]="data.props.items ?? selectDefaults.items"
5
+ [placeholder]="
6
+ data.props.placeholder ?? selectDefaults.placeholder
7
+ "
8
+ [label]="data.props.label ?? selectDefaults.label"
9
+ [bindLabel]="data.props.bindLabel ?? selectDefaults.bindLabel"
10
+ [bindValue]="data.props.bindValue ?? selectDefaults.bindValue"
11
+ [multiple]="data.props.multiple ?? selectDefaults.multiple"
12
+ [clearable]="data.props.clearable ?? selectDefaults.clearable"
13
+ [searchable]="data.props.searchable ?? selectDefaults.searchable"
14
+ [searchableBy]="
15
+ data.props.searchableBy ?? selectDefaults.searchableBy
16
+ "
17
+ [buttons]="data.props.buttons ?? selectDefaults.buttons"
18
+ [disabled]="
19
+ data.props.disabled === true ||
20
+ data.component.disabled === true
21
+ "
22
+ (wChange)="data.props.onChange?.($event); data.wChange?.()"
23
+ ></wselect>
24
+ </ng-template>
@@ -9,6 +9,7 @@ import { FormsModule } from '@angular/forms';
9
9
  import { TinymceComponent } from '@wawjs/ngx-tinymce';
10
10
  import { FormService } from '@wawjs/ngx-form';
11
11
  import { FormBridgeData } from '../form-bridge.interface';
12
+ import { FormConfigCache } from '../form-config-cache';
12
13
 
13
14
  @Component({
14
15
  templateUrl: './tinymce.component.html',
@@ -87,9 +88,20 @@ export class TinymceFormComponent implements OnInit {
87
88
 
88
89
  // ---- Props helpers (all via component.props) -----------------------------
89
90
 
91
+ /**
92
+ * The editor is re-created whenever its `config` input gets a new object, so the same props
93
+ * must give back the same config object across change detection runs.
94
+ */
95
+ private readonly _configCache = new FormConfigCache<any>();
96
+
90
97
  getConfig(data: FormBridgeData): any {
91
98
  const props = data?.props ?? {};
92
99
 
100
+ return this._configCache.get([props], () => this._buildConfig(props));
101
+ }
102
+
103
+ private _buildConfig(props: Record<string, unknown>): any {
104
+
93
105
  const toNumber = (v: unknown): number | undefined => {
94
106
  if (v === null || v === undefined || v === '') return undefined;
95
107
  const n = Number(v);
@@ -6,10 +6,10 @@ import { Component, input } from '@angular/core';
6
6
  styleUrl: './spider.component.scss',
7
7
  host: {
8
8
  class: 'spider',
9
- '[style.--spider-w]': 'width()',
10
- '[style.--spider-h]': 'height()',
11
- '[style.--spider-start]': 'start()',
12
- '[style.--spider-end]': 'end()',
9
+ '[style.--spider-w]': 'width()',
10
+ '[style.--spider-h]': 'height()',
11
+ '[style.--spider-start]': 'start()',
12
+ '[style.--spider-end]': 'end()',
13
13
  },
14
14
  })
15
15
  export class SpiderComponent {
@@ -27,7 +27,7 @@ export const DEFAULT_NGX_BOS_CONFIG: Required<NgxBosConfig> = {
27
27
  userForm: [],
28
28
  signPath: '/sign',
29
29
  profilePath: '/profile',
30
- defaultUserThumb: 'default.png',
30
+ defaultUserThumb: 'default.png',
31
31
  };
32
32
 
33
33
  export const NGX_BOS_CONFIG = new InjectionToken<Required<NgxBosConfig>>(
@@ -38,15 +38,17 @@ export const NGX_BOS_CONFIG = new InjectionToken<Required<NgxBosConfig>>(
38
38
  );
39
39
 
40
40
  export function ngxBosProvide(config: NgxBosConfig = {}): EnvironmentProviders {
41
+ // An explicit `undefined` (for example an unset environment value) must not replace a default.
42
+ const defined = Object.fromEntries(
43
+ Object.entries(config).filter(([, value]) => value !== undefined),
44
+ ) as NgxBosConfig;
45
+
41
46
  return makeEnvironmentProviders([
42
47
  {
43
48
  provide: NGX_BOS_CONFIG,
44
49
  useValue: {
45
50
  ...DEFAULT_NGX_BOS_CONFIG,
46
- ...config,
47
- roles: config.roles ?? DEFAULT_NGX_BOS_CONFIG.roles,
48
- userFields: config.userFields ?? DEFAULT_NGX_BOS_CONFIG.userFields,
49
- userForm: config.userForm ?? DEFAULT_NGX_BOS_CONFIG.userForm,
51
+ ...defined,
50
52
  },
51
53
  } satisfies Provider,
52
54
  ]);