vue#watch TypeScript Examples

The following examples show how to use vue#watch. 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: utils.ts    From hexon with GNU General Public License v3.0 7 votes vote down vote up
function useResize(elRef: Ref<HTMLElement | null>, rect: Ref<IRect>) {
  const removeEventListenerFnMap: Map<() => void, () => void> = new Map()
  const removeAllEventListener = () => {
    for (const [, fn] of removeEventListenerFnMap) {
      fn()
    }
    removeEventListenerFnMap.clear()
  }
  watch(
    () => unref(elRef.value),
    (el) => {
      removeAllEventListener()
      if (!el) return
      const resiableNodesSet: Set<Element | Document> = new Set()
      let cursor: Element | Document | null = el
      while (true) {
        cursor = getScrollParent(cursor)
        if (cursor === null) break
        resiableNodesSet.add(cursor)
      }
      for (const node of [...resiableNodesSet, window]) {
        const onResize = () => {
          if (!elRef.value) return
          rect.value = getRect(elRef.value)
        }
        node.addEventListener("resize", onResize)
        removeEventListenerFnMap.set(onResize, () => {
          node.removeEventListener("resize", onResize)
        })
      }
    },
    {
      immediate: true,
    }
  )
  onBeforeUnmount(() => {
    removeAllEventListener()
  })
}
Example #2
Source File: reactivity-utils.ts    From quantum-sheet with GNU General Public License v3.0 7 votes vote down vote up
export function untilDefined<T>(source: Ref<T>): Promise<T> {
  return new Promise((resolve) => {
    const stopHandle = watch(source, (value) => {
      if (value !== undefined && value !== null) {
        stopHandle()
        resolve(value)
      }
    })
  })
}
Example #3
Source File: composer.test.ts    From vue-i18n-next with MIT License 6 votes vote down vote up
describe('locale', () => {
  test('default value', () => {
    const { locale } = createComposer({})
    expect(locale.value).toEqual('en-US')
  })

  test('initialize at composer creating', () => {
    const { locale } = createComposer({ locale: 'ja' })
    expect(locale.value).toEqual('ja')
  })

  test('reactivity', async () => {
    const fn = jest.fn()

    const { locale } = createComposer({})
    watch(locale, fn)
    locale.value = 'en'
    await nextTick()

    expect(fn).toBeCalled()
    expect(fn.mock.calls[0][0]).toEqual('en')
    expect(fn.mock.calls[0][1]).toEqual('en-US')
  })
})
Example #4
Source File: scroll.ts    From hexon with GNU General Public License v3.0 6 votes vote down vote up
export function useOnParentScroll(
  elRef: Ref<HTMLElement | null>,
  onScroll: () => void
) {
  const removeEventListenerFnMap: Map<() => void, () => void> = new Map()
  const removeAllEventListener = () => {
    for (const [, fn] of removeEventListenerFnMap) {
      fn()
    }
    removeEventListenerFnMap.clear()
  }
  watch(
    () => elRef.value,
    (el) => {
      removeAllEventListener()
      if (!el) return
      const scrollableNodesSet: Set<Element | Document> = new Set()
      let cursor: Element | Document | null = el
      while (true) {
        cursor = getScrollParent(cursor)
        if (cursor === null) break
        scrollableNodesSet.add(cursor)
      }
      for (const node of scrollableNodesSet) {
        node.addEventListener("scroll", onScroll)
        removeEventListenerFnMap.set(onScroll, () => {
          node.removeEventListener("scroll", onScroll)
        })
      }
    },
    {
      immediate: true,
    }
  )
  onBeforeUnmount(() => {
    removeAllEventListener()
  })
}
Example #5
Source File: use-false-until-truthy.ts    From vooks with MIT License 6 votes vote down vote up
export default function useFalseUntilTruthy (originalRef: Ref<any>): Readonly<Ref<boolean>> {
  const currentRef = ref(!!(originalRef.value as boolean))
  if (currentRef.value) return readonly(currentRef)
  const stop = watch(originalRef, (value: any) => {
    if (value as boolean) {
      currentRef.value = true
      stop()
    }
  })
  return readonly(currentRef)
}
Example #6
Source File: useDebounceFn.ts    From vhook with MIT License 6 votes vote down vote up
export function useDebounceFn<T extends (...rest: any[]) => any>(fn: T, delay = 200) {
  const debounceValue = useDebounce(0, delay)
  let params: Parameters<T>

  watch(
    debounceValue,
    () => {
      fn(...params)
    },
    { flush: 'sync' }
  )
  return function (...rest: Parameters<T>) {
    params = rest
    debounceValue.value++
  }
}
Example #7
Source File: vue.ts    From keen-slider with MIT License 6 votes vote down vote up
export function useKeenSlider<
  T extends HTMLElement,
  O = {},
  P = {},
  H extends string = KeenSliderHooks
>(
  options: Ref<KeenSliderOptions<O, P, H>> | KeenSliderOptions<O, P, H>,
  plugins?: KeenSliderPlugin<O, P, H>[]
): [Ref<T | undefined>, Ref<KeenSliderInstance<O, P, H> | undefined>] {
  const container = ref<T>()
  const slider = ref<KeenSliderInstance<O, P, H>>()

  if (isRef(options)) {
    watch(options, (newOptions, _) => {
      if (slider.value) slider.value.update(newOptions)
    })
  }

  onMounted(() => {
    if (container.value)
      slider.value = new KeenSlider<O, P, H>(
        container.value,
        isRef(options) ? options.value : options,
        plugins
      )
  })

  onUnmounted(() => {
    if (slider.value) slider.value.destroy()
  })

  return [container, slider]
}
Example #8
Source File: use-title.ts    From fect with MIT License 6 votes vote down vote up
useTitle = (initialTitle = '') => {
  const [title, setTitle] = useState<string>(initialTitle)

  const titleChange = (title = '') => setTitle(title)

  const setDocumentTitle = () => (document.title = title.value)
  const resetDocumentTitle = () => (document.title = '')

  onMounted(setDocumentTitle)

  watch(title, setDocumentTitle)

  onBeforeUnmount(resetDocumentTitle)
  onDeactivated(resetDocumentTitle)

  return {
    titleChange,
    title
  }
}
Example #9
Source File: expression-element.ts    From quantum-sheet with GNU General Public License v3.0 6 votes vote down vote up
private updateGetters(getterNames: ReadonlySet<string>) {
    const namesToAdd = new Set<string>(getterNames)
    this.getters.forEach((getter, variableName) => {
      if (!namesToAdd.has(variableName)) {
        // Remove getters that aren't needed anymore
        getter.remove()
        this.getters.delete(variableName)
      } else {
        // Don't double-add names
        namesToAdd.delete(variableName)
      }
    })

    if (namesToAdd.size <= 0) return

    const scope = this.scope.value
    assert(scope, 'Expected the block to have a scope')
    namesToAdd.forEach((variableName) => {
      const newGetter = scope.addGetter(variableName, this.blockPosition)
      watch(newGetter.data, (value) => {
        this.clearResultAndVariables()
        if (value !== undefined && value !== null) this.evaluateLater()
      })
      this.getters.set(variableName, newGetter)
    })
  }
Example #10
Source File: useResize.ts    From S2 with MIT License 6 votes vote down vote up
useResize = (
  s2Ref: Ref<SpreadSheet | undefined>,
  props: BaseSheetProps,
  dom: {
    wrapperRef: Ref<HTMLDivElement | undefined>;
    containerRef: Ref<HTMLDivElement | undefined>;
  },
) => {
  const unobserve = ref<() => void>();

  watch(
    [s2Ref, () => props.adaptive],
    ([s2, adaptive], _, onCleanup) => {
      if (!s2) {
        return;
      }
      unobserve.value = createResizeObserver({
        s2,
        adaptive,
        wrapper: dom.wrapperRef.value!,
        container: dom.containerRef.value!,
      });

      onCleanup(() => {
        unobserve.value?.();
      });
    },
    { deep: true },
  );
}
Example #11
Source File: tools.ts    From trois with MIT License 6 votes vote down vote up
export function bindProp(src: any, srcProp: string, dst: any, dstProp?: string): void {
  const _dstProp = dstProp || srcProp
  const ref = toRef(src, srcProp)
  if (ref.value instanceof Object) {
    setFromProp(dst[_dstProp], ref.value)
    watch(ref, (value) => { setFromProp(dst[_dstProp], value) }, { deep: true })
  } else {
    if (ref.value !== undefined) dst[_dstProp] = src[srcProp]
    watch(ref, (value) => { dst[_dstProp] = value })
  }
}
Example #12
Source File: reactivity-utils.ts    From quantum-sheet with GNU General Public License v3.0 6 votes vote down vote up
watchImmediate: typeof watch = function (source: any, callback: any, options?: any) {
  if (!options) {
    options = {}
  }
  options.immediate = true
  return watch(source, callback, options)
}
Example #13
Source File: use-memo.ts    From vooks with MIT License 6 votes vote down vote up
function useMemo<T> (
  getterOrOptions: MemoGetter<T> | WritableMemoOptions<T>
): ComputedRef<T> | WritableComputedRef<T> {
  const computedValueRef = computed(getterOrOptions as any) as
    | WritableComputedRef<T>
    | ComputedRef<T>
  // Maybe it's not possible to lazy evaluate the value, since we can't make
  // render phase capture the deps behind useMemo
  const valueRef = ref(computedValueRef.value) as Ref<T>
  watch(computedValueRef, (value) => {
    valueRef.value = value
  })
  if (typeof getterOrOptions === 'function') {
    return valueRef as ComputedRef<T>
  } else {
    return ({
      __v_isRef: true,
      get value () {
        return valueRef.value
      },
      set value (v: T) {
        (getterOrOptions as WritableMemoOptions<T>).set(v)
      }
    } as unknown) as WritableComputedRef<T>
  }
}
Example #14
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 #15
Source File: useTitle.ts    From vite-vue3-ts with MIT License 6 votes vote down vote up
/**
 * Listening to page changes and dynamically changing site titles
 */
export function useTitle() {
  const { currentRoute } = useRouter();

  const pageTitle = usePageTitle();

  watch(
    [() => currentRoute.value.path],
    () => {
      const route = unref(currentRoute);

      const tTitle = route?.meta?.title as string;
      pageTitle.value = tTitle;
    },
    { immediate: true },
  );
}
Example #16
Source File: scope-element.ts    From quantum-sheet with GNU General Public License v3.0 6 votes vote down vote up
/*const imports = computed(() => {
    variables.forEach((value, key) => {
      if(value[0].getters.length > 0) {
        .push()
      }
    });
  })*/

  private createVariableArray(name: string): ScopedVariable[] {
    // First variable, used to import values from the scope above
    const importerVariable: ScopedVariable = reactive({
      position: computed(() => this.position.value),
      index: 0,
      data: shallowRef(),
      getters: [],
    })

    const newVariableArray = reactive([importerVariable])
    // Cleanup if unused
    watch([() => newVariableArray.length, () => importerVariable.getters.length], ([variableArrayLength, gettersLength]) => {
      if (variableArrayLength <= 1 && gettersLength == 0) {
        this._variableMap.delete(name)
      }
    })

    this._variableMap.set(name, newVariableArray)
    return newVariableArray
  }
Example #17
Source File: LayerManager.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
constructor(map: Map) {
		const showControl = computed(() => useStore().state.components.layerControl);
		this.map = map;
		this.layerControl = new LiveAtlasLayerControl({}, {},{
			position: 'topleft',
		});

		if(showControl.value) {
			this.map.addControl(this.layerControl);
		}

		watch(showControl, (show) => {
			if(show) {
				this.map.addControl(this.layerControl);
			} else {
				this.map.removeControl(this.layerControl);
			}
		})
	}
Example #18
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 #19
Source File: useData.ts    From jz-gantt with MIT License 5 votes vote down vote up
export function useInitData(
  data: Ref<Array<any>>,
  options: ComputedRef<DataOptions>
) {
  const store = useStore();
  const { GtData } = store;

  const { setHeaders } = useSetGanttHeader();
  const { IFClickRow } = useRootEmit();

  // 处理数据
  GtData.initData(data.value, options.value);

  const allData = computed(() => GtData.flatData as Row[]);

  // 监听数据变化
  watch(
    () => data,
    val => {
      let item = null as Row | null;

      // 先判断选中的内容
      const select = GtData.selected.index;
      if (select > -1) item = allData.value[select];

      GtData.update(val.value, item, options.value);
      setHeaders();

      // 数据发生变化,如果 selectIndex 变为 -1,表示数据已经被删除,选择的行内容需要抛出清空
      if (select > -1 && GtData.selected.index === -1) {
        IFClickRow(undefined);
      }
    },
    { deep: true }
  );

  return {
    allData
  };
}
Example #20
Source File: directive.ts    From vue3-gettext with MIT License 5 votes vote down vote up
/**
 * A directive to translate content according to the current language.
 *
 * Use this directive instead of the component if you need to translate HTML content.
 * It's too tricky to support HTML content within the component because we cannot get the raw HTML to use as `msgid`.
 *
 * This directive has a similar interface to the <translate> component, supporting
 * `translate-comment`, `translate-context`, `translate-plural`, `translate-n`.
 *
 * `<p v-translate translate-comment='Good stuff'>This is <strong class='txt-primary'>Sparta</strong>!</p>`
 *
 * If you need interpolation, you must add an expression that outputs binding value that changes with each of the
 * context variable:
 * `<p v-translate="fullName + location">I am %{ fullName } and from %{ location }</p>`
 * @deprecated
 */
export default function directive(language: Language): ObjectDirective<HTMLElement, any> {
  const update = (el: HTMLElement, binding: DirectiveBinding, vnode: VNode) => {
    // Store the current language in the element's dataset.
    el.dataset.currentLanguage = language.current;
    updateTranslation(language, el, binding, vnode);
  };
  return {
    beforeMount(el: HTMLElement, binding: DirectiveBinding, vnode: VNode) {
      // Get the raw HTML and store it in the element's dataset (as advised in Vue's official guide).
      if (!el.dataset.msgid) {
        el.dataset.msgid = el.innerHTML;
      }

      watch(language, () => {
        update(el, binding, vnode);
      });

      update(el, binding, vnode);
    },
    updated(el: HTMLElement, binding: DirectiveBinding, vnode: VNode) {
      update(el, binding, vnode);
    },
  };
}
Example #21
Source File: Material.ts    From trois with MIT License 5 votes vote down vote up
BaseMaterial = defineComponent({
  emits: ['created'],
  props: {
    color: { type: String, default: '#ffffff' },
    props: { type: Object as PropType<MaterialPropsInterface>, default: () => ({}) },
  },
  inject: {
    mesh: MeshInjectionKey as symbol,
  },
  setup(): MaterialSetupInterface {
    return {}
  },
  provide() {
    return {
      [MaterialInjectionKey as symbol]: this,
    }
  },
  created() {
    if (!this.mesh) {
      console.error('Missing parent Mesh')
      return
    }

    if (this.createMaterial) {
      const material = this.material = this.createMaterial()
      // @ts-ignore
      watch(() => this.color, (value) => { material.color.set(value) })
      bindObjectProp(this, 'props', material, false, this.setProp)
      this.$emit('created', material)
      this.mesh.setMaterial(material)
    }
  },
  unmounted() {
    this.material?.dispose()
  },
  methods: {
    getMaterialParams() {
      return { ...propsValues(this.$props, ['props']), ...this.props }
    },
    setProp(material: any, key: string, value: any, needsUpdate = false) {
      const dstVal = material[key]
      if (dstVal instanceof Color) dstVal.set(value)
      else material[key] = value
      material.needsUpdate = needsUpdate
    },
    setTexture(texture: Texture | null, key = 'map') {
      this.setProp(this.material, key, texture, true)
    },
  },
  render() {
    return this.$slots.default ? this.$slots.default() : []
  },
  __hmrId: 'Material',
})
Example #22
Source File: watch.ts    From theila with Mozilla Public License 2.0 5 votes vote down vote up
constructor(client: Client, items?: any, callback?: any) {
    this.client = client;
    this.handler = this.handleReconnect.bind(this);

    this.loading = ref(false);
    this.err = ref("");
    this.running = ref(false);
    this.sort = ref(defaultCompareFunc(this));

    if(items) {
      this.items = items;

      watch(this.sort, () => {
        this.items.value.sort(this.sort.value);
      });
    }

    this.callback = (message: Message) => {
      const spec = JSON.parse(message.spec);
      let index = 0;
      let foundIndex = -1;

      if(!message.metadata || message.metadata.uid != this.uid) {
        return;
      }

      if(message.kind == Kind.EventError) {
        this.stop();
        this.err.value = spec;
        return;
      }

      if(callback)
        callback(message, spec);

      if(!this.items)
        return;

      switch(message.kind) {
        case Kind.EventItemAdd:
          foundIndex = this.findIndex(spec);
          if(foundIndex != -1) {
            return;
          }

          index = getInsertionIndex(this.items.value, spec, this.sort.value);

          this.items.value.splice(index, 0, spec);

          break;
        case Kind.EventItemDelete:
          foundIndex = this.findIndex(spec);
          if(foundIndex != -1) {
            this.items.value.splice(foundIndex, 1);
          }
          break;
        case Kind.EventItemUpdate:
          foundIndex = this.findIndex(spec["old"]);
          if(foundIndex != -1) {
            this.items.value[foundIndex] = spec["new"];
          }
          break;
      }
    };
  }
Example #23
Source File: Geometry.ts    From trois with MIT License 5 votes vote down vote up
Geometry = defineComponent({
  emits: ['created'],
  props: {
    rotateX: Number,
    rotateY: Number,
    rotateZ: Number,
    attributes: { type: Array as PropType<Array<GeometryAttributeInterface>>, default: () => ([]) },
  },
  // inject for sub components
  inject: {
    mesh: MeshInjectionKey as symbol,
  },
  setup(): GeometrySetupInterface {
    return {}
  },
  created() {
    if (!this.mesh) {
      console.error('Missing parent Mesh')
      return
    }

    this.createGeometry()
    this.rotateGeometry()
    if (this.geometry) this.mesh.setGeometry(this.geometry)

    Object.keys(this.$props).forEach(prop => {
      // @ts-ignore
      watch(() => this[prop], this.refreshGeometry)
    })
  },
  unmounted() {
    this.geometry?.dispose()
  },
  methods: {
    createGeometry() {
      const bufferAttributes: Record<string, unknown> = {}
      const geometry = new BufferGeometry()
      this.attributes.forEach(attribute => {
        if (attribute.name && attribute.itemSize && attribute.array) {
          const bufferAttribute = bufferAttributes[attribute.name] = new BufferAttribute(attribute.array, attribute.itemSize, attribute.normalized)
          geometry.setAttribute(attribute.name, bufferAttribute)
        }
      })
      geometry.computeBoundingBox()
      geometry.userData.component = this
      this.geometry = geometry
      this.$emit('created', geometry)
    },
    rotateGeometry() {
      if (!this.geometry) return
      if (this.rotateX) this.geometry.rotateX(this.rotateX)
      if (this.rotateY) this.geometry.rotateY(this.rotateY)
      if (this.rotateZ) this.geometry.rotateZ(this.rotateZ)
    },
    refreshGeometry() {
      const oldGeo = this.geometry
      this.createGeometry()
      this.rotateGeometry()
      if (this.geometry && this.mesh) this.mesh.setGeometry(this.geometry)
      oldGeo?.dispose()
    },
  },
  render() { return [] },
})
Example #24
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 #25
Source File: theme.ts    From hexon with GNU General Public License v3.0 5 votes vote down vote up
export function useMonacoTheme() {
  const vars = useThemeVars()
  const custom = computed(() => {
    return {
      base: (vars.value.isDark
        ? "vs-dark"
        : "vs") as monaco.editor.BuiltinTheme,
      inherit: true,
      rules: [
        {
          foreground: removeHash(vars.value.textColorSecondary),
          token: "comment.content.md",
        },
        {
          foreground: removeHash(vars.value.textColorSecondary),
          token: "comment.md",
        },
        {
          foreground: removeHash(vars.value.textColorPrimary),
          token: "string.md",
        },
        {
          // 链接
          foreground: removeHash(vars.value.colorPrimary),
          token: "string.link.md",
          fontStyle: "blod",
        },
        {
          // 标题
          foreground: removeHash(vars.value.colorPrimary),
          token: "keyword.md",
        },
        {
          // 标题
          foreground: removeHash(vars.value.colorPrimary),
          token: "keyword",
        },
        {
          foreground: removeHash(vars.value.colorPrimary),
          fontStyle: "bold",
          token: "variable.md",
        },
      ],
      colors: {
        "editor.foreground": vars.value.textColorPrimary,
        "editor.background": vars.value.backgroundColorPrimary,
        "editorCursor.foreground": vars.value.colorPrimary,
        "editor.selectionBackground": vars.value.isDark
          ? "#ffffff35"
          : "#00000015",
      },
    }
  })
  const update = () => {
    monaco.editor.defineTheme("hexon", custom.value)
  }
  watch(
    () => custom.value,
    () => {
      update()
    },
    { immediate: true, deep: true }
  )
}
Example #26
Source File: LiveAtlasLayerControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
_initLayout() {
		const className = 'leaflet-control-layers',
			container = this._container = DomUtil.create('div', className),
			section = this._section = DomUtil.create('section', className + '-list'),
			button = this._layersButton = DomUtil.create('button', className + '-toggle', container);

		DomEvent.disableClickPropagation(container);
		DomEvent.disableScrollPropagation(container);

		//Open layer list on ArrowRight from button
		DomEvent.on(button,'keydown', (e: Event) => {
			if((e as KeyboardEvent).key === 'ArrowRight') {
				store.commit(MutationTypes.SET_UI_ELEMENT_VISIBILITY, {element: 'layers', state: true});
			}
		});

		DomEvent.on(container, 'keydown', (e: Event) => {
			//Close layer list on ArrowLeft from within list
			if((e as KeyboardEvent).key === 'ArrowLeft') {
				e.preventDefault();
				store.commit(MutationTypes.SET_UI_ELEMENT_VISIBILITY, {element: 'layers', state: false});
				nextTick(() => button.focus());
			}

			const elements = Array.from(container.querySelectorAll('input')) as HTMLElement[];
			handleKeyboardEvent(e as KeyboardEvent, elements);
		});
		DomEvent.on(button,'click', () => store.commit(MutationTypes.TOGGLE_UI_ELEMENT_VISIBILITY, 'layers'));

		section.style.display = 'none';

		button.title = store.state.messages.layersTitle;
		button.setAttribute('aria-expanded', 'false');
		button.innerHTML = `
			<svg class="svg-icon" aria-hidden="true">
			  <use xlink:href="#icon--layers" />
			</svg>`;


		//Use vuex track expanded state
		watch(store.state.ui.visibleElements, (newValue) => {
			if(newValue.has('layers') && !this.visible) {
				this.expand();
			} else if(this.visible && !newValue.has('layers')) {
				this.collapse();
			}

			this.visible = store.state.ui.visibleElements.has('layers');
		});

		watch(store.state.messages, (newValue) => (button.title = newValue.layersTitle));//

		this.visible = store.state.ui.visibleElements.has('layers');

		if (this.visible) {
			this.expand();
		}

		this._baseLayersList = DomUtil.create('div', className + '-base', section);
		this._separator = DomUtil.create('div', className + '-separator', section);
		this._overlaysList = DomUtil.create('div', className + '-overlays', section);

		container.appendChild(section);

		window.addEventListener('resize', () => this.handleResize());
		this.handleResize();
	}
Example #27
Source File: FormKitSchema.ts    From formkit with MIT License 5 votes vote down vote up
FormKitSchema = defineComponent({
  name: 'FormKitSchema',
  props: {
    schema: {
      type: [Array, Object] as PropType<
        FormKitSchemaNode[] | FormKitSchemaCondition
      >,
      required: true,
    },
    data: {
      type: Object as PropType<Record<string, any>>,
      default: () => ({}),
    },
    library: {
      type: Object as PropType<FormKitComponentLibrary>,
      default: () => ({}),
    },
  },
  setup(props, context) {
    const instance = getCurrentInstance()
    let instanceKey = Symbol(String(i++))
    instanceScopes.set(instanceKey, [])
    let provider = parseSchema(props.library, props.schema)
    let render: RenderChildren
    let data: Record<string, any>
    // Re-parse the schema if it changes:
    watch(
      () => props.schema,
      (newSchema, oldSchema) => {
        instanceKey = Symbol(String(i++))
        provider = parseSchema(props.library, props.schema)
        render = createRenderFn(provider, data, instanceKey)
        if (newSchema === oldSchema) {
          // In this edge case, someone pushed/modified something in the schema
          // and we've successfully re-parsed, but since the schema is not
          // referenced in the render function it technically isnt a dependency
          // and we need to force a re-render since we swapped out the render
          // function completely.
          ;(instance?.proxy?.$forceUpdate as unknown as CallableFunction)()
        }
      },
      { deep: true }
    )

    // Watch the data object explicitly
    watchEffect(() => {
      data = Object.assign(reactive(props.data), {
        slots: context.slots,
      })
      render = createRenderFn(provider, data, instanceKey)
    })
    return () => render()
  },
})
Example #28
Source File: useEventListener.ts    From vite-vue3-ts with MIT License 5 votes vote down vote up
export function useEventListener({
  el = window,
  name,
  listener,
  options,
  autoRemove = true,
  isDebounce = true,
  wait = 80,
}: UseEventParams): { removeEvent: RemoveEventFn } {
  /* eslint-disable-next-line */
  let remove: RemoveEventFn = () => {};
  const isAddRef = ref(false);

  if (el) {
    const element = ref(el as Element) as Ref<Element>;

    const handler = isDebounce ? useDebounceFn(listener, wait) : useThrottleFn(listener, wait);
    const realHandler = wait ? handler : listener;
    const removeEventListener = (e: Element) => {
      isAddRef.value = true;
      e.removeEventListener(name, realHandler, options);
    };
    const addEventListener = (e: Element) => e.addEventListener(name, realHandler, options);

    const removeWatch = watch(
      element,
      (v, _ov, cleanUp) => {
        if (v) {
          !unref(isAddRef) && addEventListener(v);
          cleanUp(() => {
            autoRemove && removeEventListener(v);
          });
        }
      },
      { immediate: true },
    );

    remove = () => {
      removeEventListener(element.value);
      removeWatch();
    };
  }
  return { removeEvent: remove };
}
Example #29
Source File: use-theme.ts    From fect with MIT License 5 votes vote down vote up
useTheme = () => {
  const themes = [THEMES.LIGHT, THEMES.DARK]

  const getClientTheme = () => {
    const storageTheme = localStorage.getItem(THEME_STORAGE_KEY)
    if (storageTheme) return storageTheme === THEMES.DARK ? THEMES.DARK : THEMES.LIGHT
    if (window.matchMedia(DARK_THEME_QUERY).matches) return THEMES.DARK
    if (window.matchMedia(LIGHT_THEME_QUERY).matches) return THEMES.LIGHT
    return THEMES.LIGHT
  }

  const set = (newTheme: Theme) => {
    if (themes.includes(newTheme) && newTheme !== theme.value) {
      theme.value = newTheme
    }
  }

  const themeChange = () => {
    const nextTheme = theme.value === THEMES.DARK ? THEMES.LIGHT : THEMES.DARK
    set(nextTheme)
  }

  onMounted(() => {
    if (typeof window === 'undefined' || !window.localStorage) return
    const theme = getClientTheme()
    set(theme)
  })

  watch(theme, (cur) => {
    if (typeof window === 'undefined' || !window.localStorage) return
    if (!cur) return
    localStorage.setItem('theme', cur)
    const root = document.querySelector('html') as HTMLElement
    root.setAttribute('class', cur)
  })

  return {
    themeChange,
    theme: readonly(theme)
  }
}