Ver código fonte

feat: Allow use of reactive model from store in useForm

Owen Diffey 1 ano atrás
pai
commit
d29334a89c

+ 5 - 9
frontend/src/components/modals/EditNews.vue

@@ -56,7 +56,7 @@ const getTitle = () => {
 	return title;
 };
 
-const { inputs, save, setOriginalValue } = useForm(
+const { inputs, save, setModelValues } = useForm(
 	{
 		markdown: {
 			value: "# Header\n## Sub-Header\n- **So**\n- _Many_\n- ~Points~\n\nOther things you want to say and [link](https://example.com).\n\n### Sub-Sub-Header\n> Oh look, a quote!\n\n`lil code`\n\n```\nbig code\n```\n",
@@ -111,19 +111,15 @@ onMounted(async () => {
 
 	await onReady(async () => {
 		if (props.newsId && !props.createNews) {
-			const { value: data } = await findById(props.newsId).catch(() => {
+			const data = await findById(props.newsId).catch(() => {
 				new Toast("News with that ID not found.");
 				closeCurrentModal();
 			});
 
-			setOriginalValue({
-				markdown: data.markdown,
-				status: data.status,
-				showToNewUsers: data.showToNewUsers
-			});
+			setModelValues(data, ["markdown", "status", "showToNewUsers"]);
 
-			createdBy.value = data.createdBy;
-			createdAt.value = data.createdAt;
+			createdBy.value = data.value.createdBy;
+			createdAt.value = data.value.createdAt;
 		}
 
 		console.log(

+ 28 - 2
frontend/src/composables/useForm.ts

@@ -1,4 +1,4 @@
-import { ref, computed, onMounted, onBeforeUnmount } from "vue";
+import { ref, computed, onMounted, onBeforeUnmount, Ref, watch } from "vue";
 import { useModalsStore } from "@/stores/modals";
 
 export const useForm = (
@@ -207,6 +207,31 @@ export const useForm = (
 		});
 	};
 
+	const setModelValues = (
+		model: Ref<Record<string, any>>,
+		keys: string[]
+	) => {
+		const getModelValue = (key, modelObject) => {
+			let value = JSON.parse(JSON.stringify(modelObject));
+			key.split(".").forEach(property => {
+				value = value[property];
+			});
+			return value;
+		};
+
+		const setMappedValues = modelObject => {
+			setOriginalValue(
+				Object.fromEntries(
+					keys.map(key => [key, getModelValue(key, modelObject)])
+				)
+			);
+		};
+
+		setMappedValues(model.value);
+
+		watch(model, setMappedValues);
+	};
+
 	onMounted(() => {
 		if (
 			options &&
@@ -231,6 +256,7 @@ export const useForm = (
 		unsavedChanges,
 		save,
 		setValue,
-		setOriginalValue
+		setOriginalValue,
+		setModelValues
 	};
 };