vue#WatchStopHandle TypeScript Examples

The following examples show how to use vue#WatchStopHandle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useTimeoutFn.ts    From vhook with MIT License 6 votes vote down vote up
export function useTimeoutFn(fn: Function, delay = 1000, immediate = true, clearEffectWhenStop = false) {
  const { start, ready, stop } = useTimeout(delay, immediate)
  let stopEffect: WatchStopHandle | undefined
  const startEffect = () => {
    stopEffect = watch(
      ready,
      (hasReady) => {
        hasReady && fn()
      },
      { flush: 'sync' }
    )
  }
  const _stop = () => {
    clearEffectWhenStop && stopEffect!()
    stop()
  }
  startEffect()
  return {
    start: () => {
      clearEffectWhenStop && startEffect()
      start()
    },
    stop: _stop
  }
}
Example #2
Source File: tools.ts    From trois with MIT License 6 votes vote down vote up
export function bindObjectProp(
  src: any,
  prop: string,
  dst: any,
  apply = true,
  setter?: OptionSetter
): WatchStopHandle {
  if (apply) applyObjectProps(dst, src[prop], setter)
  const r = toRef(src, prop)
  return watch(r, (value) => { applyObjectProps(dst, value, setter) })
}
Example #3
Source File: tools.ts    From trois with MIT License 6 votes vote down vote up
export function bindObjectProps(
  src: any,
  dst: any,
  apply = true,
  setter?: OptionSetter
): WatchStopHandle {
  if (apply) applyObjectProps(dst, src, setter)
  const r = ref(src)
  return watch(r, (value) => { applyObjectProps(dst, value, setter) }, { deep: true })
}
Example #4
Source File: PlayerMarker.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
private _playerUnwatch?: WatchStopHandle;
Example #5
Source File: PlayerMarker.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
private _imageUrlUnwatch?: WatchStopHandle;
Example #6
Source File: DynmapTileLayer.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
private _nightUnwatch: WatchStopHandle | null = null;
Example #7
Source File: DynmapTileLayer.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
private _updateUnwatch: WatchStopHandle | null = null;
Example #8
Source File: watchVerbose.ts    From formkit with MIT License 5 votes vote down vote up
/**
 *
 * @param obj - An object to observe at depth
 * @param callback - A callback that
 * @public
 */
export default function watchVerbose<
  T extends Ref<unknown> | Record<string, any>
>(
  obj: T,
  callback: (keypath: string[], value?: unknown, obj?: T) => void
): void {
  const watchers: Record<string, WatchStopHandle> = {}

  const applyWatch = (paths: ObjectPath[]): void => {
    // Watch each property
    for (const path of paths) {
      // Stops pre-existing watchers at a given location to prevent dupes:
      if (path.__str in watchers) watchers[path.__str]()
      watchers[path.__str] = watch(
        touch.bind(null, obj, path),
        dispatcher.bind(null, path),
        { deep: false }
      )
    }
  }

  /**
   * Clear any watchers deeper than this path.
   * @param path - The path to start from
   */
  const clearWatch = (path: ObjectPath) => {
    if (!path.length) return
    for (const key in watchers) {
      if (`${key}`.startsWith(`${path.__str}.`)) {
        watchers[key]()
        delete watchers[key]
      }
    }
  }

  const dispatcher = createDispatcher(obj, callback, applyWatch, clearWatch)
  applyWatch(getPaths(obj))
}
Example #9
Source File: useInput.ts    From formkit with MIT License 4 votes vote down vote up
/**
 * A composable for creating a new FormKit node.
 * @param type - The type of node (input, group, list)
 * @param attrs - The FormKit "props" — which is really the attrs list.
 * @returns
 * @public
 */
export function useInput(
  props: FormKitComponentProps,
  context: SetupContext<any>,
  options: FormKitOptions = {}
): FormKitNode {
  /**
   * The configuration options, these are provided by either the plugin or by
   * explicit props.
   */
  const config = Object.assign({}, inject(optionsSymbol) || {}, options)

  /**
   * The current instance.
   */
  const instance = getCurrentInstance()

  /**
   * Extracts the listeners.
   */
  const listeners = onlyListeners(instance?.vnode.props)

  /**
   * Determines if the prop is v-modeled.
   */
  const isVModeled = props.modelValue !== undefined

  /**
   * Determines if the object being passed as a v-model is reactive.
   */
  // const isReactiveVModel = isVModeled && isReactive(props.modelValue)

  /**
   * Define the initial component
   */
  const value: any =
    props.modelValue !== undefined
      ? props.modelValue
      : cloneAny(context.attrs.value)

  /**
   * Creates the node's initial props from the context, props, and definition
   * @returns
   */
  function createInitialProps(): Record<string, any> {
    const initialProps: Record<string, any> = {
      ...nodeProps(props),
      ...listeners,
    }
    const attrs = except(nodeProps(context.attrs), pseudoProps)
    initialProps.attrs = attrs
    const propValues = only(nodeProps(context.attrs), pseudoProps)
    for (const propName in propValues) {
      initialProps[camel(propName)] = propValues[propName]
    }
    const classesProps = { props: {} }
    classesToNodeProps(classesProps as FormKitNode, props)
    Object.assign(initialProps, classesProps.props)
    if (typeof initialProps.type !== 'string') {
      initialProps.definition = initialProps.type
      delete initialProps.type
    }
    return initialProps
  }

  /**
   * Create the FormKitNode.
   */
  const initialProps = createInitialProps()

  /**
   * The parent node.
   */
  const parent = initialProps.ignore
    ? null
    : props.parent || inject(parentSymbol, null)

  const node = createNode(
    extend(
      config || {},
      {
        name: props.name || undefined,
        value,
        parent,
        plugins: (config.plugins || []).concat(props.plugins),
        config: props.config,
        props: initialProps,
        index: props.index,
      },
      false,
      true
    ) as Partial<FormKitOptions>
  ) as FormKitNode

  /**
   * If no definition has been assigned at this point — we're out!
   */
  if (!node.props.definition) error(600, node)

  /**
   * All props that are bound "late" (after node creation) — are added to a set
   * which is used to watch the context.attrs object.
   */
  const lateBoundProps = ref<Set<string | RegExp>>(
    new Set(node.props.definition.props || [])
  )

  /**
   * Any additional props added at a "later" time should also be part of the
   * late bound props.
   */
  node.on('added-props', ({ payload: lateProps }) => {
    if (Array.isArray(lateProps))
      lateProps.forEach((newProp) => lateBoundProps.value.add(newProp))
  })

  /**
   * These prop names must be assigned.
   */
  const pseudoPropNames = computed(() =>
    pseudoProps.concat([...lateBoundProps.value]).reduce((names, prop) => {
      if (typeof prop === 'string') {
        names.push(camel(prop))
        names.push(kebab(prop))
      } else {
        names.push(prop)
      }
      return names
    }, [] as Array<string | RegExp>)
  )

  /* Splits Classes object into discrete props for each key */
  watchEffect(() => classesToNodeProps(node, props))

  /**
   * The props object already has properties even if they start as "undefined"
   * so we can loop over them and individual watchEffect to prevent responding
   * inappropriately.
   */
  const passThrough = nodeProps(props)
  for (const prop in passThrough) {
    watch(
      () => props[prop as keyof FormKitComponentProps],
      () => {
        if (props[prop as keyof FormKitComponentProps] !== undefined) {
          node.props[prop] = props[prop as keyof FormKitComponentProps]
        }
      }
    )
  }

  /**
   * Watch "pseudoProp" attributes explicitly.
   */
  const attributeWatchers = new Set<WatchStopHandle>()
  const possibleProps = nodeProps(context.attrs)
  watchEffect(() => {
    watchAttributes(only(possibleProps, pseudoPropNames.value))
  })

  /**
   * Defines attributes that should be used as props.
   * @param attrProps - Attributes that should be used as props instead
   */
  function watchAttributes(attrProps: Record<string, any>) {
    attributeWatchers.forEach((stop) => {
      stop()
      attributeWatchers.delete(stop)
    })
    for (const prop in attrProps) {
      const camelName = camel(prop)
      attributeWatchers.add(
        watch(
          () => context.attrs[prop],
          () => {
            node.props[camelName] = context.attrs[prop]
          }
        )
      )
    }
  }

  /**
   * Watch and dynamically set attribute values, those values that are not
   * props and are not pseudoProps
   */
  watchEffect(() => {
    const attrs = except(nodeProps(context.attrs), pseudoPropNames.value)
    node.props.attrs = Object.assign({}, node.props.attrs || {}, attrs)
  })

  /**
   * Add any/all "prop" errors to the store.
   */
  watchEffect(() => {
    const messages = props.errors.map((error) =>
      createMessage({
        key: slugify(error),
        type: 'error',
        value: error,
        meta: { source: 'prop' },
      })
    )
    node.store.apply(
      messages,
      (message) => message.type === 'error' && message.meta.source === 'prop'
    )
  })

  /**
   * Add input errors.
   */
  if (node.type !== 'input') {
    const sourceKey = `${node.name}-prop`
    watchEffect(() => {
      const keys = Object.keys(props.inputErrors)
      const messages = keys.reduce((messages, key) => {
        let value = props.inputErrors[key]
        if (typeof value === 'string') value = [value]
        if (Array.isArray(value)) {
          messages[key] = value.map((error) =>
            createMessage({
              key: error,
              type: 'error',
              value: error,
              meta: { source: sourceKey },
            })
          )
        }
        return messages
      }, {} as Record<string, FormKitMessage[]>)
      node.store.apply(
        messages,
        (message) =>
          message.type === 'error' && message.meta.source === sourceKey
      )
    })
  }

  /**
   * Watch the config prop for any changes.
   */
  watchEffect(() => Object.assign(node.config, props.config))

  /**
   * Produce another parent object.
   */
  if (node.type !== 'input') {
    provide(parentSymbol, node)
  }

  let inputTimeout: number | undefined

  // eslint-disable-next-line @typescript-eslint/ban-types
  const mutex = new WeakSet<object>()

  /**
   * Explicitly watch the input value, and emit changes (lazy)
   */
  node.on('modelUpdated', () => {
    // Emit the values after commit
    context.emit('inputRaw', node.context?.value, node)
    clearTimeout(inputTimeout)
    inputTimeout = setTimeout(
      context.emit,
      20,
      'input',
      node.context?.value,
      node
    ) as unknown as number

    if (isVModeled && node.context) {
      const newValue = useRaw(node.context.value)
      if (isObject(newValue) && useRaw(props.modelValue) !== newValue) {
        // If this is an object that has been mutated inside FormKit core then
        // we know when it is emitted it will "return" in the watchVerbose so
        // we pro-actively add it to the mutex.
        mutex.add(newValue)
      }
      context.emit('update:modelValue', newValue)
    }
  })

  /**
   * Enabled support for v-model, using this for groups/lists is not recommended
   */
  if (isVModeled) {
    watchVerbose(toRef(props, 'modelValue'), (path, value): void | boolean => {
      const rawValue = useRaw(value)
      if (isObject(rawValue) && mutex.has(rawValue)) {
        return mutex.delete(rawValue)
      }
      if (!path.length) node.input(value, false)
      else node.at(path)?.input(value, false)
    })
  }

  /**
   * When this input shuts down, we need to "delete" the node too.
   */
  onUnmounted(() => node.destroy())

  return node
}