vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.78k stars 2.16k forks source link

convert example js_dom_draw to veb #22603

Open jorgeluismireles opened 6 days ago

jorgeluismireles commented 6 days ago

Describe the issue

Examples js_dom_draw and others (js_dom_cube) have README.md files describing how to compile v code to browser javascript manually for a node server or automatically for vweb to serve the html and js files.

You can delete node/vweb readme files and include a veb server as a main.v like this:

import veb
import os

const http_port = 3001

struct Context {
    veb.Context
}

pub struct App {
    veb.StaticHandler
}

fn main() {
    os.chdir(os.dir(os.executable()))!
    mut app := &App{}
    veb.run_at[App, Context](mut app, port: http_port)!
}

pub fn (mut app App) before_accept_loop() {
    os.execute_or_panic('v -b js_browser draw.js.v ') // create draw.js first!
    app.handle_static('.', true) or { panic('${err}') } // and the server will find it always
}

Is important to compile first the files js.v before calling app.handle_static otherwise, the first time when draw.js is not available at the current folder the server can't load it.

For the example at js_dom_cube use a similar main.v changing draw.js.v by cube.js.v.

I tested both examples and worked without touching index.html and *.js.v files:

v run examples/js_dom_draw/main.v 
[veb] Running app on http://localhost:3001/

Links

https://github.com/vlang/v/tree/master/examples/js_dom_cube

https://github.com/vlang/v/tree/master/examples/js_dom_draw

[!NOTE] You can use the šŸ‘ reaction to increase the issue's priority for developers.

Please note that only the šŸ‘ reaction to the issue itself counts as a vote. Other reactions and those to comments will not be taken into account.

Huly®: V_0.6-21052

jorgeluismireles commented 6 days ago

For the example wasm/mandelbrot replace the vweb serve_folder.v file with this veb main.v file to compile and serve the wasm:

import veb
import os

const http_port = 3001

struct Context {
    veb.Context
}

pub struct App {
    veb.StaticHandler
}

fn main() {
    os.chdir(os.dir(os.executable()))!
    mut app := &App{}
    veb.run_at[App, Context](mut app, port: http_port)!
}

pub fn (mut app App) before_accept_loop() {
    os.execute_or_panic('v -b wasm -os browser mandelbrot.wasm.v ')
    app.handle_static('.', true) or { panic('${err}') }
}

Rename mandelbrot.html to index.html to keep the server simple. Then:

$ v run examples/wasm/mandelbrot/main.v 
[veb] Running app on http://localhost:3001/