Skip to content

build web component #1034

@Its-Just-Nans

Description

@Its-Just-Nans

Could trunk become a webcomponent generator ?

Example with https://github.com/emilk/eframe_template

#!/bin/bash


cargo build --target wasm32-unknown-unknown
# cargo install -f wasm-bindgen-cli --version 0.2.106
OUTPUT=web_component
ELEMENT=eframe-example
rm -rf "$OUTPUT"
wasm-bindgen --target=web "--out-dir=target/wasm-bindgen/debug" "--out-name=eframe_template" "target/wasm32-unknown-unknown/debug/eframe_template.wasm" "--no-typescript"
mkdir -p "$OUTPUT"
cp target/wasm-bindgen/debug/eframe_template_bg.wasm "$OUTPUT"
cp target/wasm-bindgen/debug/eframe_template.js "$OUTPUT"
cat "$OUTPUT/eframe_template.js" > "$OUTPUT/temp.js"
echo "customElements.define('$ELEMENT',class extends HTMLElement {
    constructor() {
      super();
      const shadowRoot = this.attachShadow({ mode: 'open' });
      const canvas = document.createElement('canvas');
      canvas.id = 'the_canvas_id';
      shadowRoot.appendChild(canvas);
    }
    connectedCallback() {
        this.init();
    }
    async init() {
        const wasm = await __wbg_init({ module_or_path: './eframe_template_bg.wasm' });
        // window.wasmBindings = bindings;
        dispatchEvent(new CustomEvent('TrunkApplicationStarted', {detail: {wasm}}));
    }
  },
);" >> "$OUTPUT/temp.js"
mv "$OUTPUT/temp.js" "$OUTPUT/eframe_template.js"


echo "
<script type='module' src='eframe_template.js'></script>
<eframe-example></eframe-example>
" > "$OUTPUT/index.html"

code to get the canvas inside the shadowRoot

let canvas = document
    .body()
    .expect("Failed to find <body>")
    .child_nodes()
    .get(0)
    .expect("Failed to find the CustomElement")
    .dyn_into::<web_sys::Element>()
    .expect("convert failed")
    .shadow_root()
    .expect("Failed to find shadowRoot")
    .dyn_into::<web_sys::ShadowRoot>()
    .expect("failed convert ShadowRoot")
    .get_element_by_id("the_canvas_id")
    .expect("Failed to find the_canvas_id")
    .dyn_into::<web_sys::HtmlCanvasElement>()
    .expect("the_canvas_id was not a HtmlCanvasElement");
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions