From e1cd7c94fb13f8e49667b17554d22ce8de627a2a Mon Sep 17 00:00:00 2001 From: かっこかり <67428053+kakkokari-gtyih@users.noreply.github.com> Date: Sat, 10 May 2025 07:58:26 +0900 Subject: refactor(frontend): use* 関数の格納場所のフォルダ名を composables に変更 (#16004) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor(frontend): use* 関数の格納場所を正式名称(composables)に変更 * migrate * move useLoading --- packages/frontend/src/composables/use-form.ts | 57 +++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 packages/frontend/src/composables/use-form.ts (limited to 'packages/frontend/src/composables/use-form.ts') diff --git a/packages/frontend/src/composables/use-form.ts b/packages/frontend/src/composables/use-form.ts new file mode 100644 index 0000000000..1c93557413 --- /dev/null +++ b/packages/frontend/src/composables/use-form.ts @@ -0,0 +1,57 @@ +/* + * SPDX-FileCopyrightText: syuilo and misskey-project + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { computed, reactive, watch } from 'vue'; +import type { Reactive } from 'vue'; +import { deepEqual } from '@/utility/deep-equal'; + +function copy(v: T): T { + return JSON.parse(JSON.stringify(v)); +} + +function unwrapReactive(v: Reactive): T { + return JSON.parse(JSON.stringify(v)); +} + +export function useForm>(initialState: T, save: (newState: T) => Promise) { + const currentState = reactive(copy(initialState)); + const previousState = reactive(copy(initialState)); + + const modifiedStates = reactive>({} as any); + for (const key in currentState) { + modifiedStates[key] = false; + } + const modified = computed(() => Object.values(modifiedStates).some(v => v)); + const modifiedCount = computed(() => Object.values(modifiedStates).filter(v => v).length); + + watch([currentState, previousState], () => { + for (const key in modifiedStates) { + modifiedStates[key] = !deepEqual(currentState[key], previousState[key]); + } + }, { deep: true }); + + async function _save() { + await save(unwrapReactive(currentState)); + for (const key in currentState) { + previousState[key] = copy(currentState[key]); + } + } + + function discard() { + for (const key in currentState) { + currentState[key] = copy(previousState[key]); + } + } + + return { + state: currentState, + savedState: previousState, + modifiedStates, + modified, + modifiedCount, + save: _save, + discard, + }; +} -- cgit v1.2.3-freya