(inputDef: InputDefinition<T>, checkIsActive: OptionalDefPredicateFn, options?: OptionalDefOptions)
| 193 | * it would be useful. |
| 194 | */ |
| 195 | export const optionalDef = <T>(inputDef: InputDefinition<T>, checkIsActive: OptionalDefPredicateFn, options?: OptionalDefOptions): InputDefinition<T | undefined> => { |
| 196 | // In certain situations we need to know if the def has changed. |
| 197 | let isActive = options?.initiallyActive ?? false |
| 198 | const decideAndSave = (context?: unknown[]): boolean => { |
| 199 | isActive = checkIsActive(context) |
| 200 | return isActive |
| 201 | } |
| 202 | const buildFromUserInput = async (context?: unknown[]): Promise<T | undefined | CancelAction> => |
| 203 | decideAndSave(context) ? inputDef.buildFromUserInput(context) : undefined |
| 204 | const summarizeForEdit = (value: T | undefined, context?: unknown[]): string | Uneditable => |
| 205 | isActive ? inputDef.summarizeForEdit(value as T, context) : uneditable |
| 206 | const updateFromUserInput = async (original: T | undefined, context?: unknown[]): Promise<T | undefined | CancelAction> => |
| 207 | isActive |
| 208 | ? (original ? inputDef.updateFromUserInput(original as T, context) : inputDef.buildFromUserInput(context)) |
| 209 | : undefined |
| 210 | |
| 211 | const updateIfNeeded = async (original: T | undefined, updatedPropertyName: string | number | symbol, context?: unknown[]): Promise<T | undefined | CancelAction> => { |
| 212 | const previouslyActive = isActive |
| 213 | const currentlyActive = decideAndSave(context) |
| 214 | if (previouslyActive && currentlyActive) { |
| 215 | return inputDef.updateIfNeeded |
| 216 | ? inputDef.updateIfNeeded(original as T, updatedPropertyName, context) |
| 217 | : original |
| 218 | } |
| 219 | if (currentlyActive && !previouslyActive) { |
| 220 | return inputDef.buildFromUserInput(context) |
| 221 | } |
| 222 | return undefined |
| 223 | } |
| 224 | |
| 225 | return { name: inputDef.name, buildFromUserInput, summarizeForEdit, updateFromUserInput, updateIfNeeded } |
| 226 | } |
no outgoing calls
no test coverage detected