-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpattern-import-runtime.ts
More file actions
219 lines (203 loc) · 8.07 KB
/
Copy pathpattern-import-runtime.ts
File metadata and controls
219 lines (203 loc) · 8.07 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import { applyOverlayIntent, OVERLAY_INTENT_BOARD_REBUILT } from "../overlay-policy.js";
import {
clearEditMode,
clearPatternStatus,
dismissFirstRunHint,
setPatternStatus,
} from "../state/overlay-state.js";
import { RULE_SELECTION_ORIGIN_DEFAULT } from "../state/constants.js";
import { setRuleSelectionOrigin } from "../state/simulation-state.js";
import { parsePatternText } from "../pattern-io.js";
import { createActionMutationAdapter } from "./shared/mutation-adapter.js";
import {
buildPatternImportResetRequest,
normalizeImportedCellUpdates,
shouldConfirmPatternImport,
} from "./pattern-import-plan.js";
import type { ActionMutationAdapter, PatternImportOptions } from "../types/actions.js";
import type {
InteractionController,
PostControlFunction,
SetCellsRequestFunction,
SimulationMutations,
ViewportController,
} from "../types/controller.js";
import type { ParsedPattern, SimulationSnapshot } from "../types/domain.js";
import type { AppState } from "../types/state.js";
interface PatternImportElements {
speedInput: HTMLInputElement | null;
}
export interface PatternTextImportOptions extends PatternImportOptions {
failurePrefix: string;
}
interface CreatePatternImportRuntimeOptions {
state: AppState;
elements: PatternImportElements;
interactions: Pick<InteractionController, "runSerialized">;
viewportController: Pick<ViewportController, "suppressAutoSync">;
renderControlPanel: () => void;
applySimulationState: (
simulationState: SimulationSnapshot,
options?: { source?: string },
) => void;
postControlFn: PostControlFunction;
setCellsRequestFn: SetCellsRequestFunction;
onError: (error: unknown) => void;
refreshState: () => Promise<void>;
simulationMutations?: ActionMutationAdapter | SimulationMutations | null;
parsePatternTextFn?: typeof parsePatternText;
confirmImportFn?: (message: string) => boolean;
applyOverlayIntentFn?: typeof applyOverlayIntent;
dismissFirstRunHintFn?: typeof dismissFirstRunHint;
clearEditModeFn?: typeof clearEditMode;
setRuleSelectionOriginFn?: typeof setRuleSelectionOrigin;
setPatternStatusFn?: typeof setPatternStatus;
clearPatternStatusFn?: typeof clearPatternStatus;
}
export interface PatternImportRuntime {
importPatternText(
readTextTask: () => Promise<string>,
options: PatternTextImportOptions,
): Promise<SimulationSnapshot | null>;
applyParsedPattern(
parsedPattern: ParsedPattern,
options: PatternTextImportOptions & { skipConfirm?: boolean },
): Promise<SimulationSnapshot | null>;
}
export function createPatternImportRuntime({
state,
elements,
interactions,
viewportController,
renderControlPanel,
applySimulationState,
postControlFn,
setCellsRequestFn,
onError,
refreshState,
simulationMutations = null,
parsePatternTextFn = parsePatternText,
confirmImportFn = (message) => window.confirm(message),
applyOverlayIntentFn = applyOverlayIntent,
dismissFirstRunHintFn = dismissFirstRunHint,
clearEditModeFn = clearEditMode,
setRuleSelectionOriginFn = setRuleSelectionOrigin,
setPatternStatusFn = setPatternStatus,
clearPatternStatusFn = clearPatternStatus,
}: CreatePatternImportRuntimeOptions): PatternImportRuntime {
const mutations: ActionMutationAdapter | SimulationMutations =
simulationMutations || createActionMutationAdapter({ interactions, applySimulationState });
function updatePatternStatus(message = "", tone = "info"): void {
if (!message) {
clearPatternStatusFn(state);
} else {
setPatternStatusFn(state, message, tone);
}
renderControlPanel();
}
function handleImportParseFailure(prefix: string, error: unknown): void {
const message = error instanceof Error ? error.message : String(error);
updatePatternStatus(`${prefix}: ${message}`, "error");
onError(error);
}
async function parseImportedPattern(
readTextTask: () => Promise<string>,
failurePrefix: string,
): Promise<ParsedPattern | null> {
try {
return parsePatternTextFn(await readTextTask());
} catch (error) {
handleImportParseFailure(failurePrefix, error);
return null;
}
}
async function applyParsedPattern(
parsedPattern: ParsedPattern,
{
successMessage,
cancelMessage,
blockingActivity = null,
onSuccess = () => {},
skipConfirm = false,
}: PatternTextImportOptions & { skipConfirm?: boolean },
): Promise<SimulationSnapshot | null> {
if (
!skipConfirm &&
shouldConfirmPatternImport(state) &&
!confirmImportFn("Importing a pattern will replace the current board. Continue?")
) {
updatePatternStatus(cancelMessage, "info");
return null;
}
const requestedSpeed = Number(elements.speedInput?.value);
const speed = Number.isFinite(requestedSpeed) ? requestedSpeed : Number(state.speed);
viewportController.suppressAutoSync?.();
return mutations
.runSerialized(
async () => {
const resetState = await postControlFn(
"/api/control/reset",
buildPatternImportResetRequest(parsedPattern, speed),
);
const resolvedResetState = await mutations.applyRemoteState(resetState, {
source: "external",
});
const importedCells = normalizeImportedCellUpdates(parsedPattern);
if (importedCells.length === 0) {
return resolvedResetState;
}
const availableCellIds = new Set(
resolvedResetState.topology.cells.map((cell) => cell.id),
);
const unknownCellId = importedCells.find(
(cell) => !availableCellIds.has(cell.id),
)?.id;
if (unknownCellId) {
throw new Error(
`Pattern references an unknown cell id '${unknownCellId}'.`,
);
}
const importedState = await setCellsRequestFn(importedCells);
await mutations.applyRemoteState(importedState, { source: "external" });
return importedState;
},
{
blockingActivity,
onError: (error) => {
const message = error instanceof Error ? error.message : String(error);
updatePatternStatus(`Import failed: ${message}`, "error");
onError(error);
},
onRecover: refreshState,
},
)
.then(async (result) => {
viewportController.suppressAutoSync?.();
dismissFirstRunHintFn(state);
setRuleSelectionOriginFn(state, RULE_SELECTION_ORIGIN_DEFAULT);
const overlaysRestored = applyOverlayIntentFn(state, OVERLAY_INTENT_BOARD_REBUILT);
const editChanged = clearEditModeFn(state);
if (overlaysRestored || editChanged) {
renderControlPanel();
}
await onSuccess();
updatePatternStatus(successMessage, "success");
return result;
})
.catch(() => null);
}
async function importPatternText(
readTextTask: () => Promise<string>,
options: PatternTextImportOptions,
): Promise<SimulationSnapshot | null> {
const parsedPattern = await parseImportedPattern(readTextTask, options.failurePrefix);
if (!parsedPattern) {
return null;
}
return applyParsedPattern(parsedPattern, options);
}
return {
importPatternText,
applyParsedPattern,
};
}