press-plus
Version:
85 lines (81 loc) • 2.5 kB
JavaScript
export function getTouchMixin() {
return {
data() {
const switchPos = {
hasMoved: false, // exclude click event
x: 20, // right
y: 100, // bottom
startX: 0,
startY: 0,
endX: 0,
endY: 0,
};
return {
switchPos,
btnSwitchPos: { x: 20, y: 100 },
};
},
methods: {
onTouchStart(e) {
this.switchPos.startX = e.touches[0].pageX;
this.switchPos.startY = e.touches[0].pageY;
},
onTouchEnd() {
if (!this.switchPos.hasMoved) {
return;
}
this.switchPos.startX = 0;
this.switchPos.startY = 0;
this.switchPos.hasMoved = false;
this.setSwitchPosition(this.switchPos.endX, this.switchPos.endY);
},
onTouchMove(e) {
if (e.touches.length <= 0) {
return;
}
const offsetX = e.touches[0].pageX - this.switchPos.startX;
const offsetY = e.touches[0].pageY - this.switchPos.startY;
let x = Math.floor(this.switchPos.x - offsetX);
let y = Math.floor(this.switchPos.y - offsetY);
[x, y] = this.getSwitchButtonSafeAreaXY(x, y);
this.btnSwitchPos.x = x;
this.btnSwitchPos.y = y;
this.switchPos.endX = x;
this.switchPos.endY = y;
this.switchPos.hasMoved = true;
e.preventDefault();
e.stopPropagation();
},
setSwitchPosition(switchX, switchY) {
[switchX, switchY] = this.getSwitchButtonSafeAreaXY(switchX, switchY);
this.switchPos.x = switchX;
this.switchPos.y = switchY;
this.btnSwitchPos.x = switchX;
this.btnSwitchPos.y = switchY;
},
getSwitchButtonSafeAreaXY(x, y) {
const bottomThreshold = 20;
const top = 0;
const { fabSize } = this;
const { windowWidth, windowHeight, windowTop, windowBottom } = uni.getSystemInfoSync();
const docWidth = windowWidth;
const docHeight = windowHeight - top;
// check edge
if (x + fabSize.width > docWidth) {
x = docWidth - fabSize.width;
}
if (y + fabSize.height - windowTop > docHeight) {
y = docHeight - fabSize.height + windowTop;
}
if (x < 0) {
x = 0;
}
if (y < bottomThreshold + windowBottom) {
y = bottomThreshold + windowBottom;
}
// safe area for iOS Home indicator
return [x, y];
},
},
};
}