Files
pihkaal-me/app/components/Common/Buttons.vue

158 lines
3.2 KiB
Vue

<script setup lang="ts">
import gsap from "gsap";
const props = defineProps<{
yOffset: number;
opacity?: number;
bLabel: string;
aLabel: string;
noKeyboardA?: boolean;
}>();
const emit = defineEmits<{
activateA: [];
activateB: [];
}>();
const { onRender, onClick, onMouseDown } = useScreen();
const BUTTON_WIDTH = 80;
const BUTTON_HEIGHT = 18;
const B_BUTTON: Rect = [31, 172, BUTTON_WIDTH, BUTTON_HEIGHT];
const A_BUTTON: Rect = [144, 172, BUTTON_WIDTH, BUTTON_HEIGHT];
const LABEL_CHANGE_OFFSET = 20;
const LABEL_CHANGE_DURATION = 0.167;
const LABEL_CHANGE_PAUSE = 0.08;
let bButtonOffsetY = 0;
let aButtonOffsetY = 0;
let displayedBLabel = props.bLabel;
let displayedALabel = props.aLabel;
let bButtonPressed = false;
let aButtonPressed = false;
const animateLabelChange = (
setter: (v: number) => void,
setLabel: (label: string) => void,
newLabel: string,
) => {
const target = { v: 0 };
gsap
.timeline()
.to(target, {
v: LABEL_CHANGE_OFFSET,
duration: LABEL_CHANGE_DURATION,
ease: "none",
onUpdate: () => setter(target.v),
onComplete: () => setLabel(newLabel),
})
.to(target, {
v: 0,
duration: LABEL_CHANGE_DURATION,
delay: LABEL_CHANGE_PAUSE,
ease: "none",
onUpdate: () => setter(target.v),
});
};
watch(
() => props.bLabel,
(newLabel) =>
animateLabelChange(
(v) => (bButtonOffsetY = v),
(l) => (displayedBLabel = l),
newLabel,
),
);
watch(
() => props.aLabel,
(newLabel) =>
animateLabelChange(
(v) => (aButtonOffsetY = v),
(l) => (displayedALabel = l),
newLabel,
),
);
onRender((ctx) => {
ctx.globalAlpha = props.opacity ?? 1;
ctx.font = "10px NDS10";
ctx.fillStyle = "#010101";
ctx.translate(0, 172 + props.yOffset);
drawButton(
ctx,
`${ICONS.B} ${displayedBLabel}`,
31,
bButtonOffsetY,
BUTTON_WIDTH,
bButtonPressed,
);
drawButton(
ctx,
`${ICONS.A} ${displayedALabel}`,
144,
aButtonOffsetY,
BUTTON_WIDTH,
aButtonPressed,
);
}, 60);
let lastPressedButton: "A" | "B" | null = null;
onClick((x, y) => {
if (props.yOffset !== 0) return;
if (rectContains(B_BUTTON, [x, y]) && lastPressedButton === "B") {
emit("activateB");
} else if (rectContains(A_BUTTON, [x, y]) && lastPressedButton === "A") {
emit("activateA");
}
lastPressedButton = null;
});
onMouseDown((x, y) => {
if (props.yOffset !== 0) return;
if (rectContains(B_BUTTON, [x, y])) {
bButtonPressed = true;
lastPressedButton = "B";
} else if (rectContains(A_BUTTON, [x, y])) {
aButtonPressed = true;
lastPressedButton = "A";
}
});
useMouseUp(() => {
bButtonPressed = false;
aButtonPressed = false;
});
useKeyDown(({ key, repeated }) => {
if (props.yOffset !== 0 || repeated) return;
switch (key) {
case "NDS_START":
case "NDS_A":
if (!props.noKeyboardA) emit("activateA");
break;
case "NDS_B":
emit("activateB");
break;
}
});
const forceAnimateBLabel = () =>
animateLabelChange(
(v) => (bButtonOffsetY = v),
(l) => (displayedBLabel = l),
props.bLabel,
);
defineExpose({ forceAnimateBLabel });
defineOptions({ render: () => null });
</script>