Skip to content

Instantly share code, notes, and snippets.

@Xevion
Created December 15, 2022 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xevion/6f8fb8e35878c2d65368bb115549e538 to your computer and use it in GitHub Desktop.
Save Xevion/6f8fb8e35878c2d65368bb115549e538 to your computer and use it in GitHub Desktop.
import React from "react";
import { Button } from "@chakra-ui/react";
import ReactDOMServer from "react-dom/server";
interface DipswitchProps {
length: number;
value: number;
}
interface DipswitchExporterProps {
startLength: number;
endLength: number;
}
const toBitArray = (length: number, value: number) => {
return Array(length)
.fill(1)
.map((v, i) => Boolean(value & (1 << i)));
};
/**
* Generates an SVG-based dipswitch graphic.
*
* @param length The number of switches in the graphic.
* @param value The value the dipswitch should be configured to represent. Each switch represents one bit of information from left to right.
* @constructor
*/
const Dipswitch = ({ length, value }: DipswitchProps) => {
const switches = toBitArray(length, value);
return (
<svg
viewBox={`0 0 ${30 + (50 + 30) * length} 220`}
xmlns="http://www.w3.org/2000/svg"
>
{switches.map((s, i) => (
<>
<rect
width="50"
height="160"
x={30 + 80 * i}
y="20"
strokeWidth="2"
fill="none"
stroke="black"
rx={2}
/>
<rect
width="30"
height="50"
x={30 + 10 + 80 * i}
y={30 + (s ? 0 : 90)}
rx={1}
/>
<text x={45 + 80 * i} y={215} fontSize={32}>
{i}
</text>
</>
))}
</svg>
);
};
export default Dipswitch;
export const DipswitchExporter = ({
startLength,
endLength,
}: DipswitchExporterProps) => {
return (
<Button
onClick={() => {
const exportObject: Record<string, string> = {};
// Build all SVG values
for (let curLength = startLength; curLength <= endLength; curLength++) {
Array(2 ** curLength)
.fill(1)
.map((_, i) => [
toBitArray(curLength, i)
.map((v) => (v ? "1" : "0"))
.join(""),
<Dipswitch length={curLength} value={i} />,
])
.forEach(([value, svg]) => {
exportObject[value.toString()] = ReactDOMServer.renderToString(
svg as React.ReactElement
);
});
}
// console.log(exportObject);
// Copy to clipboard
navigator.clipboard.writeText(
JSON.stringify(
exportObject,
Object.keys(exportObject).sort((s) => s.length),
4
)
);
}}
>
Copy to Clipboard
</Button>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment