refactor: replace useState() with useSignal() (#1234)

This commit is contained in:
Asher Gomez
2023-06-02 06:43:01 +10:00
committed by GitHub
parent 7b35cb07d4
commit 8fa4141e06
15 changed files with 120 additions and 112 deletions
+3 -4
View File
@@ -14,15 +14,14 @@ island. The file must have a default export that is a regular Preact component.
```tsx
// islands/MyIsland.tsx
import { useState } from "preact/hooks";
import type { Signal } from "@preact/signals";
export default function MyIsland() {
const [count, setCount] = useState(0);
const count = useSignal(0);
return (
<div>
Counter is at {count}.{" "}
<button onClick={() => setCount(count + 1)}>+</button>
Counter is at {count}. <button onClick={() => count.value += 1}>+</button>
</div>
);
}
+7 -8
View File
@@ -31,7 +31,8 @@ Here is an example of an island component that counts down to a specific time.
```tsx
// islands/Countdown.tsx
import { useEffect, useState } from "preact/hooks";
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
const timeFmt = new Intl.RelativeTimeFormat("en-US");
@@ -39,18 +40,16 @@ const timeFmt = new Intl.RelativeTimeFormat("en-US");
// props to island components need to be JSON (de)serializable.
export default function Countdown(props: { target: string }) {
const target = new Date(props.target);
const [now, setNow] = useState(new Date());
const now = useSignal(new Date());
// Set up an interval to update the `now` date every second with the current
// date as long as the component is mounted.
useEffect(() => {
const timer = setInterval(() => {
setNow((now) => {
if (now > target) {
clearInterval(timer);
}
return new Date();
});
if (now.value > target) {
clearInterval(timer);
}
now.value = new Date();
}, 1000);
return () => clearInterval(timer);
}, [props.target]);
+10 -7
View File
@@ -112,9 +112,11 @@ await Deno.writeTextFile(
);
const ROUTES_INDEX_TSX = `import { Head } from "$fresh/runtime.ts";
import { useSignal } from "@preact/signals";
import Counter from "../islands/Counter.tsx";
export default function Home() {
const count = useSignal(3);
return (
<>
<Head>
@@ -132,7 +134,7 @@ export default function Home() {
Welcome to \`fresh\`. Try updating this message in the
./routes/index.tsx file, and refresh.
</p>
<Counter start={3} />
<Counter count={count} />
</div>
</>
);
@@ -164,20 +166,21 @@ await Deno.writeTextFile(
COMPONENTS_BUTTON_TSX,
);
const ISLANDS_COUNTER_TSX = `import { useState } from "preact/hooks";
const ISLANDS_COUNTER_TSX = `import type { Signal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
start: number;
count: Signal<number>;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div${useTwind ? ' class="flex gap-2 w-full"' : ""}>
<p${useTwind ? ' class="flex-grow-1 font-bold text-xl"' : ""}>{count}</p>
<Button onClick={() => setCount(count - 1)}>-1</Button>
<Button onClick={() => setCount(count + 1)}>+1</Button>
<p${
useTwind ? ' class="flex-grow-1 font-bold text-xl"' : ""
}>{props.count}</p>
<Button onClick={() => props.count.value -= 1}>-1</Button>
<Button onClick={() => props.count.value += 1}>+1</Button>
</div>
);
}
+3 -1
View File
@@ -3,6 +3,8 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.13.1",
"preact/": "https://esm.sh/preact@10.13.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.6"
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.6",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3"
}
}
+4 -5
View File
@@ -1,19 +1,18 @@
import { useState } from "preact/hooks";
import type { Signal } from "@preact/signals";
import { IS_BROWSER } from "$fresh/runtime.ts";
interface CounterProps {
start: number;
count: Signal<number>;
id: string;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div id={props.id}>
<p>{count}</p>
<p>{props.count}</p>
<button
id={`b-${props.id}`}
onClick={() => setCount(count + 1)}
onClick={() => props.count.value += 1}
disabled={!IS_BROWSER}
>
+1
+4 -4
View File
@@ -1,15 +1,15 @@
import { useState } from "preact/hooks";
import { useSignal } from "@preact/signals";
export default function RootFragment() {
const [shown, setShown] = useState(false);
const shown = useSignal(false);
return (
<>
Hello
<div onClick={() => setShown(true)} id="root-fragment-click-me">
<div onClick={() => shown.value = true} id="root-fragment-click-me">
World
</div>
{shown && <div>I'm rendered now</div>}
{shown.value && <div>I'm rendered now</div>}
</>
);
}
@@ -1,14 +1,14 @@
import { useState } from "preact/hooks";
import { useSignal } from "@preact/signals";
export default function RootFragmentWithConditionalFirst() {
const [shown, setShown] = useState(false);
const shown = useSignal(false);
return (
<>
{shown && <div>I'm rendered on top</div>}
{shown.value && <div>I'm rendered on top</div>}
Hello
<div
onClick={() => setShown(true)}
onClick={() => shown.value = true}
id="root-fragment-conditional-first-click-me"
>
World
+4 -5
View File
@@ -1,19 +1,18 @@
import { useState } from "preact/hooks";
import type { Signal } from "@preact/signals";
import { IS_BROWSER } from "$fresh/runtime.ts";
interface CounterProps {
start: number;
count: Signal<number>;
id: string;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div id={props.id}>
<p>{count}</p>
<p>{props.count}</p>
<button
id={`b-${props.id}`}
onClick={() => setCount(count + 1)}
onClick={() => props.count.value += 1}
disabled={!IS_BROWSER}
>
+1
@@ -1,21 +1,20 @@
import { useState } from "preact/hooks";
import type { Signal } from "@preact/signals";
import { IS_BROWSER } from "$fresh/runtime.ts";
interface KebabCaseFileNameTestProps {
start: number;
count: Signal<number>;
id: string;
}
export default function KebabCaseFileNameTest(
props: KebabCaseFileNameTestProps,
) {
const [count, setCount] = useState(props.start);
return (
<div id={props.id}>
<p>{count}</p>
<p>{props.count}</p>
<button
id={`b-${props.id}`}
onClick={() => setCount(count + 1)}
onClick={() => props.count.value += 1}
disabled={!IS_BROWSER}
>
+1
+8 -4
View File
@@ -1,3 +1,4 @@
import { useSignal } from "@preact/signals";
import Counter from "../../islands/Counter.tsx";
import FolderCounter from "../../islands/folder/Counter.tsx";
import KebabCaseFileNameTest from "../../islands/kebab-case-counter-test.tsx";
@@ -6,10 +7,13 @@ import Test from "../../islands/Test.tsx";
export default function Home() {
return (
<div>
<Counter id="counter1" start={3} />
<Counter id="counter2" start={10} />
<FolderCounter id="folder-counter" start={3} />
<KebabCaseFileNameTest id="kebab-case-file-counter" start={5} />
<Counter id="counter1" count={useSignal(3)} />
<Counter id="counter2" count={useSignal(10)} />
<FolderCounter id="folder-counter" count={useSignal(3)} />
<KebabCaseFileNameTest
id="kebab-case-file-counter"
count={useSignal(5)}
/>
<Test message="" />
<Test message={`</script><script>alert('test')</script>`} />
</div>
@@ -1,6 +1,7 @@
// https://github.com/denoland/fresh/pull/1050
import { useEffect, useState } from "preact/hooks";
import { useEffect } from "preact/hooks";
import { cmpCssRules } from "../utils/utils.ts";
import { useSignal } from "@preact/signals";
/**
* Returns a cssrulelist of styleElement matching the selector.
@@ -11,22 +12,18 @@ function getCssrules(selector: string) {
}
export default function CheckDuplication() {
const [cssRulesFRSHTWIND, setCssRulesFRSHTWIND] = useState<
undefined | CSSRuleList
>(undefined);
const [cssRulesClaimed, setCssRulesClaimed] = useState<
undefined | CSSRuleList
>(undefined);
const cssRulesFRSHTWIND = useSignal<undefined | CSSRuleList>(undefined);
const cssRulesClaimed = useSignal<undefined | CSSRuleList>(undefined);
// Init
useEffect(() => {
// get <style id="__FRSH_TWIND">
setCssRulesFRSHTWIND(getCssrules("#__FRSH_TWIND"));
cssRulesFRSHTWIND.value = getCssrules("#__FRSH_TWIND");
// get <style data-twind="claimed">
// see https://github.com/tw-in-js/twind/blob/main/packages/core/src/sheets.ts#L5-L16
setCssRulesClaimed(
getCssrules('[data-twind="claimed"]:not(#__FRSH_TWIND)'),
cssRulesClaimed.value = getCssrules(
'[data-twind="claimed"]:not(#__FRSH_TWIND)',
);
});
@@ -37,22 +34,24 @@ export default function CheckDuplication() {
{/* Status of duplicates */}
{(() => {
if (cssRulesFRSHTWIND != null && cssRulesClaimed != null) {
if (cssRulesFRSHTWIND.value != null && cssRulesClaimed.value != null) {
return (
<div>
<p>Error :</p>
<p id="numDuplicates">
{`${
cmpCssRules(
cssRulesFRSHTWIND,
cssRulesClaimed,
cssRulesFRSHTWIND.value,
cssRulesClaimed.value,
)
}`}
</p>
<p>cssrules are duplicated</p>
</div>
);
} else if (cssRulesFRSHTWIND != null && cssRulesClaimed == null) {
} else if (
cssRulesFRSHTWIND.value != null && cssRulesClaimed.value == null
) {
return <p id="okNoDuplicates">Ok : No duplicates</p>;
} else {
return <p id="errorNoExistsRules">Error : Cssrules does not exist</p>;
@@ -1,5 +1,6 @@
// https://github.com/denoland/fresh/pull/1050
import { useEffect, useState } from "preact/hooks";
import { useEffect } from "preact/hooks";
import { useSignal } from "@preact/signals";
/**
* Returns a number of cssrules set by twind.
@@ -10,21 +11,19 @@ function getNumCssrules(): number | undefined {
}
export default function InsertCssrules() {
const [numDefCssRules, setNumDefCssRules] = useState<number | undefined>(
undefined,
);
const [numCssRules, setNumCssRules] = useState<number | undefined>(undefined);
const [insertedStyles, setInsertedStyles] = useState("");
const numDefCssRules = useSignal<number | undefined>(undefined);
const numCssRules = useSignal<number | undefined>(undefined);
const insertedStyles = useSignal("");
// Init numDefCssRules
useEffect(() => {
setNumDefCssRules(getNumCssrules());
numDefCssRules.value = getNumCssrules();
}, []);
// Init and Update numCssRules
useEffect(() => {
setNumCssRules(getNumCssrules());
}, [insertedStyles]);
numCssRules.value = getNumCssrules();
}, [insertedStyles.value]);
return (
<div>
@@ -33,22 +32,26 @@ export default function InsertCssrules() {
<div>
<p>Default Number of __FRSH_TWIND CssRules :</p>
<p id="defaultNumCssRules" class={`text-xl`}>
{numDefCssRules ? numDefCssRules : "Error : Cannot get cssrules"}
{numDefCssRules.value
? numDefCssRules.value
: "Error : Cannot get cssrules"}
</p>
</div>
<div>
<p>Current Number of __FRSH_TWIND CssRules :</p>
<p id="currentNumCssRules" class={`text-xl ${insertedStyles}`}>
{numCssRules ? numCssRules : "Error : Cannot get cssrules"}
<p id="currentNumCssRules" class={`text-xl ${insertedStyles.value}`}>
{numCssRules.value
? numCssRules.value
: "Error : Cannot get cssrules"}
</p>
</div>
{/* Status of insert css rules */}
{(() => {
if (insertedStyles === "") {
if (insertedStyles.value === "") {
return <p id="waitClickButton">Plese click button</p>;
} else if (numDefCssRules === numCssRules) {
} else if (numDefCssRules.value === numCssRules.value) {
return (
<p id="errorInsertCssrules">
{'Error: A cssrule has been inserted into a style sheet other than <style id="__FRSH_TWIND">'}
@@ -62,9 +65,9 @@ export default function InsertCssrules() {
<button
id="insertCssRuleButton"
onClick={() => {
setInsertedStyles("text-green-600");
insertedStyles.value = "text-green-600";
}}
disabled={insertedStyles === "" ? false : true}
disabled={insertedStyles.value === "" ? false : true}
>
Add `text-green-600` to Cureent Number Class
</button>
+4 -4
View File
@@ -1,4 +1,4 @@
import { useState } from "preact/hooks";
import { useSignal } from "@preact/signals";
import Prism from "https://esm.sh/prismjs@1.27.0";
import "https://esm.sh/prismjs@1.27.0/components/prism-typescript?no-check";
@@ -15,10 +15,10 @@ export default function CodeBox(props: CodeBoxProps) {
);
const onCopy = () => {
navigator.clipboard.writeText(props.code);
setCopied(true);
copied.value = true;
};
const [copied, setCopied] = useState(false);
const copied = useSignal(false);
return (
<div class="">
<details>
@@ -35,7 +35,7 @@ export default function CodeBox(props: CodeBoxProps) {
onClick={onCopy}
class="absolute top-2 right-2 px-3 py-2 border border-gray-400 rounded text-white bg-gray-800"
>
{copied ? "Copied!" : "Copy"}
{copied.value ? "Copied!" : "Copy"}
</button>
</div>
</details>
+9 -8
View File
@@ -1,10 +1,11 @@
import { ComponentChildren } from "preact";
import { useEffect, useState } from "preact/hooks";
import { useEffect } from "preact/hooks";
import { IS_BROWSER } from "$fresh/runtime.ts";
import * as Icons from "../components/Icons.tsx";
import { useSignal } from "@preact/signals";
export default function CopyArea(props: { children: ComponentChildren }) {
const [copied, setCopied] = useState(false);
const copied = useSignal(false);
async function handleClick() {
if (props.children === undefined || props.children === null) {
@@ -12,22 +13,22 @@ export default function CopyArea(props: { children: ComponentChildren }) {
}
try {
await navigator.clipboard.writeText(props.children.toString());
setCopied(true);
copied.value = true;
} catch (error) {
setCopied(false);
copied.value = false;
console.error((error && error.message) || "Copy failed");
}
}
useEffect(() => {
if (!copied) {
if (!copied.value) {
return;
}
const timer = setTimeout(() => {
setCopied(false);
copied.value = false;
}, 2000);
return () => clearTimeout(timer);
}, [copied]);
}, [copied.value]);
return (
<div class="bg(gray-800) rounded text-white flex items-center">
@@ -47,7 +48,7 @@ export default function CopyArea(props: { children: ComponentChildren }) {
aria-label="Copy to Clipboard"
disabled={!IS_BROWSER}
class={`rounded p-1.5 border border-gray-300 hover:bg-gray-700 ${
copied ? "text-green-500" : ""
copied.value ? "text-green-500" : ""
} relative`}
onClick={handleClick}
>
+24 -23
View File
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from "preact/hooks";
import { Spring, WaveTank } from "../components/WaveTank.ts";
import { useEffect, useRef } from "preact/hooks";
import { useSignal } from "@preact/signals";
import { WaveTank } from "../components/WaveTank.ts";
function easeInCirc(x: number) {
return 1 - Math.sqrt(1 - Math.pow(x, 2));
@@ -9,44 +10,44 @@ const waveTank = new WaveTank();
function LemonDrop() {
const SVG_WIDTH = 100;
const [counter, setCounter] = useState(0);
const [dropy, setDropy] = useState(60);
const [width, setWidth] = useState(SVG_WIDTH);
const widthRef = useRef(width);
const [springs, setSprings] = useState<Spring[]>(waveTank.springs);
const counter = useSignal(0);
const dropy = useSignal(60);
const width = useSignal(SVG_WIDTH);
const widthRef = useRef(width.value);
const springs = useSignal(waveTank.springs);
const requestIdRef = useRef<number>();
const grid = SVG_WIDTH / waveTank.waveLength;
const points = [
[0, 100],
[0, 0],
...springs.map((x, i) => [i * grid, x.p]),
[width, 0],
[width, 100],
...springs.value.map((x, i) => [i * grid, x.p]),
[width.value, 0],
[width.value, 100],
];
const springsPath = `${points.map((x) => x.join(",")).join(" ")}`;
const juice = `M18 ${63 + counter} C15 ${63 + counter} 16 ${
63 + counter
const juice = `M18 ${63 + counter.value} C15 ${63 + counter.value} 16 ${
63 + counter.value
} 12 61L9 56C2 33 62 -3 80 12C103 27 44 56 29 58C27 58 25 59 24 61C20 ${
63 + counter
} 21 ${63 + counter} 18 ${63 + counter}Z`;
63 + counter.value
} 21 ${63 + counter.value} 18 ${63 + counter.value}Z`;
function updateJuice(timestamp: number) {
const amp = 40;
const x = timestamp / 2000;
const saw = x - Math.floor(x);
if (saw < 0.6) {
setCounter(easeInCirc(saw) * amp);
setDropy(-100);
counter.value = easeInCirc(saw) * amp;
dropy.value = -100;
} else {
setCounter(easeInCirc(1 - saw) * amp * 0.1);
setDropy(70 + Math.pow(saw - 0.6, 2) * 10000);
counter.value = easeInCirc(1 - saw) * amp * 0.1;
dropy.value = 70 + Math.pow(saw - 0.6, 2) * 10000;
}
}
function update(timestamp: number) {
updateJuice(timestamp);
waveTank.update(waveTank.springs);
setSprings([...waveTank.springs]);
springs.value = [...waveTank.springs];
const offset = 500;
const saw = (timestamp + offset) / 2000 -
@@ -58,7 +59,7 @@ function LemonDrop() {
}
function resize() {
setWidth(document.body.clientWidth);
width.value = document.body.clientWidth;
}
function drop() {
@@ -69,8 +70,8 @@ function LemonDrop() {
}
useEffect(() => {
widthRef.current = width;
}, [width]);
widthRef.current = width.value;
}, [width.value]);
useEffect(() => {
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
@@ -102,7 +103,7 @@ function LemonDrop() {
role="img"
aria-label="Fresh logo"
>
<circle cx="18" cy={dropy} r="4" fill="white"></circle>
<circle cx="18" cy={dropy.value} r="4" fill="white"></circle>
<path
d="M11.9 96.3v24H7v-24h4.9Zm7.5 10.2v4h-8.8v-4h8.8Zm1-10.2v4h-9.8v-4h9.8ZM23.2 96.3H31c1.6 0 3 .3 4.1.9 1.1.5 2 1.3 2.6 2.4a8 8 0 0 1 1 4c0 1.3-.2 2.4-.6 3.3-.3 1-.8 1.7-1.5 2.3-.7.6-1.4 1-2.3 1.5l-1.5.8h-6.3v-4h4.3a3 3 0 0 0 1.7-.4c.4-.3.7-.7 1-1.2a5 5 0 0 0 .3-2c0-.7-.1-1.3-.3-1.9-.2-.5-.5-1-1-1.2-.3-.3-.9-.5-1.5-.5h-3v20h-4.8v-24Zm11 24-4.4-10.7h5l4.6 10.5v.2h-5.2ZM55.9 116.3v4H45.4v-4h10.5Zm-9-20v24H42v-24H47Zm7.6 9.8v3.8h-9.1v-3.8h9Zm1.4-9.8v4H45.4v-4h10.5ZM69 114c0-.4 0-.8-.2-1.1 0-.4-.2-.7-.5-1l-1-1-1.9-.8-2.6-1.2-2.2-1.5a6.5 6.5 0 0 1-1.7-2 6 6 0 0 1-.5-2.7c0-1 .1-2 .5-2.7a6 6 0 0 1 1.6-2.2c.7-.5 1.5-1 2.4-1.3a9.5 9.5 0 0 1 7.1.5c1.2.6 2 1.5 2.7 2.6.6 1 1 2.4 1 3.8h-5a5 5 0 0 0-.2-1.8c-.2-.5-.5-1-1-1.2-.4-.3-1-.5-1.6-.5-.6 0-1.1.2-1.5.4-.4.2-.7.6-1 1l-.2 1.4c0 .4.1.8.3 1.1l.8.8a21.3 21.3 0 0 0 2.8 1.4l2.9 1.4a9 9 0 0 1 2 1.8c.7.6 1 1.3 1.4 2a7.9 7.9 0 0 1-.1 5.5c-.4.8-.9 1.5-1.5 2.1a7 7 0 0 1-2.5 1.4c-2 .5-1 1.8-3 1.8s-1.3-1.5-3.2-1.8c-1-.3-2-.8-2.7-1.4a6.7 6.7 0 0 1-1.8-2.5c-.4-1-.6-2.2-.6-3.5h4.9c0 .7 0 1.3.2 1.8.1.5.3 1 .6 1.3.3.2.7.5 1.1.6.5.2 1 .2 1.5.2.7 0 1.2 0 1.6-.3.4-.3.6-.6.8-1 .2-.4.3-.9.3-1.4ZM90.5 106v4h-10v-4h10Zm-8.6-9.7v24h-4.8v-24h4.8Zm12.1 0v24h-4.8v-24H94Z"
fill="#0A140C"