Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/** @jsxImportSource https://esm.sh/react */
import React, { useEffect, useRef, useState } from "https://esm.sh/react";
import { renderToString } from "https://esm.sh/react-dom/server";
const ForceScale = () => {
const [force, setForce] = useState(0);
const [weight, setWeight] = useState(0);
const scaleRef = useRef(null);
const baselineForceRef = useRef(0);
const isPressedRef = useRef(false);
useEffect(() => {
const handleForceChange = (e) => {
if (typeof e.webkitForce !== "undefined") {
const currentForce = e.webkitForce;
setForce(currentForce);
if (isPressedRef.current && baselineForceRef.current > 0) {
const forceDifference = Math.max(0, currentForce - baselineForceRef.current);
const estimatedWeight = (forceDifference * 1000).toFixed(2);
setWeight(estimatedWeight);
}
}
};
const handleMouseDown = (e) => {
isPressedRef.current = true;
baselineForceRef.current = e.webkitForce || 0;
};
const handleMouseUp = () => {
isPressedRef.current = false;
baselineForceRef.current = 0;
setWeight(0);
};
document.addEventListener("webkitmouseforcechanged", handleForceChange);
scaleRef.current?.addEventListener("mousedown", handleMouseDown);
scaleRef.current?.addEventListener("mouseup", handleMouseUp);
return () => {
document.removeEventListener("webkitmouseforcechanged", handleForceChange);
scaleRef.current?.removeEventListener("mousedown", handleMouseDown);
scaleRef.current?.removeEventListener("mouseup", handleMouseUp);
};
}, []);
const isForceSupported = typeof window !== "undefined" && "webkitForce" in MouseEvent.prototype;
return (
<div>
<div
ref={scaleRef}
id="scale"
style={{
width: "200px",
height: "200px",
backgroundColor: "#3498db",
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "white",
fontSize: "24px",
cursor: "pointer",
userSelect: "none",
borderRadius: "10px",
}}
>
{isForceSupported
? weight > 0
? `${weight}g`
: "Place apple here"
: "Force Touch not supported"}
</div>
<div id="force-display" style={{ marginTop: "20px", fontSize: "16px", color: "#333" }}>
{isForceSupported
? `Current force: ${force.toFixed(2)}`
: "This demo requires Safari on a Mac with Force Touch"}
</div>
</div>
);
};
const App = () => (
<html lang="en">
<head>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Force Touch Scale</title>
<style>
{`
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
perbhat-primitivebronzeowl.web.val.run
September 6, 2024