<!--
 * @Author: ChenChanghua
 * @Date: 2023-03-09 14:19:01
 * @Description: 一个简单的按左右键, 焦点在左右两个view来回切换的控件
-->
<script setup>
import { ref } from "vue";
import { useFocusHub } from "jsview";

const props = defineProps({
  data: Object,
  onAction: Object,
});
const focusHub = useFocusHub();

let focused = ref(false);
let focusIndex = ref(0);
const onFocus = () => {
  /**重要代码: onFocus时, 获得焦点, 以处理自己内部的焦点逻辑*/
  focusHub.setFocus(props.data.name);
  /*******/
  focused.value = true;
};
const onBlur = () => {
  focused.value = false;
  focusIndex.value = 0;
  /**重要代码: onBlur的时候, 需要将焦点返还给父*/
  focusHub.returnFocusToParent();
  /*******/
};

const onKeyDown = (ev) => {
  if (ev.keyCode == 37 && focusIndex.value == 1) {
    focusIndex.value = 0;
    return true;
  } else if (ev.keyCode == 39 && focusIndex.value == 0) {
    focusIndex.value = 1;
    return true;
  } else if (ev.keyCode == 13) {
    console.log("button click", props.data);
    return true;
  }
  return false;
};

props.onAction.register("onFocus", onFocus);
props.onAction.register("onBlur", onBlur);
</script>

<template>
  <jsv-focus-block
    :name="data.name"
    :onAction="{
      onKeyDown: onKeyDown,
    }"
  >
    <div
      :style="{
        width: 100,
        height: 100,
        fontSize: 20,
        color: '#FFFFFF',
        backgroundColor: '#00AA00',
      }"
    ></div>

    <div
      :style="{
        left: 100,
        width: 100,
        height: 100,
        backgroundColor: '#0000AA',
      }"
    ></div>

    <div
      :style="{
        visibility: focused ? 'visible' : 'hidden',
        left: 100 * focusIndex,
        width: 10,
        height: 10,
        backgroundColor: '#FF0000',
      }"
    ></div>
  </jsv-focus-block>
</template>