@vdatacloud/cx-commons 0.9.0 → 0.10.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vdatacloud/cx-commons",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Product CX Commons - Shared design system, UI components, and Astro integration for Data Cloud web applications",
5
5
  "repository": {
6
6
  "type": "git",
@@ -93,6 +93,8 @@ export const cxMessages = {
93
93
  cancel: 'Cancel',
94
94
  cancelling: 'Cancelling…',
95
95
  cancelRequested: 'Cancel requested',
96
+ elapsed: '{time} so far',
97
+ took: 'Took {time}',
96
98
  notCancellable: '{state, select, SUBMITTED {Too late to cancel: it is already with the ledger and will finish on its own.} COMMITTED {Too late to cancel: it has already been recorded. Undo it through the matching action instead.} CANCELLED {It was already cancelled.} other {Too late to cancel: it has already finished.}}',
97
99
  },
98
100
  language: {
@@ -189,6 +191,8 @@ export const cxMessages = {
189
191
  cancel: 'Annuler',
190
192
  cancelling: 'Annulation…',
191
193
  cancelRequested: 'Annulation demandée',
194
+ elapsed: 'Depuis {time}',
195
+ took: 'Durée : {time}',
192
196
  notCancellable: '{state, select, SUBMITTED {Trop tard pour annuler : l’opération est déjà au registre et se terminera d’elle-même.} COMMITTED {Trop tard pour annuler : l’opération est déjà enregistrée. Annulez-la plutôt par l’action correspondante.} CANCELLED {L’opération était déjà annulée.} other {Trop tard pour annuler : l’opération est déjà terminée.}}',
193
197
  },
194
198
  language: {
@@ -83,8 +83,28 @@ function stateLabel(t: Translator, op: Operation): string {
83
83
  return t.maybe(`cx.operation.state.${op.state}`) ?? op.state;
84
84
  }
85
85
 
86
- /** The operation's current state as an element (no following). */
87
- export function renderOperationStatus<R>(op: Operation<R>, opts: OperationStatusOptions<R> & { onCancel?: () => void; cancelling?: boolean } = {}): HTMLElement {
86
+ /** A duration as 8s, 1m 05s or 1h 02m. */
87
+ export function formatElapsed(ms: number): string {
88
+ const s = Math.max(0, Math.floor(ms / 1000));
89
+ if (s < 60) return `${s}s`;
90
+ const m = Math.floor(s / 60);
91
+ if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`;
92
+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`;
93
+ }
94
+
95
+ /** How long op has run by the server's clock: createdAt to its last change. */
96
+ export function serverElapsedMs(op: Pick<Operation, 'createdAt' | 'updatedAt'>): number {
97
+ const d = Date.parse(op.updatedAt) - Date.parse(op.createdAt);
98
+ return Number.isFinite(d) ? Math.max(0, d) : 0;
99
+ }
100
+
101
+ function elapsedText(t: Translator, op: Operation, ms: number): string {
102
+ return t.t(isTerminal(op) ? 'cx.operation.took' : 'cx.operation.elapsed', { time: formatElapsed(ms) });
103
+ }
104
+
105
+ /** The operation's current state as an element (no following). elapsedMs
106
+ * is how long it has run (default: by the server's clock, to its last change). */
107
+ export function renderOperationStatus<R>(op: Operation<R>, opts: OperationStatusOptions<R> & { onCancel?: () => void; cancelling?: boolean; elapsedMs?: number } = {}): HTMLElement {
88
108
  const t = getTranslator(opts.locale);
89
109
  const tone = TONE[toneOf(op.state)];
90
110
  const root = el('div', `rounded-2xl border p-4 text-sm text-slate-800 dark:text-slate-100 ${tone.box}`);
@@ -99,11 +119,17 @@ export function renderOperationStatus<R>(op: Operation<R>, opts: OperationStatus
99
119
  const label = el('div', 'min-w-0');
100
120
  label.append(el('p', 'font-semibold', stateLabel(t, op)));
101
121
  const sub: string[] = [];
102
- const kind = t.maybe(`cx.operation.kind.${op.kind}`);
122
+ // an app's label for the kind, e.g. 'Ratifying {subject}'
123
+ const kind = t.maybe(`cx.operation.kind.${op.kind}`, { subject: op.subject ?? '' });
103
124
  if (kind) sub.push(kind);
104
125
  if (op.steps > 1 && !isTerminal(op)) sub.push(t.t('cx.operation.step', { step: op.step || 1, steps: op.steps }));
105
126
  if (op.cancelRequested) sub.push(t.t('cx.operation.cancelRequested'));
106
- if (sub.length) label.append(el('p', 'text-xs text-slate-600 dark:text-slate-300', sub.join(' · ')));
127
+ const line = el('p', 'text-xs text-slate-600 dark:text-slate-300', sub.join(' · '));
128
+ const elapsed = el('span', 'tabular-nums', elapsedText(t, op, opts.elapsedMs ?? serverElapsedMs(op)));
129
+ elapsed.dataset.operationElapsed = '';
130
+ if (sub.length) line.append(' · ');
131
+ line.append(elapsed);
132
+ label.append(line);
107
133
  left.append(label);
108
134
  head.append(left);
109
135
 
@@ -144,9 +170,18 @@ export function mountOperationStatus<R>(container: HTMLElement, op: Operation<R>
144
170
  let cancelError: HTMLElement | null = null; // a failed cancel request; cleared once the operation ends
145
171
  let cancelNote: HTMLElement | null = null; // "too late to cancel"; stays with the outcome it explains
146
172
  const t = getTranslator(opts.locale);
173
+ // Elapsed by the server's clock at the last change, plus the time since
174
+ // it arrived here: no skew between the browser's clock and the server's.
175
+ let seenAt = Date.now();
176
+ const elapsedMs = () => serverElapsedMs(current) + (isTerminal(current) ? 0 : Date.now() - seenAt);
177
+ let ticker: ReturnType<typeof setInterval> | undefined;
178
+ const stopTicking = () => {
179
+ if (ticker !== undefined) clearInterval(ticker);
180
+ ticker = undefined;
181
+ };
147
182
 
148
183
  const draw = () => {
149
- const n = renderOperationStatus(current, { ...opts, cancelling, onCancel: opts.noCancel ? undefined : cancel });
184
+ const n = renderOperationStatus(current, { ...opts, cancelling, elapsedMs: elapsedMs(), onCancel: opts.noCancel ? undefined : cancel });
150
185
  if (cancelNote) n.append(cancelNote);
151
186
  if (cancelError) n.append(cancelError);
152
187
  container.replaceChildren(n);
@@ -154,7 +189,11 @@ export function mountOperationStatus<R>(container: HTMLElement, op: Operation<R>
154
189
  const update = (next: Operation<R>) => {
155
190
  if (next.operationId !== current.operationId || next.seq < current.seq) return;
156
191
  current = next;
157
- if (isTerminal(next)) cancelError = null;
192
+ seenAt = Date.now();
193
+ if (isTerminal(next)) {
194
+ cancelError = null;
195
+ stopTicking();
196
+ }
158
197
  draw();
159
198
  opts.onUpdate?.(next);
160
199
  };
@@ -191,6 +230,13 @@ export function mountOperationStatus<R>(container: HTMLElement, op: Operation<R>
191
230
  }
192
231
 
193
232
  draw();
233
+ if (opts.follow !== false && !isTerminal(op)) {
234
+ // only the elapsed text changes each second (Cancel keeps its focus)
235
+ ticker = setInterval(() => {
236
+ const n = container.querySelector<HTMLElement>('[data-operation-elapsed]');
237
+ if (n) n.textContent = elapsedText(t, current, elapsedMs());
238
+ }, 1000);
239
+ }
194
240
  let done: Promise<Operation<R>>;
195
241
  if (opts.follow === false || isTerminal(op)) {
196
242
  done = Promise.resolve(op);
@@ -202,9 +248,10 @@ export function mountOperationStatus<R>(container: HTMLElement, op: Operation<R>
202
248
  opts.onDone?.(final);
203
249
  return final;
204
250
  })
205
- .catch(() => current);
251
+ .catch(() => current)
252
+ .finally(stopTicking);
206
253
  }
207
- return { done, stop: () => controller.abort() };
254
+ return { done, stop: () => { stopTicking(); controller.abort(); } };
208
255
  }
209
256
 
210
257
  /**