index.vue 2.13 KB
<script lang="ts" setup>
  import { Input } from 'ant-design-vue';
  import { JSONEditor } from '/@/components/CodeEditor';
  import { SettingOutlined } from '@ant-design/icons-vue';
  import { ModeEnum } from './index';
  import { computed } from '@vue/reactivity';
  import CreateTCPCommandModal from './CreateTCPCommandModal.vue';
  import { useModal } from '/@/components/Modal';
  import { ref } from 'vue';
  import { unref } from 'vue';
  import JSONEditorType from 'jsoneditor';

  const props = withDefaults(
    defineProps<{
      value?: any;
      mode?: string;
      inputProps?: Recordable;
      showSettingAddonAfter?: boolean;
      openSettingOnInputFocus?: boolean;
    }>(),
    {
      mode: 'application/json',
      showSettingAddonAfter: true,
      openSettingOnInputFocus: false,
    }
  );

  const emit = defineEmits(['update:value']);

  const inputElRef = ref<Nullable<HTMLInputElement>>(null);

  const [registerCreateTCPCommandModal, { openModal }] = useModal();

  const getJSONValue = computed(() => {
    return props.value;
  });

  const handleEmit = (value: any) => {
    emit('update:value', value);
    openModal(false);
    if (props.openSettingOnInputFocus) {
      unref(inputElRef)?.blur();
    }
  };

  const handleClick = () => {
    openModal(true);
  };

  const handleFocus = () => {
    if (props.openSettingOnInputFocus) {
      openModal(true);
      unref(inputElRef)?.blur();
    }
  };

  const handleEditorBlur = (_event: Event, instance: JSONEditorType) => {
    const value = instance.getText();
    handleEmit(value);
  };
</script>

<template>
  <section>
    <Input
      v-if="mode === ModeEnum.NORMAL"
      ref="inputElRef"
      :value="getJSONValue"
      @change="handleEmit"
      v-bind="inputProps"
      @focus="handleFocus"
    >
      <template v-if="showSettingAddonAfter" #addonAfter>
        <SettingOutlined class="cursor-pointer" @click="handleClick" />
      </template>
    </Input>
    <JSONEditor v-if="mode === ModeEnum.JSON" :value="getJSONValue" @blur="handleEditorBlur" />
    <CreateTCPCommandModal @register="registerCreateTCPCommandModal" @update:value="handleEmit" />
  </section>
</template>