|
| 1 | +import { MaybeRef, computed, unref, ref, Ref } from 'vue'; |
| 2 | +import type { vtkObject } from '@kitware/vtk.js/interfaces'; |
| 3 | +import { onPausableVTKEvent } from '@/src/composables/onPausableVTKEvent'; |
| 4 | +import { batchForNextTask } from '@/src/utils/batchForNextTask'; |
| 5 | +import { arrayEquals } from '@/src/utils'; |
| 6 | +import type { Maybe } from '@/src/types'; |
| 7 | + |
| 8 | +/** |
| 9 | + * A computed property that derives a reactive property from a VTK object using a getter function. |
| 10 | + * The computed property updates when the underlying VTK object emits an 'onModified' event. |
| 11 | + * |
| 12 | + * @param vtkObjectRef A Vue Ref or direct reference to a VTK object (or null/undefined). |
| 13 | + * @param propertyGetter A function that computes the property value. It will be called reactively. |
| 14 | + * @returns A read-only ComputedRef to the derived property. |
| 15 | + */ |
| 16 | +export function useVtkProperty<T extends Maybe<vtkObject>, R>( |
| 17 | + obj: MaybeRef<T>, |
| 18 | + propertyGetter: () => R |
| 19 | +) { |
| 20 | + const initialValue = propertyGetter(); |
| 21 | + const trackedValue = ref( |
| 22 | + Array.isArray(initialValue) ? [...initialValue] : initialValue |
| 23 | + ) as Ref<R>; |
| 24 | + let lastValueIsArray = Array.isArray(initialValue); |
| 25 | + const onModified = batchForNextTask(() => { |
| 26 | + if (unref(obj)?.isDeleted()) return; |
| 27 | + |
| 28 | + const currentValue = propertyGetter(); // Avoid unnecessary updates when array contents haven't changed |
| 29 | + if (lastValueIsArray && Array.isArray(currentValue)) { |
| 30 | + const previousValue = trackedValue.value; |
| 31 | + if ( |
| 32 | + Array.isArray(previousValue) && |
| 33 | + !arrayEquals(previousValue as any[], currentValue as any[]) |
| 34 | + ) { |
| 35 | + trackedValue.value = [...currentValue] as R; |
| 36 | + return; |
| 37 | + } |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + if (Array.isArray(currentValue)) { |
| 42 | + trackedValue.value = [...currentValue] as R; |
| 43 | + lastValueIsArray = true; |
| 44 | + } else { |
| 45 | + trackedValue.value = currentValue; |
| 46 | + lastValueIsArray = false; |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + onPausableVTKEvent(obj as vtkObject, 'onModified', onModified); |
| 51 | + return computed(() => { |
| 52 | + return trackedValue.value; |
| 53 | + }); |
| 54 | +} |
0 commit comments