Files
CT/src/View/Components/propertyValueList.tsx
T

71 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-07-25 01:28:55 +02:00
import * as React from "bloatless-react";
import {
StringEntryObject,
collectObjectValuesForKey,
2024-07-25 18:42:06 +02:00
localeCompare,
2024-07-25 01:28:55 +02:00
} from "../../Model/Utility/utility";
export function PropertyValueList<T>(
propertyKey: string,
stringEntryObjectConverter: (object: T) => StringEntryObject,
objects: React.ListState<T> | React.MapState<T>,
2024-07-25 18:42:06 +02:00
viewBuilder: (
keys: React.ListState<string>,
sortedKeys: React.State<string[]>
) => HTMLElement
2024-07-25 01:28:55 +02:00
) {
const propertyValues: React.ListState<string> = new React.ListState();
2024-07-25 18:42:06 +02:00
const sortedPropertyValues: React.State<string[]> = createSortedPropertyValueState(propertyValues)
objects.subscribe(() => {
collectPropertyValuesToState(
2024-07-25 01:28:55 +02:00
propertyKey,
stringEntryObjectConverter,
2024-07-25 18:42:06 +02:00
objects,
propertyValues
2024-07-25 01:28:55 +02:00
);
2024-07-25 18:42:06 +02:00
});
return viewBuilder(propertyValues, sortedPropertyValues);
}
export function collectPropertyValuesToState<T>(
propertyKey: string,
stringEntryObjectConverter: (object: T) => StringEntryObject,
objects: React.ListState<T> | React.MapState<T>,
propertyValues: React.ListState<string>
) {
const values: string[] = collectObjectValuesForKey(
propertyKey,
stringEntryObjectConverter,
[...objects.value.values()]
);
for (const existingValue of values) {
if (propertyValues.value.has(existingValue)) continue;
propertyValues.add(existingValue);
}
2024-07-25 18:42:06 +02:00
for (const displayedValue of propertyValues.value.values()) {
if (values.includes(displayedValue) == false) {
propertyValues.remove(displayedValue);
}
2024-07-25 01:28:55 +02:00
}
2024-07-25 18:42:06 +02:00
}
2024-07-25 01:28:55 +02:00
2024-07-25 18:42:06 +02:00
export function createSortedPropertyValueState(
propertyValues: React.ListState<string>
): React.State<string[]> {
return React.createProxyState([propertyValues], () =>
[...propertyValues.value.values()].sort(localeCompare)
);
}
2024-07-25 01:28:55 +02:00
2024-07-25 18:42:06 +02:00
export function createPropertyValueIndexState(
sortedKeys: React.State<string[]>,
key: string
): React.State<number> {
return React.createProxyState([sortedKeys], () =>
sortedKeys.value.indexOf(key)
);
2024-07-25 01:28:55 +02:00
}