1
0
mirror of https://github.com/misskey-dev/misskey.git synced 2026-05-23 01:44:10 +02:00

refactor(frontend): prefer.model, store.modelではcustomRefを使用するように (#17058)

* refactor(frontend): prefer.model, store.modelではcustomRefを使用するように

* fix: watchの解除に失敗してもエラーで落ちないように

* Update packages/frontend/src/lib/pizzax.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
かっこかり
2026-01-02 21:34:43 +09:00
committed by GitHub
parent b5454cb2c4
commit 443e1ed29e
7 changed files with 67 additions and 65 deletions

View File

@@ -3,11 +3,11 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { computed, onUnmounted, ref, watch } from 'vue';
import { customRef, ref, watch, onScopeDispose } from 'vue';
import { EventEmitter } from 'eventemitter3';
import { host, version } from '@@/js/config.js';
import { PREF_DEF } from './def.js';
import type { Ref, WritableComputedRef } from 'vue';
import type { Ref } from 'vue';
import type { MenuItem } from '@/types/menu.js';
import { genId } from '@/utility/id.js';
import { copyToClipboard } from '@/utility/copy-to-clipboard.js';
@@ -299,36 +299,39 @@ export class PreferencesManager extends EventEmitter<PreferencesManagerEvents> {
* 特定のキーの、簡易的なcomputed refを作ります
* 主にvue上で設定コントロールのmodelとして使う用
*/
public model<K extends keyof PREF, V extends ValueOf<K> = ValueOf<K>>(
public model<K extends keyof PREF, V = ValueOf<K>>(
key: K,
): Ref<V>;
public model<K extends keyof PREF, V extends Exclude<any, ValueOf<K>>>(
key: K,
getter: (v: ValueOf<K>) => V,
setter: (v: V) => ValueOf<K>,
): Ref<V>;
public model<K extends keyof PREF, V>(
key: K,
getter?: (v: ValueOf<K>) => V,
setter?: (v: V) => ValueOf<K>,
): WritableComputedRef<V> {
const valueRef = ref(this.s[key]);
): Ref<V> {
return customRef<V>((track, trigger) => {
const watchStop = watch(this.r[key], () => {
trigger();
});
const stop = watch(this.r[key], val => {
valueRef.value = val;
});
onScopeDispose(() => {
watchStop();
}, true);
// NOTE: vueコンポーネント内で呼ばれない限りは、onUnmounted は無意味なのでメモリリークする
onUnmounted(() => {
stop();
});
// TODO: VueのcustomRef使うと良い感じになるかも
return computed({
get: () => {
if (getter) {
return getter(valueRef.value);
} else {
return valueRef.value;
}
},
set: (value) => {
const val = setter ? setter(value) : value;
this.commit(key, val);
valueRef.value = val;
},
return {
get: () => {
track();
return (getter != null ? getter(this.s[key]) : this.s[key]) as V;
},
set: (value) => {
const val = setter != null ? setter(value) : value;
this.commit(key, val as ValueOf<K>);
},
};
});
}