Skip to content

Commit

Permalink
initial webpage with wasm
Browse files Browse the repository at this point in the history
  • Loading branch information
PKopel committed Nov 26, 2023
1 parent 61d182a commit bb9c67e
Show file tree
Hide file tree
Showing 18 changed files with 4,764 additions and 9 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
[workspace]
members = ["filegram", "filegram-cli", "filegram-web"]
resolver = "2"
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright (c) 2018 Paweł Kopel <pawel.kopel2@gmail.com>
Copyright (c) 2023 Paweł Kopel <pawel.kopel2@gmail.com>

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
Expand Down
2 changes: 2 additions & 0 deletions filegram-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ filegram = { path = "../filegram" }
# code size when deploying.
console_error_panic_hook = { version = "0.1.7", optional = true }
getrandom = { version = "0.2.11", features = ["js"] }
js-sys = "0.3.65"
image = "0.24.7"

[dev-dependencies]
wasm-bindgen-test = "0.3.34"
Expand Down
20 changes: 16 additions & 4 deletions filegram-web/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
mod utils;

use std::io::Cursor;

use filegram::{decode, encode};
use js_sys::Uint8Array;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
pub fn encode(contents: &[u8]) -> Uint8Array {
let rgb = encode::from_slice(contents);

let mut bytes: Vec<u8> = Vec::new();
rgb.write_to(&mut Cursor::new(&mut bytes), image::ImageOutputFormat::Png)
.unwrap();

Uint8Array::from(&bytes[..])
}

#[wasm_bindgen]
pub fn greet() {
alert("Hello, filegram-web!");
pub fn decode(bytes: &[u8]) -> Uint8Array {
let contents = decode::from_file(Cursor::new(&bytes[..]));

Uint8Array::from(&contents[..])
}
3 changes: 3 additions & 0 deletions filegram-web/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
Expand Down
7 changes: 3 additions & 4 deletions filegram-web/tests/web.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#![cfg(target_arch = "wasm32")]

extern crate wasm_bindgen_test;
use filegram::{decode, encode};
use filegram_web::{decode, encode};
use getrandom;

use wasm_bindgen_test::*;

#[wasm_bindgen_test]
Expand All @@ -12,8 +11,8 @@ fn encode_decode_test() {
getrandom::getrandom(&mut original_data).unwrap();
let original_data = original_data.to_vec();

let rgb = encode::from_slice(&original_data);
let data = decode::from_rgb(&rgb);
let rgb = encode(&original_data).to_vec();
let data = decode(&rgb).to_vec();

assert_eq!(original_data, data)
}
24 changes: 24 additions & 0 deletions filegram-web/www/.bin/create-wasm-app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env node

const { spawn } = require("child_process");
const fs = require("fs");

let folderName = '.';

if (process.argv.length >= 3) {
folderName = process.argv[2];
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName);
}
}

const clone = spawn("git", ["clone", "https://github.com/rustwasm/create-wasm-app.git", folderName]);

clone.on("close", code => {
if (code !== 0) {
console.error("cloning the template failed!")
process.exit(code);
} else {
console.log("🦀 Rust + 🕸 Wasm = ❤");
}
});
2 changes: 2 additions & 0 deletions filegram-web/www/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
5 changes: 5 additions & 0 deletions filegram-web/www/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
language: node_js
node_js: "10"

script:
- ./node_modules/.bin/webpack
25 changes: 25 additions & 0 deletions filegram-web/www/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) 2023 Paweł Kopel <pawel.kopel2@gmail.com>

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
67 changes: 67 additions & 0 deletions filegram-web/www/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<div align="center">

<h1><code>create-wasm-app</code></h1>

<strong>An <code>npm init</code> template for kick starting a project that uses NPM packages containing Rust-generated WebAssembly and bundles them with Webpack.</strong>

<p>
<a href="https://travis-ci.org/rustwasm/create-wasm-app"><img src="https://img.shields.io/travis/rustwasm/create-wasm-app.svg?style=flat-square" alt="Build Status" /></a>
</p>

<h3>
<a href="#usage">Usage</a>
<span> | </span>
<a href="https://discordapp.com/channels/442252698964721669/443151097398296587">Chat</a>
</h3>

<sub>Built with 🦀🕸 by <a href="https://rustwasm.github.io/">The Rust and WebAssembly Working Group</a></sub>
</div>

## About

This template is designed for depending on NPM packages that contain
Rust-generated WebAssembly and using them to create a Website.

* Want to create an NPM package with Rust and WebAssembly? [Check out
`wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template)
* Want to make a monorepo-style Website without publishing to NPM? Check out
[`rust-webpack-template`](https://github.com/rustwasm/rust-webpack-template)
and/or
[`rust-parcel-template`](https://github.com/rustwasm/rust-parcel-template).

## 🚴 Usage

```
npm init wasm-app
```

## 🔋 Batteries Included

- `.gitignore`: ignores `node_modules`
- `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you
- `README.md`: the file you are reading now!
- `index.html`: a bare bones html document that includes the webpack bundle
- `index.js`: example js file with a comment showing how to import and use a wasm pkg
- `package.json` and `package-lock.json`:
- pulls in devDependencies for using webpack:
- [`webpack`](https://www.npmjs.com/package/webpack)
- [`webpack-cli`](https://www.npmjs.com/package/webpack-cli)
- [`webpack-dev-server`](https://www.npmjs.com/package/webpack-dev-server)
- defines a `start` script to run `webpack-dev-server`
- `webpack.config.js`: configuration file for bundling your js with webpack

## License

Licensed under either of

* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.
5 changes: 5 additions & 0 deletions filegram-web/www/bootstrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// A dependency graph that contains any wasm must all be imported
// asynchronously. This `bootstrap.js` file does the single async import, so
// that no one else needs to worry about it again.
import("./index.js")
.catch(e => console.error("Error importing `index.js`:", e));
24 changes: 24 additions & 0 deletions filegram-web/www/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Hello wasm-pack!</title>
<style>
#drop_zone {
border: 5px solid blue;
width: 200px;
height: 100px;
}
</style>
</head>

<body>
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
<p>Drag one or more files to this <i>drop zone</i>.</p>
</div>

<script src="./bootstrap.js"></script>
</body>

</html>
41 changes: 41 additions & 0 deletions filegram-web/www/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import * as wasm from "filegram-web";


window.dragOverHandler = (ev) => {
console.log("File(s) in drop zone");

// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
};

window.dropHandler = (ev) => {
console.log("File(s) dropped");

// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();

if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
[...ev.dataTransfer.items].forEach((item, i) => {
// If dropped items aren't files, reject them
if (item.kind === "file") {
const file = item.getAsFile();
const bytes = file.arrayBuffer();
const encoded = wasm.encode(bytes);
// Make a Blob from the bytes
const blob = new Blob([encoded], { type: 'image/png' });

// Use createObjectURL to make a URL for the blob
const image = new Image();
image.src = URL.createObjectURL(blob);

document.body.appendChild(image);
}
});
} else {
// Use DataTransfer interface to access the file(s)
[...ev.dataTransfer.files].forEach((file, i) => {
console.log(`… file[${i}].name = ${file.name}`);
});
};
};
Loading

0 comments on commit bb9c67e

Please sign in to comment.