@@ -23,9 +23,9 @@ type TimelineAction<T> =
23
23
| { type : 'run-started' }
24
24
| { type : 'task-started' ; task : T ; onTaskCompleted : ( ) => void }
25
25
| { type : 'task-completed' }
26
- | { type : 'run -completed' }
26
+ | { type : 'all-tasks -completed' }
27
27
| { type : 'run-canceled' }
28
- | { type : 'logger-flushed ' }
28
+ | { type : 'run-completed ' }
29
29
| { type : 'logger-error' ; error : Error } ;
30
30
31
31
export type Logger = {
@@ -51,11 +51,11 @@ function timelineReducer<T extends BaseTask>(
51
51
onTaskCompleted : action . onTaskCompleted ,
52
52
} ;
53
53
case 'task-completed' :
54
- case 'run -completed' :
54
+ case 'all-tasks -completed' :
55
55
return { status : 'loading' , task : null } ;
56
56
case 'run-canceled' :
57
57
return { status : 'canceled' , task : null } ;
58
- case 'logger-flushed ' :
58
+ case 'run-completed ' :
59
59
return { status : 'completed' , task : null } ;
60
60
case 'logger-error' :
61
61
return { status : 'crashed' , task : null , error : action . error } ;
@@ -64,12 +64,29 @@ function timelineReducer<T extends BaseTask>(
64
64
65
65
export default function useManagedTimeline < Task extends BaseTask > (
66
66
timeline : Timeline < Task > | null ,
67
- logger : Logger | null
67
+ logger : Logger | null ,
68
+ {
69
+ cancelRunOnUnload,
70
+ completeRunOnCompletion,
71
+ } : { cancelRunOnUnload : boolean ; completeRunOnCompletion : boolean }
68
72
) : TimelineState < Task > {
69
73
const [ state , dispatch ] = React . useReducer ( timelineReducer < Task > , {
70
74
status : 'idle' ,
71
75
task : null ,
72
76
} ) ;
77
+
78
+ // When the page is closed, one may want to mark the run as canceled.
79
+ React . useEffect ( ( ) => {
80
+ if ( ! cancelRunOnUnload ) return ;
81
+ let unloadHandler = ( ) => {
82
+ logger ?. cancelRun ?.( ) ;
83
+ } ;
84
+ globalThis . addEventListener ( 'unload' , unloadHandler ) ;
85
+ return ( ) => {
86
+ globalThis . removeEventListener ( 'unload' , unloadHandler ) ;
87
+ } ;
88
+ } , [ cancelRunOnUnload , logger ] ) ;
89
+
73
90
React . useEffect ( ( ) => {
74
91
let hasEnded = false ;
75
92
async function doRun ( ) {
@@ -99,10 +116,11 @@ export default function useManagedTimeline<Task extends BaseTask>(
99
116
} ,
100
117
} ) ;
101
118
if ( hasEnded ) return ;
102
- dispatch ( { type : 'run -completed' } ) ;
119
+ dispatch ( { type : 'all-tasks -completed' } ) ;
103
120
await logger ?. flush ( ) ;
121
+ await logger ?. completeRun ( ) ;
104
122
if ( hasEnded ) return ;
105
- dispatch ( { type : 'logger-flushed ' } ) ;
123
+ dispatch ( { type : 'run-completed ' } ) ;
106
124
hasEnded = true ;
107
125
}
108
126
doRun ( ) ;
0 commit comments