File size: 1,200 Bytes
68d7816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { assign, emit, setup } from '#/xstate2';

import { accumulateUsage, emptyUsageSummary, type UsageRecord, type UsageSummary } from './usage';

export type UsageEvent = { type: 'usage.record'; record: UsageRecord };

export type UsageEmitted = { type: 'usage.updated'; record: UsageRecord; summary: UsageSummary };

export interface UsageMachineContext {
  records: UsageRecord[];
  summary: UsageSummary;
}

export function createUsageMachine() {
  return setup({
    types: {
      context: {} as UsageMachineContext,
      events: {} as UsageEvent,
      emitted: {} as UsageEmitted,
    },
  }).createMachine({
    id: 'usage',
    context: {
      records: [],
      summary: emptyUsageSummary(),
    },
    on: {
      'usage.record': {
        actions: [
          assign(({ context, event }) => ({
            records: [...context.records, event.record],
            summary: accumulateUsage(context.summary, event.record),
          })),
          emit(({ context }) => ({
            type: 'usage.updated' as const,
            record: context.records[context.records.length - 1] as UsageRecord,
            summary: context.summary,
          })),
        ],
      },
    },
  });
}