docs: add WASM library demo using Vite & React

This commit is contained in:
rzmk 2024-06-20 20:13:34 -04:00
parent bc05a9f46e
commit 93bc82bd36
27 changed files with 534 additions and 111 deletions

View file

@ -46,7 +46,7 @@ Or use `npm`, `pnpm`, or `yarn` instead of `bun`.
The following example is written in TypeScript:
```ts
import init, * as czv from "czv";
import init, * as czv from "czv-wasm";
// Must run `await init()` or `initSync()` first for web use
await init();

View file

@ -20,7 +20,7 @@ Or use `npm`, `pnpm`, or `yarn` instead of `bun`.
The following example is written in TypeScript:
```ts
import init, * as czv from "czv";
import init, * as czv from "czv-wasm";
// Must run `await init()` or `initSync()` first for web use
await init();
@ -48,7 +48,7 @@ cargo install wasm-pack
### Build WASM for web
```bash
wasm-pack build --release --target web --out-name czv
wasm-pack build --release --target web
```
**Note**: Currently you must modify the `pkg/package.json` by replacing the name from `czv-wasm` to `czv`.

View file

@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}

24
czv-wasm/examples/web-demo/.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View file

@ -1,7 +1,25 @@
# czv for WebAssembly web demo
# czv - web-demo
View `index.html` in a web browser and import a CSV file.
Demo website for the [czv](https://github.com/rzmk/czv) WebAssembly library built with Vite & React.
![Preview image](preview.png)
## Development
If you want to modify the TypeScript code then after you save your modifications you must run `tsc script.ts --module es2022 --target es2022` to generate a compatible `script.js` file.
1. Install the packages:
```bash
bun install
```
2. Build the site:
```bash
bun run build
```
3. Serve the site:
```bash
bun preview
```

Binary file not shown.

View file

@ -0,0 +1,17 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils"
}
}

View file

@ -1,46 +1,16 @@
<!DOCTYPE html>
<html id="html" lang="en">
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="pico.min.css" />
<title>czv demo</title>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>czv - WebAssembly library demo (using Vite & React)</title>
</head>
<body style="padding:1rem">
<div style="display: flex; gap: 2rem; justify-content: space-between;">
<h1>czv playground</h1>
<button class="outline secondary" style="height: fit-content; padding: 0.25rem;" onclick="const html = document.getElementById('html');
if (html.getAttribute('data-theme') === 'light')
html.setAttribute('data-theme', 'dark')
else
html.setAttribute('data-theme', 'light')">Switch
page theme</button>
</div>
<p>Import a CSV file and get statistical data from running <a href="https://github.com/rzmk/czv">czv</a> in your
browser using WASM.</p>
<input type="file" id="upload" accept=".csv" class="hidden" />
<label for="upload" style="display: none;" id="progress">Loading...</label>
<table style="width: 100%;" class="striped">
<thead>
<tr>
<th style="width: 10rem">Output type</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row count</td>
<td id="row-count"></td>
</tr>
<tr>
<td>Column count</td>
<td id="column-count"></td>
</tr>
</tbody>
</table>
<script src="script.js" type="module"></script>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View file

@ -0,0 +1,40 @@
{
"name": "web-demo",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-label": "^2.1.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"czv-wasm": "^0.0.0",
"lucide-react": "^0.395.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@types/node": "^20.14.7",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.19",
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.4",
"typescript": "^5.2.2",
"vite": "^5.2.0",
"vite-plugin-wasm-pack": "0.1.11"
}
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View file

@ -1,27 +0,0 @@
const progress = document.getElementById("progress");
import init, * as czv from "../../pkg/czv.js";
// Must run `await init()` or `initSync()` first for web use
await init();
const fileReader = new FileReader();
fileReader.onloadstart = () => {
if (progress)
progress.style.display = "block";
};
fileReader.onloadend = () => {
const rowCountElement = document.getElementById("row-count");
const columnCountElement = document.getElementById("column-count");
if (rowCountElement)
rowCountElement.innerText = String(czv.rowCount({
file_data: fileReader.result,
}));
if (columnCountElement)
columnCountElement.innerText = String(czv.columnCount({ file_data: fileReader.result }));
if (progress)
progress.style.display = "none";
};
const input = document.getElementById("upload");
if (input)
input.addEventListener("change", () => {
// @ts-ignore
fileReader.readAsText(input.files[0]);
});

View file

@ -1,34 +0,0 @@
const progress = document.getElementById("progress");
import init, * as czv from "../../pkg/czv.js";
// Must run `await init()` or `initSync()` first for web use
await init();
const fileReader = new FileReader();
fileReader.onloadstart = () => {
if (progress) progress.style.display = "block";
};
fileReader.onloadend = () => {
const rowCountElement = document.getElementById("row-count");
const columnCountElement = document.getElementById("column-count");
if (rowCountElement)
rowCountElement.innerText = String(
czv.rowCount({
file_data: fileReader.result as string,
})
);
if (columnCountElement)
columnCountElement.innerText = String(
czv.columnCount({ file_data: fileReader.result as string })
);
if (progress) progress.style.display = "none";
};
const input = document.getElementById("upload");
if (input)
input.addEventListener("change", () => {
// @ts-ignore
fileReader.readAsText(input.files[0]);
});

View file

@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View file

@ -0,0 +1,80 @@
import "./App.css";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import init, * as czv from "czv-wasm";
import React, { useState } from "react";
function App() {
const [initDone, setInitDone] = useState(false);
const [loading, setLoading] = useState(false);
const [rowCount, setRowCount] = useState<number | undefined>(undefined);
const [columnCount, setColumnCount] = useState<number | undefined>(
undefined
);
const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
setLoading(true);
if (!initDone) {
await init();
setInitDone(true);
}
if (e.target.files && e.target.files.length === 1) {
const rowCountOutput = czv.rowCount({
file_data: await e.target.files[0].text(),
});
setRowCount(rowCountOutput);
const columnCountOutput = czv.columnCount({
file_data: await e.target.files[0].text(),
});
setColumnCount(columnCountOutput);
}
setLoading(false);
};
return (
<>
<div className="grid text-left w-full gap-1.5">
<hgroup>
<h1 className="scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl">
czv - WebAssembly library demo using Vite & React
</h1>
<p className="text-xl text-muted-foreground mb-4">
Visit{" "}
<a
className="text-cyan-400"
href="https://github.com/rzmk/czv"
>
here
</a>{" "}
for the czv source code and{" "}
<a
className="text-cyan-400"
href="https://github.com/rzmk/czv/tree/main/czv-wasm/examples/web-demo"
>
here
</a>{" "}
for this site's source code.
</p>
</hgroup>
<Label htmlFor="csv">Import your CSV file</Label>
<Input onChange={handleFile} id="csv" type="file" />
{loading && <p>Loading...</p>}
{rowCount && (
<p>
<strong>Row count (excluding header row)</strong>:{" "}
{rowCount}
</p>
)}
{columnCount && (
<p>
<strong>Column count</strong>: {columnCount}
</p>
)}
</div>
</>
);
}
export default App;

View file

@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View file

@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View file

@ -0,0 +1,76 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 240 5.9% 10%;
--primary-foreground: 0 0% 98%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 240 10% 3.9%;
--radius: 0.5rem;
}
.dark {
--background: 240 10% 3.9%;
--foreground: 0 0% 98%;
--card: 240 10% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 240 10% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 240 5.9% 10%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 240 3.7% 15.9%;
--muted-foreground: 240 5% 64.9%;
--accent: 240 3.7% 15.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 240 4.9% 83.9%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

View file

@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View file

@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)

View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

View file

@ -0,0 +1,77 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
prefix: "",
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
}

View file

@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View file

@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}

View file

@ -0,0 +1,13 @@
import path from "path";
import react from "@vitejs/plugin-react-swc";
import wasmPack from "vite-plugin-wasm-pack";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react(), wasmPack([], ["czv-wasm"])],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});

View file

@ -7,7 +7,7 @@
//! Let's say we want to print the total number of non-header rows in our data:
//!
//! ```js
//! import init, * as czv from "czv";
//! import init, * as czv from "czv-wasm";
//! // Must run `await init()` or `initSync()` first for web use
//! await init();
//!