refactor: Significantly refactor how conditions work internally (#1886)

- Much improved API cleanliness and testability to allow further
extensibility in future
 - Simplified code in `live` view

This technically contains a small change in how overrides work in the
`live` view. Since that change is _closer_ to the documentation, and
since this is likely to be rarely used, this is not considered a
breaking change. Previously, overrides for a given live camera would
always render _as if_ that camera was selected, vs was actually
selected. Now, overrides will only apply in the live view when the
camera is _actually_ selected. If this is an issue for you in practice,
lets discuss.
This commit is contained in:
Dermot Duffy
2025-02-11 20:07:55 -08:00
committed by GitHub
parent a92074bc8d
commit 8d3cf07b43
51 changed files with 2443 additions and 2118 deletions
@@ -0,0 +1,76 @@
import { merge } from 'lodash-es';
import { ZodType as ZodSchema } from 'zod';
import { ConditionsManagerReadonlyInterface } from '../../conditions/types';
import {
copyConfig,
deleteConfigValue,
getConfigValue,
setConfigValue,
} from '../../config/management';
import { Overrides, RawAdvancedCameraCardConfig } from '../../config/types';
import { localize } from '../../localize/localize';
import { AdvancedCameraCardError } from '../../types';
import { desparsifyArrays } from '../../utils/basic';
class OverrideConfigurationError extends AdvancedCameraCardError {}
export function getOverriddenConfig<RT extends RawAdvancedCameraCardConfig>(
manager: ConditionsManagerReadonlyInterface,
config: Readonly<RT>,
options?: {
configOverrides?: Readonly<Overrides>;
schema?: ZodSchema;
},
): RT {
if (!options?.configOverrides) {
return config;
}
let output = copyConfig(config);
let overridden = false;
for (const override of options.configOverrides) {
if (manager.getEvaluation()?.result) {
override.delete?.forEach((deletionKey) => {
deleteConfigValue(output, deletionKey);
});
Object.keys(override.set ?? {}).forEach((setKey) => {
setConfigValue(output, setKey, override.set?.[setKey]);
});
Object.keys(override.merge ?? {}).forEach((mergeKey) => {
setConfigValue(
output,
mergeKey,
merge({}, getConfigValue(output, mergeKey), override.merge?.[mergeKey]),
);
});
overridden = true;
}
}
if (!overridden) {
// Return the same configuration object if it has not been overridden (to
// reduce re-renders for a configuration that has not changed).
return config;
}
if (options?.configOverrides?.some((override) => override.delete?.length)) {
// If anything was deleted during this override, empty undefined slots may
// be left in arrays where values were unset. Desparsify them.
output = desparsifyArrays(output);
}
if (options?.schema) {
const parseResult = options.schema.safeParse(output);
if (!parseResult.success) {
throw new OverrideConfigurationError(
localize('error.invalid_configuration_override'),
[parseResult.error.errors, output],
);
}
return parseResult.data;
}
return output;
}