vue#onMounted TypeScript Examples

The following examples show how to use vue#onMounted. 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: util.ts    From vhook with MIT License 7 votes vote down vote up
export function tryOnMounted(cb: () => any): void {
  const instance = getCurrentInstance()
  if (instance) {
    if (instance?.isMounted) {
      cb()
    } else {
      onMounted(cb)
    }
  }
}
Example #2
Source File: components.ts    From vite-ssr with MIT License 6 votes vote down vote up
ClientOnly = defineComponent({
  name: 'ClientOnly',
  setup(_, { slots }) {
    const show = ref(false)
    onMounted(() => {
      show.value = true
    })

    return () => (show.value && slots.default ? slots.default() : null)
  },
})
Example #3
Source File: usePlocState.ts    From frontend-clean-architecture with MIT License 6 votes vote down vote up
export function usePlocState<S>(ploc: Ploc<S>): DeepReadonly<Ref<S>> {
    const state = ref(ploc.state) as Ref<S>;

    const stateSubscription = (newState: S) => {
        state.value = newState;
    };

    onMounted(() => {
        ploc.subscribe(stateSubscription);
    });

    onUnmounted(() => {
        ploc.unsubscribe(stateSubscription);
    });

    return readonly(state);
}
Example #4
Source File: useRight.ts    From am-editor with MIT License 6 votes vote down vote up
useRight = (button: Ref<HTMLElement | null>) => {
	const isRight = ref(false);

	onMounted(() => {
		if (button.value && isMobile) {
			const rect = button.value.getBoundingClientRect();
			isRight.value = rect.left > window.visualViewport.width / 2;
		}
	});

	return isRight;
}
Example #5
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 #6
Source File: useResize.ts    From jz-gantt with MIT License 6 votes vote down vote up
/**
 * 监听甘特横向大小变化
 */
export function useResizeGanttObserver() {
  const { initGanttWidth, setHeaders } = useSetGanttHeader();
  const { ganttRef } = useGanttRef();

  const ganttResizeObserver = ref<ResizeObserver>();

  onBeforeMount(() => {
    ganttResizeObserver.value = new ResizeObserver(entries => {
      // eslint-disable-next-line no-restricted-syntax
      for (const entry of entries) {
        initGanttWidth.value = entry.contentRect.width;
        setHeaders();
      }
    });
  });

  onMounted(() => {
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    ganttRef?.value && ganttResizeObserver.value?.observe(ganttRef.value);
  });

  onUnmounted(() => {
    ganttResizeObserver.value = undefined;
  });

  return {};
}
Example #7
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 #8
Source File: use-event-listener.ts    From fect with MIT License 6 votes vote down vote up
useEventListener = (
  event: EventTypes,
  listener: EventListenerOrEventListenerObject,
  options: Options = {}
) => {
  const { target = window, ...rest } = options

  const remove = (el: Options['target']) => {
    const _el = unref(el)
    _el && _el.removeEventListener(event, listener, rest)
  }

  const add = (el: Options['target']) => {
    const _el = unref(el)
    _el && _el.addEventListener(event, listener, rest)
  }

  watch(
    () => unref(target),
    (el, prevEl) => {
      remove(prevEl)
      add(el)
    }
  )

  onMounted(() => add(target))
  onDeactivated(() => remove(target))
  onBeforeUnmount(() => remove(target))
}
Example #9
Source File: use-mount.ts    From fect with MIT License 6 votes vote down vote up
useMounted = (fns: MountedFn[]) => {
  if (!isArray(fns)) {
    console.log('[Fect] useMounted must entry array')
    return
  }

  const filterFunc = (fns: MountedFn[]) => {
    const single = len(fns) === 1
    if (single)
      return {
        start: fns[0],
        end: fns[0]
      }
    const [start, ...ends] = fns
    return {
      start,
      end: ends
    }
  }

  const { start, end } = filterFunc(fns)

  onMounted(start)

  onBeforeUnmount(() => {
    if (isArray(end)) {
      end.forEach((_) => _.apply(null))
      return
    }
    end()
    return
  })
}
Example #10
Source File: useBreadcrumbTitle.ts    From vite-vue3-ts with MIT License 6 votes vote down vote up
useBreadcrumbTitle = (isAddOn = true) => {
  const route = useRoute();
  const title = ref(route.meta.title);

  watch(
    () => route.meta.title,
    (val) => {
      title.value = val;
    },
  );

  const changeTitle = (val: string) => (title.value = val);

  onMounted(() => isAddOn && emitter.on(key, changeTitle));

  onUnmounted(() => isAddOn && emitter.off(key, changeTitle));

  const setBreadcrumbTitle = (title: string) => emitter.emit(key, title);

  return {
    title,
    setBreadcrumbTitle,
  };
}
Example #11
Source File: on-fonts-ready.ts    From vooks with MIT License 6 votes vote down vote up
/**
 * Call callback on fontsReady is resolved. If fontsReady is already resolved,
 * callback won't be called.
 */
export default function onFontsReady (cb: () => any): void {
  /* istanbul ignore next */
  if (isFontReady) return
  let deactivated = false
  onMounted(() => {
    /* istanbul ignore next */
    if (!isFontReady) {
      fontsReady?.then(() => {
        if (deactivated) return
        cb()
      })
    }
  })
  onBeforeUnmount(() => {
    deactivated = true
  })
}
Example #12
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)
  }
}
Example #13
Source File: useDato.ts    From vue-datocms with MIT License 5 votes vote down vote up
export function useDato({
  query,
  variables,
  baseUrl,
  preview,
  environment,
  apiToken,
}: UseDatoParams) {
  const data = ref<Record<string, any> | null>(null);
  const loading = ref<boolean>(false);
  const error = ref<string | null>(null);

  onMounted(async () => {
    loading.value = true;
    data.value = null;
    error.value = null;

    let endpoint = baseUrl || "https://graphql.datocms.com";

    if (environment) {
      endpoint += `/environments/${environment}`;
    }

    if (preview) {
      endpoint += `/preview`;
    }

    try {
      const response = await fetch(endpoint, {
        method: "POST",
        headers: {
          authorization: `Bearer ${apiToken}`,
        },
        body: JSON.stringify({ query, variables }),
      });

      const responseBody = await response.json();

      if (responseBody.errors) {
        error.value = responseBody.errors;
      } else {
        data.value = responseBody.data;
      }
    } catch (err) {
      error.value = err.message;
    }
    loading.value = false;
  });

  return {
    data,
    loading,
    error,
  };
}
Example #14
Source File: use-is-mounted.ts    From vooks with MIT License 5 votes vote down vote up
export default function isMounted (): Readonly<Ref<boolean>> {
  const isMounted = ref(false)
  onMounted(() => { isMounted.value = true })
  return readonly(isMounted)
}
Example #15
Source File: useSpreadSheet.ts    From S2 with MIT License 5 votes vote down vote up
export function useSpreadSheet(
  props: BaseSheetProps,
  emit: EmitFn<BaseSheetInitEmits>,
) {
  const {
    dataCfg,
    options,
    themeCfg,
    loading: loadingProps,
    sheetType,
    onSpreadsheet,
    onGetSpreadSheet,
  } = props;
  const wrapperRef = ref<HTMLDivElement>();
  const containerRef = ref<HTMLDivElement>();

  const s2Ref = shallowRef<SpreadSheet>();

  const { loading, setLoading } = useLoading(s2Ref, loadingProps);
  const pagination = usePagination(s2Ref, props);

  // TODO: 如果onSpreadsheet属性变更了怎么办???
  const renderSpreadSheet = (container: HTMLDivElement) => {
    const rawDataCfg = toRaw(dataCfg!);
    const rawOptions = toRaw(options);

    const s2Options = getSheetComponentOptions(rawOptions as S2Options);
    const s2Constructor: S2Constructor = [container, rawDataCfg, s2Options];
    if (onSpreadsheet) {
      return onSpreadsheet(...s2Constructor);
    }
    if (sheetType === 'table') {
      return new TableSheet(container, rawDataCfg, s2Options);
    }
    return new PivotSheet(container, rawDataCfg, s2Options);
  };

  const buildSpreadSheet = () => {
    setLoading(true);
    s2Ref.value = renderSpreadSheet(containerRef.value!);
    s2Ref.value.setThemeCfg(toRaw(themeCfg));
    s2Ref.value.render();
    setLoading(false);
    onGetSpreadSheet?.(s2Ref.value);
  };

  onMounted(buildSpreadSheet);
  useEvents(s2Ref, emit);
  useSheetUpdate(s2Ref, props);
  useResize(s2Ref, props, { wrapperRef, containerRef });

  onBeforeUnmount(() => {
    s2Ref.value?.destroy();
  });

  return {
    wrapperRef,
    containerRef,
    s2Ref,
    loading,
    setLoading,
    pagination,
  };
}
Example #16
Source File: component.ts    From vue3-gettext with MIT License 5 votes vote down vote up
Component = defineComponent({
  // eslint-disable-next-line vue/multi-word-component-names, vue/component-definition-name-casing
  name: "translate",
  props: {
    tag: {
      type: String,
      default: "span",
    },
    // Always use v-bind for dynamically binding the `translateN` prop to data on the parent,
    // i.e.: `:translate-n`.
    translateN: {
      type: Number,
      default: null,
    },
    translatePlural: {
      type: String,
      default: null,
    },
    translateContext: {
      type: String,
      default: null,
    },
    translateParams: {
      type: Object,
      default: null,
    },
    translateComment: {
      type: String,
      default: null,
    },
  },

  setup(props, context) {
    const isPlural = props.translateN !== undefined && props.translatePlural !== undefined;
    if (!isPlural && (props.translateN || props.translatePlural)) {
      throw new Error(
        `\`translate-n\` and \`translate-plural\` attributes must be used together: ${
          context.slots.default?.()[0]?.children
        }.`,
      );
    }

    const root = ref<HTMLElement>();

    const plugin = useGettext();
    const msgid = ref<string | null>(null);

    onMounted(() => {
      if (!msgid.value && root.value) {
        msgid.value = root.value.innerHTML.trim();
      }
    });

    const translation = computed(() => {
      const translatedMsg = translate(plugin).getTranslation(
        msgid.value!,
        props.translateN,
        props.translateContext,
        isPlural ? props.translatePlural : null,
        plugin.current,
      );

      return interpolate(plugin)(translatedMsg, props.translateParams, undefined, getCurrentInstance()?.parent);
    });

    // The text must be wraped inside a root HTML element, so we use a <span> by default.
    return () => {
      if (!msgid.value) {
        return h(props.tag, { ref: root }, context.slots.default ? context.slots.default() : "");
      }
      return h(props.tag, { ref: root, innerHTML: translation.value });
    };
  },
})
Example #17
Source File: useEvent.test.ts    From vhook with MIT License 5 votes vote down vote up
function testUseEvent(description: string, targetFn: () => Target, isRef = false) {
  describe(description, () => {
    let wrapper: VueWrapper<any>
    let clear: () => void
    let target: IEventTarget
    let testRef: Ref<Element | null>
    beforeEach(() => {
      if (isRef) {
        testRef = targetFn() as Ref<Element>
      }
      wrapper = invokeHook(() => {
        onMounted(() => {
          [target, clear] = useEvent(
            'click',
            handler,
            true,
            !isRef ? targetFn() : testRef
          )
        })
        return {
          test: testRef
        }
      })
    })
    test('target should be equal to the target parameter', () => {
      expect(target.value).toEqual(document.getElementById('test'))
    })
    test('addEventListener should be called after mounted', () => {
      expect(add).toHaveBeenCalledTimes(1)
      expect(add).toHaveBeenCalledWith('click', handler, true)
    })
    test('callback should be called after firing an event', () => {
      const target = wrapper.find('#test')
      target.trigger('click')
      expect(handler).toHaveBeenCalledTimes(1)
    })
    test('removeEventListener should be called after invoking clear', () => {
      clear()
      expect(remove).toHaveBeenCalledTimes(1)
      expect(remove).toHaveBeenCalledWith('click', handler, true)
    })
    test('callback should not be called after invoking clear', () => {
      const target = wrapper.find('#test')
      clear()
      target.trigger('click')
      expect(handler).not.toBeCalled()
    })
    test('target.value should be null after invoking clear', () => {
      clear()
      expect(target.value).toBeNull()
    })
    test('event should be removed after unmounted', () => {
      const targetDiv = wrapper.find('#test')
      wrapper.unmount()
      expect(remove).toHaveBeenCalledTimes(1)
      expect(remove).toHaveBeenCalledWith('click', handler, true)
      targetDiv.trigger('click')
      expect(handler).not.toBeCalled()
      expect(target.value).toBeNull()
    })
    if (isRef) {
      test('removeEventListener should be called when ref is manually set to null', async () => {
        const targetDiv = wrapper.find('#test')
        testRef.value = null
        await nextTick()
        expect(remove).toHaveBeenCalledTimes(1)
        expect(remove).toHaveBeenCalledWith('click', handler, true)
        targetDiv.trigger('click')
        expect(handler).not.toBeCalled()
        expect(target.value).toBeNull()
      })
    }
  })
}
Example #18
Source File: i18n.ts    From vue-i18n-next with MIT License 4 votes vote down vote up
function setupLifeCycle(
  i18n: I18nInternal,
  target: ComponentInternalInstance,
  composer: Composer
): void {
  let emitter: VueDevToolsEmitter | null = null

  if (__BRIDGE__) {
    // assign legacy VueI18n instance to Vue2 instance
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const vm = target.proxy as any
    if (vm == null) {
      throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
    }

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const _i18n = (composer as any)[LegacyInstanceSymbol]
    if (_i18n === i18n) {
      throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
    }
    vm._i18n = _i18n
    vm._i18n_bridge = true

    // browser only
    if (inBrowser) {
      vm._i18nWatcher = vm._i18n.watchI18nData()
      if (vm._i18n._sync) {
        vm._localeWatcher = vm._i18n.watchLocale()
      }
    }

    let subscribing = false
    onBeforeMount(() => {
      vm._i18n.subscribeDataChanging(vm)
      subscribing = true
    }, target)

    onUnmounted(() => {
      if (subscribing) {
        vm._i18n.unsubscribeDataChanging(vm)
        subscribing = false
      }
      if (vm._i18nWatcher) {
        vm._i18nWatcher()
        vm._i18n.destroyVM()
        delete vm._i18nWatcher
      }
      if (vm._localeWatcher) {
        vm._localeWatcher()
        delete vm._localeWatcher
      }
      delete vm._i18n_bridge
      delete vm._i18n
    }, target)
  } else {
    onMounted(() => {
      // inject composer instance to DOM for intlify-devtools
      if (
        (__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
        !__NODE_JS__ &&
        target.vnode.el
      ) {
        target.vnode.el.__VUE_I18N__ = composer
        emitter = createEmitter<VueDevToolsEmitterEvents>()
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const _composer = composer as any
        _composer[EnableEmitter] && _composer[EnableEmitter](emitter)
        emitter.on('*', addTimelineEvent)
      }
    }, target)

    onUnmounted(() => {
      // remove composer instance from DOM for intlify-devtools
      if (
        (__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
        !__NODE_JS__ &&
        target.vnode.el &&
        target.vnode.el.__VUE_I18N__
      ) {
        emitter && emitter.off('*', addTimelineEvent)
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const _composer = composer as any
        _composer[DisableEmitter] && _composer[DisableEmitter]()
        delete target.vnode.el.__VUE_I18N__
      }
      i18n.__deleteInstance(target)
    }, target)
  }
}
Example #19
Source File: EventMonitoring.ts    From screen-shot with MIT License 4 votes vote down vote up
constructor(props: Record<string, any>, context: SetupContext<any>) {
    // 实例化响应式data
    this.data = new InitData();
    // 获取截图区域canvas容器
    this.screenShortController = this.data.getScreenShortController();
    this.toolController = this.data.getToolController();
    this.textInputController = this.data.getTextInputController();
    this.optionController = this.data.getOptionController();
    this.optionIcoController = this.data.getOptionIcoController();
    this.videoController = document.createElement("video");
    this.videoController.autoplay = true;
    this.screenShortImageController = document.createElement("canvas");
    // 设置实例与属性
    this.data.setPropsData(context.emit);

    onMounted(() => {
      this.emit = this.data.getEmit();
      const plugInParameters = new PlugInParameters();
      // 单击截屏启用状态
      this.clickCutFullScreen = plugInParameters.getClickCutFullScreenStatus();
      // 设置需要隐藏的工具栏图标
      this.data.setHiddenToolIco(plugInParameters.getHiddenToolIco());
      // 设置截图区域canvas宽高
      this.data.setScreenShortInfo(window.innerWidth, window.innerHeight);
      if (this.screenShortImageController == null) return;
      // 设置截图图片存放容器宽高
      this.screenShortImageController.width = window.innerWidth;
      this.screenShortImageController.height = window.innerHeight;
      if (plugInParameters.getWebRtcStatus()) {
        // 设置为屏幕宽高
        this.data.setScreenShortInfo(window.screen.width, window.screen.height);
        // 设置为屏幕宽高
        this.screenShortImageController.width = window.screen.width;
        this.screenShortImageController.height = window.screen.height;
      }
      // 获取截图区域画canvas容器画布
      const context = this.screenShortController.value?.getContext("2d");
      if (context == null) return;
      if (!plugInParameters.getWebRtcStatus()) {
        // html2canvas截屏
        html2canvas(document.body, {
          useCORS: plugInParameters.getEnableCORSStatus(),
          proxy: plugInParameters.getProxyAddress()
        }).then(canvas => {
          // 装载截图的dom为null则退出
          if (this.screenShortController.value == null) return;

          // 调整截屏容器层级
          this.screenShortController.value.style.zIndex =
            plugInParameters.getLevel() + "";
          // 调整截图工具栏层级
          if (this.toolController.value == null) return;
          this.toolController.value.style.zIndex = `${plugInParameters.getLevel() +
            1}`;

          // 存放html2canvas截取的内容
          this.screenShortImageController = canvas;
          // 存储屏幕截图
          this.data.setScreenShortImageController(canvas);

          // 赋值截图区域canvas画布
          this.screenShortCanvas = context;
          // 绘制蒙层
          drawMasking(context);

          // 添加监听
          this.screenShortController.value?.addEventListener(
            "mousedown",
            this.mouseDownEvent
          );
          this.screenShortController.value?.addEventListener(
            "mousemove",
            this.mouseMoveEvent
          );
          this.screenShortController.value?.addEventListener(
            "mouseup",
            this.mouseUpEvent
          );
        });
        return;
      }
      // 开始捕捉屏幕
      this.startCapture().then(() => {
        setTimeout(() => {
          // 装载截图的dom为null则退出
          if (this.screenShortController.value == null) return;
          if (this.screenShortImageController == null) return;
          const imageContext = this.screenShortImageController.getContext("2d");
          if (imageContext == null) return;
          // 将获取到的屏幕截图绘制到图片容器里
          imageContext.drawImage(
            this.videoController,
            0,
            0,
            this.screenShortImageController.width,
            this.screenShortImageController.height
          );
          // 存储屏幕截图
          this.data.setScreenShortImageController(
            this.screenShortImageController
          );

          // 赋值截图区域canvas画布
          this.screenShortCanvas = context;
          // 绘制蒙层
          drawMasking(context);

          // 添加监听
          this.screenShortController.value?.addEventListener(
            "mousedown",
            this.mouseDownEvent
          );
          this.screenShortController.value?.addEventListener(
            "mousemove",
            this.mouseMoveEvent
          );
          this.screenShortController.value?.addEventListener(
            "mouseup",
            this.mouseUpEvent
          );
          // 停止捕捉屏幕
          this.stopCapture();
          // 调整截屏容器层级
          this.screenShortController.value.style.zIndex =
            plugInParameters.getLevel() + "";
          // 调整截图工具栏层级
          if (this.toolController.value == null) return;
          this.toolController.value.style.zIndex = `${plugInParameters.getLevel() +
            1}`;
        }, 500);
      });
    });

    onUnmounted(() => {
      // 初始化initData中的数据
      this.data.setInitStatus(true);
    });
  }
Example #20
Source File: useEvents.ts    From S2 with MIT License 4 votes vote down vote up
useEvents = (
  s2Ref: Ref<SpreadSheet | undefined>,
  emit: EmitFn<BaseSheetInitEmits>,
) => {
  onMounted(() => {
    if (!s2Ref.value) {
      return;
    }

    // ============== Row Cell ====================
    useCellEvent(s2Ref, emit, S2Event.ROW_CELL_HOVER, 'rowCellHover');
    useCellEvent(s2Ref, emit, S2Event.ROW_CELL_CLICK, 'rowCellClick');
    useCellEvent(
      s2Ref,
      emit,
      S2Event.ROW_CELL_DOUBLE_CLICK,
      'rowCellDoubleClick',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.ROW_CELL_CONTEXT_MENU,
      'rowCellContextMenu',
    );
    useCellEvent(s2Ref, emit, S2Event.ROW_CELL_MOUSE_DOWN, 'rowCellMouseDown');
    useCellEvent(s2Ref, emit, S2Event.ROW_CELL_MOUSE_UP, 'rowCellMouseUp');
    useCellEvent(s2Ref, emit, S2Event.ROW_CELL_MOUSE_MOVE, 'rowCellMouseMove');
    useS2Event(
      s2Ref,
      emit,
      S2Event.ROW_CELL_COLLAPSE_TREE_ROWS,
      'rowCellCollapseTreeRows',
    );

    // ============== Col Cell ====================
    useCellEvent(s2Ref, emit, S2Event.COL_CELL_HOVER, 'colCellHover');
    useCellEvent(s2Ref, emit, S2Event.COL_CELL_CLICK, 'colCellClick');
    useCellEvent(
      s2Ref,
      emit,
      S2Event.COL_CELL_DOUBLE_CLICK,
      'colCellDoubleClick',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.COL_CELL_CONTEXT_MENU,
      'colCellContextMenu',
    );
    useCellEvent(s2Ref, emit, S2Event.COL_CELL_MOUSE_DOWN, 'colCellMouseDown');
    useCellEvent(s2Ref, emit, S2Event.COL_CELL_MOUSE_UP, 'colCellMouseUp');
    useCellEvent(s2Ref, emit, S2Event.COL_CELL_MOUSE_MOVE, 'colCellMouseMove');

    // ============== Data Cell ====================
    useCellEvent(s2Ref, emit, S2Event.DATA_CELL_HOVER, 'dataCellHover');
    useCellEvent(s2Ref, emit, S2Event.DATA_CELL_CLICK, 'dataCellClick');
    useCellEvent(
      s2Ref,
      emit,
      S2Event.DATA_CELL_DOUBLE_CLICK,
      'dataCellDoubleClick',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.DATA_CELL_CONTEXT_MENU,
      'dataCellContextMenu',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.DATA_CELL_MOUSE_DOWN,
      'dataCellMouseDown',
    );
    useCellEvent(s2Ref, emit, S2Event.DATA_CELL_MOUSE_UP, 'dataCellMouseUp');
    useCellEvent(
      s2Ref,
      emit,
      S2Event.DATA_CELL_MOUSE_MOVE,
      'dataCellMouseMove',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.DATA_CELL_TREND_ICON_CLICK,
      'dataCellTrendIconClick',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.DATE_CELL_BRUSH_SELECTION,
      'dataCellBrushSelection',
    );

    // ============== Corner Cell ====================
    useCellEvent(s2Ref, emit, S2Event.CORNER_CELL_HOVER, 'cornerCellHover');
    useCellEvent(s2Ref, emit, S2Event.CORNER_CELL_CLICK, 'cornerCellClick');
    useCellEvent(
      s2Ref,
      emit,
      S2Event.CORNER_CELL_DOUBLE_CLICK,
      'cornerCellDoubleClick',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.CORNER_CELL_CONTEXT_MENU,
      'cornerCellContextMenu',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.CORNER_CELL_MOUSE_DOWN,
      'cornerCellMouseDown',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.CORNER_CELL_MOUSE_UP,
      'cornerCellMouseUp',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.CORNER_CELL_MOUSE_MOVE,
      'cornerCellMouseMove',
    );

    // ============== Merged Cells ====================
    useCellEvent(s2Ref, emit, S2Event.MERGED_CELLS_HOVER, 'mergedCellsHover');
    useCellEvent(s2Ref, emit, S2Event.MERGED_CELLS_CLICK, 'mergedCellsClick');
    useCellEvent(
      s2Ref,
      emit,
      S2Event.MERGED_CELLS_DOUBLE_CLICK,
      'mergedCellsDoubleClick',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.MERGED_CELLS_CONTEXT_MENU,
      'mergedCellsContextMenu',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.MERGED_CELLS_MOUSE_DOWN,
      'mergedCellsMouseDown',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.MERGED_CELLS_MOUSE_UP,
      'mergedCellsMouseUp',
    );
    useCellEvent(
      s2Ref,
      emit,
      S2Event.MERGED_CELLS_MOUSE_MOVE,
      'mergedCellsMouseMove',
    );

    // ============== Sort ====================
    useS2Event(s2Ref, emit, S2Event.RANGE_SORT, 'rangeSort');
    useS2Event(s2Ref, emit, S2Event.RANGE_SORTED, 'rangeSorted');

    // ============== Filter ====================
    useS2Event(s2Ref, emit, S2Event.RANGE_FILTER, 'rangeFilter');
    useS2Event(s2Ref, emit, S2Event.RANGE_FILTERED, 'rangeFiltered');

    // ============== Layout ====================
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_AFTER_HEADER_LAYOUT,
      'layoutAfterHeaderLayout',
    );
    useS2Event(s2Ref, emit, S2Event.LAYOUT_PAGINATION, 'layoutPagination');
    useS2Event(s2Ref, emit, S2Event.LAYOUT_CELL_SCROLL, 'layoutCellScroll');
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_AFTER_COLLAPSE_ROWS,
      'layoutAfterCollapseRows',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_TREE_ROWS_COLLAPSE_ALL,
      'collapseRowsAll',
    );
    useS2Event(s2Ref, emit, S2Event.LAYOUT_COLS_EXPANDED, 'layoutColsExpanded');
    useS2Event(s2Ref, emit, S2Event.LAYOUT_COLS_HIDDEN, 'layoutColsHidden');
    useS2Event(s2Ref, emit, S2Event.LAYOUT_BEFORE_RENDER, 'beforeRender');
    useS2Event(s2Ref, emit, S2Event.LAYOUT_AFTER_RENDER, 'afterRender');
    useS2Event(s2Ref, emit, S2Event.LAYOUT_DESTROY, 'destroy');

    // ============== Resize ====================
    useS2Event(s2Ref, emit, S2Event.LAYOUT_RESIZE, 'layoutResize');
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_SERIES_WIDTH,
      'layoutResizeSeriesWidth',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_ROW_WIDTH,
      'layoutResizeRowWidth',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_ROW_HEIGHT,
      'layoutResizeRowHeight',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_COL_WIDTH,
      'layoutResizeColWidth',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_COL_HEIGHT,
      'layoutResizeColHeight',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_TREE_WIDTH,
      'layoutResizeTreeWidth',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_MOUSE_DOWN,
      'layoutResizeMouseDown',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_MOUSE_UP,
      'layoutResizeMouseUp',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.LAYOUT_RESIZE_MOUSE_MOVE,
      'layoutResizeMouseMove',
    );

    // ============== Global ====================
    useS2Event(s2Ref, emit, S2Event.GLOBAL_KEYBOARD_DOWN, 'keyBoardDown');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_KEYBOARD_UP, 'keyBoardUp');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_COPIED, 'copied');
    useS2Event(
      s2Ref,
      emit,
      S2Event.GLOBAL_ACTION_ICON_HOVER,
      'actionIconHover',
    );
    useS2Event(
      s2Ref,
      emit,
      S2Event.GLOBAL_ACTION_ICON_CLICK,
      'actionIconClick',
    );
    useS2Event(s2Ref, emit, S2Event.GLOBAL_CONTEXT_MENU, 'contextMenu');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_HOVER, 'mouseHover');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_CLICK, 'click');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_DOUBLE_CLICK, 'doubleClick');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_SELECTED, 'selected');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_MOUSE_UP, 'mouseUp');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_RESET, 'reset');
    useS2Event(s2Ref, emit, S2Event.GLOBAL_LINK_FIELD_JUMP, 'linkFieldJump');
  });
}
Example #21
Source File: useNode.ts    From vue3-treeview with MIT License 4 votes vote down vote up
export function useNode(cmn: IUseCommon, props: INodeProps): IUseNode { 
    const state = cmn.state;
    const node = cmn.node;
    const config = cmn.config;
    const wrapper = cmn.wrapper;
    const editing = cmn.editing;
    const level = ref(null);
    const depth = ref(props.depth);
    const index = ref(props.index);
    const id = computed(() => {
        return hasNode.value && node.value.id;
    });

    const hasNode = computed(() => {
        return !isNil(node);
    });

    const hasState = computed(() => {
        return hasNode.value && !isNil(node.value.state);
    });

    const roots = computed(() => {
        return config.value.roots || [];
    });

    const children = computed(() => {
        return isNil(node.value.children) ? [] : node.value.children;
    });

    const nbChildren = computed(() => {
        return children.value.length;
    });

    const hasChildren = computed(() => {
        return nbChildren.value > 0;
    });

    const opened = computed(() => {
        return hasState.value && node.value.state.opened || false;
    });

    const isLoading = computed(() => {
        return hasState.value && node.value.state.isLoading || false;
    });

    const displayLoading = computed(() => {
        return isLoading.value && !hasChildren.value && opened.value; 
    });

    const displayLevel = computed(() => {
        return !isLoading.value && hasChildren.value && opened.value;
    });

    const style = computed(() => {
        return {
            display: "flex"
        };
    });

    const disabledClass = computed(() => {
        if (!cmn.disabled.value) {
            return null;
        }

        return config.value.disabledClass ? config.value.disabledClass : defaultDisabledClass;
    });

    const hideIcons = computed(() => {
        for (const id of roots.value) {
            const node = state.nodes.value[id];

            if (node.children && node.children.length > 0) {
                return false;
            }
        }

        return true;
    });

    const isLeaf = computed(() => {
        if (isArray(config.value.leaves)) {
            const arr: string[] = config.value.leaves;
            const idx = arr.indexOf(id.value);
            return Number.isFinite(idx) && idx >= 0;
        }

        return isNil(node.value.children) || !isArray(node.value.children) || node.value.children.length === 0;
    });

    const isFocusable = computed(() => {
        return state.focusable.value === node.value.id;
    });

    const tabIndex = computed(() => {
        if (depth.value === 0 && index.value === 0 && isNil(state.focusable.value)) {
            return 0; 
        }

        return isFocusable.value ? 0 : -1;
    });

    const focusClass = computed(() =>  {
        if (!cmn.focused.value) {
            return null;
        }

        return config.value.focusClass ? config.value.focusClass : defaultFocusClass;
    });

    watch(opened, (nv: boolean) => {
        nv ? cmn.root.emit(nodeEvents.opened, node.value) : cmn.root.emit(nodeEvents.closed, node.value);
    });

    const focus = (() => {
        state.focusable.value = node.value.id;

        nextTick(() => {
            wrapper.value.focus();
            cmn.focused.value = true;
            cmn.root.emit(nodeEvents.focus, node.value);
        });
    });

    const toggle = (() => {
        node.value.state.opened = !node.value.state.opened;
        cmn.root.emit(nodeEvents.toggle, node.value);
    });

    const right = (() => {
        if (!editing.value && config.value.keyboardNavigation) {
            node.value.state.opened = true;
        }
    });

    const left = (() => {
        if (!editing.value && config.value.keyboardNavigation) {
            node.value.state.opened = false;
        }
    });

    const move = ((getFunc: (s: string) => string) => {
        const id = getFunc(node.value.id);

        if (!isNil(id) && config.value.keyboardNavigation) {
            const f = state.focusFunc.get(id);

            if(f) {
                f();
            }
        }
    });

    const up = () => move(prevVisible);

    const prev = ((id: string): string => { 
        const n = state.nodes.value[id];

        if (n.children && n.children.length > 0) {
            const idx = n.children.indexOf(node.value.id);
            const prev = n.children[idx - 1];
            
            if (!isNil(prev)) {
                return lastChild(prev);
            }
        } 

        return n.id;
    });

    const prevVisible = ((id: string) => {
        const n = state.nodes.value[id];  
        const p = state.nodes.value[n.parent];

        if (!p) {
            const idx = roots.value.indexOf(id);
            return lastChild(roots.value[idx - 1]) || null;            
        }

        return prev(p.id);
    });

    const lastChild = ((id: string): string => {
        const n = state.nodes.value[id];

        if (!n) {
            return null;
        }  

        if (n.children && n.children.length > 0 && n.state.opened) {
            const last = n.children[n.children.length - 1];

            if (!isNil(last)) {
                return lastChild(last);
            }
        }

        return n.id;
    });

    const down = () => move(nextVisible);

    const nextRoot = ((id: string) => {
        const idx = roots.value.indexOf(id);
        return roots.value[idx + 1] || null;
    });

    const next = ((p: INode, id: string): string => {
        const idx = p.children.indexOf(id);

        if (p.children[idx + 1]) {
            return p.children[idx + 1];
        }

        if (p.parent) {
            return next(state.nodes.value[p.parent], p.id);
        }

        return nextRoot(p.id);
    });

    const nextVisible = ((id: string): string => {
        const n = state.nodes.value[id];

        if (n.children && n.children.length > 0 && n.state.opened) {
            return n.children[0];
        }

        const p = state.nodes.value[n.parent];

        return p ? next(p, id) : nextRoot(id);
    });

    onMounted(() => {
        state.focusFunc.set(node.value.id, focus);
    });

    onUnmounted(() => {
        state.focusFunc.delete(node.value.id);
    });

    return {
        id,
        level,
        style,
        opened,
        hasNode,
        hideIcons,
        hasChildren,
        tabIndex,
        focusClass,
        disabledClass,
        isLeaf,
        isLoading,
        displayLoading,
        displayLevel,
        right,
        left,
        up,
        down,
        toggle,
        focus,
        prevVisible,
        nextVisible
    };
}
Example #22
Source File: watch.ts    From theila with Mozilla Public License 2.0 4 votes vote down vote up
// setup is meant to be called from the component setup method
  // and provides seamless integration with the reactive properties of the component.
  public setup(props: any, componentContext: any) {
    const {
      resource,
      context,
      kubernetes,
      talos,
      theila,
      compareFn,
    } = toRefs(props);

    watch([
      resource,
      context,
      kubernetes,
      talos,
      theila,
      compareFn,
      ctx.current,
    ], (val, oldVal) => {
      if(JSON.stringify(val) != JSON.stringify(oldVal)) {
        startWatch();
      }
    });

    const startWatch = async () => {
      stopWatch();

      if(!resource.value) {
        return;
      }

      let source:Runtime;

      if(kubernetes.value) {
        source = Runtime.Kubernetes;
      } else if(talos.value) {
        source = Runtime.Talos;
      }  else if(theila.value) {
        source = Runtime.Theila;
      }
      else {
        throw new Error("unknown source specified");
      }

      const compare = compareFn && compareFn.value ? compareFn.value : defaultCompareFunc(this);
      const c = {};

      if(context && context.value) {
        Object.assign(c, context.value)
      }

      // override the context name by the current default one unless it's explicitly defined
      if(!componentContext.context || !componentContext.context.name)
        c["name"] = contextName();

      await this.start(
        source,
        resource.value,
        c,
        compare,
      );
    };

    const stopWatch = async () => {
      if(this.running.value) {
        await this.stop();
      }
    };

    const handleReconnect = async () => {
      await startWatch();
    }

    onMounted(async () => {
      ctx.api.addListener(ClientReconnected, handleReconnect);

      await startWatch();
    });

    onUnmounted(async () => {
      ctx.api.removeListener(ClientReconnected, handleReconnect);

      await stopWatch();
    });
  }