export const [JsonDataProvider, useJsonData] = createContextProvider(() => {
// get the state synchronously
const [filePath, setFilePath] = useFilePath()!;
const [jsonPath, setJsonPath] = useJsonPath()!;
const [, setSaved] = useSaved()!;
const [jsonData, { mutate: setJsonData }] = createResource(async () => {
let jsonData: JsonValue = null;
const { args } = await getMatches();
// If user specified a file, set it as the current file
if ("file" in args && typeof args.file.value === "string") {
const resolvedPath = await path.resolve(args.file.value);
setFilePath(resolvedPath);
// Reset the json path as the file path has changed
setJsonPath([]);
}
// If a saved file path is set, load it
if (filePath()) {
try {
jsonData = await readFile(filePath()!);
} catch (error) {
dialog.message(String(error), { type: "error" });
// Remove the file path
setFilePath(null);
}
}
// Ensure the json path is pointing to an existing entry
if (jsonPath().length && !objectPath.has(jsonData, jsonPath()))
setJsonPath([]);
setSaved(true);
return jsonData;
});
return [jsonData, setJsonData] satisfies [
Resource<JsonValue>,
Setter<JsonValue>,
];
});
export const [SavedProvider, useSaved] = createContextProvider(() => {
const [jsonData] = useJsonData()!;
return createWritableMemo(() => {
jsonData();
return false;
});
});