Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Javascript Interoperation #859

Closed
suntong opened this issue Aug 4, 2023 · 15 comments
Closed

Javascript Interoperation #859

suntong opened this issue Aug 4, 2023 · 15 comments

Comments

@suntong
Copy link

suntong commented Aug 4, 2023

So I've checked https://go-app.dev/js#intro page, but I'm still not too clear on how to invoke Javascript from go-app.

I've provided an almost working example here. In its test folder, the Javascript invoked fine from html page.

However, the same content, when rendered with go-app, the Javascript was not able to be invoked.

I tried to ask ChatGPT for an answer, and this is what I got (handling onclick using go-app):

func (m *CodeBlockModel) Render() app.UI {
	return app.Div().Body(
		app.Button().
			OnClick(m.OnCopy).
			Body(
				app.Img().Src("copy-icon.svg").Alt("Copy Icon"),
			),
		app.Pre().Body(
			app.Code().Text(m.Code),
		),
	)
}

func (m *CodeBlockModel) OnCopy(ctx app.Context, e app.Event) {
	tempInput := app.Window().Document().CreateElement("textarea")
	tempInput.Set("value", m.Code)
	app.Window().Document().Body().AppendChild(tempInput)

	tempInput.Call("select")
	app.Window().Document().Call("execCommand", "copy")

	app.Window().Document().Body().RemoveChild(tempInput)

	fmt.Println("Code copied!")

	// Trigger a model update to change the button state
	m.Update()
}

However, I cannot even get it compiles.

Sorry this is a bit OT. Anyone can help please?

@mlctrez
Copy link
Contributor

mlctrez commented Aug 4, 2023

@suntong

See https://github.com/mlctrez/imgtofactbp/blob/master/components/clipboard/clipboard.go#L41 for an alternate method for placing text into the clipboard using the window.navigator.clipboard api. I think this is what you're trying to do.

@suntong
Copy link
Author

suntong commented Aug 4, 2023

Wow, amazing response speed!

@suntong
Copy link
Author

suntong commented Aug 14, 2023

alternate method for placing text into the clipboard using the window.navigator.clipboard api

I gave it a try (finally), but nothing get copied on click.

would you see what I'm missing please?

@suntong suntong reopened this Aug 14, 2023
@mlctrez
Copy link
Contributor

mlctrez commented Aug 14, 2023

Your code example works for me.. Clicking the button results in the code text block being present in the clipboard.

There are some broken symbolic links in your repository that result errors loading the service worker:

web/script.js -> ../test/script.js
web/styles.css -> ../test/styles.css

@suntong
Copy link
Author

suntong commented Aug 14, 2023

There are some broken symbolic links in your repository

Ops, yeah, thx, fixed now.

Your code example works for me.. Clicking the button results in the code text block being present in the clipboard.

Oh, I tried to view different X selections, including "primary" XA_PRIMARY (default), "secondary" for XA_SECONDARY or "clipboard" for XA_CLIPBOARD, none is replaced with the code text block.

Is any of your env different from mine pls:

$ uname -rm
6.1.0-9-amd64 x86_64

$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 12 (bookworm)
Release:        12
Codename:       bookworm

$ apt-cache policy google-chrome-stable
google-chrome-stable:
  Installed: 114.0.5735.133-1
  Candidate: 115.0.5790.170-1
  Version table:
     115.0.5790.170-1 500
        500 https://dl.google.com/linux/chrome/deb stable/main amd64 Packages
 *** 114.0.5735.133-1 100
        100 /var/lib/dpkg/status

@mlctrez
Copy link
Contributor

mlctrez commented Aug 14, 2023

I'm not sure about the X selections that you posted.
For me, pasting into a text editor ( or console ) resulted with the correct result.

@oderwat
Copy link
Sponsor Contributor

oderwat commented Aug 14, 2023

@suntong You are running the browser on Debian? A quick search gave me: https://www.reddit.com/r/gnome/comments/11lrn4j/chromes_clipboard_is_getting_broken_under_linux/

Did you try another browser or OS yet?

@mlctrez I guess you are not testing it with Google-Chrome on Linux?

@oderwat
Copy link
Sponsor Contributor

oderwat commented Aug 14, 2023

About the clipboard and calling JavaScript. In one of our projects, I do this:

First I added this JavaScript in the RAWHeaders section of the app.Handler

<script>
    function copyToClipboard(text) {
        if (window.clipboardData && window.clipboardData.setData) {
            // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
            return window.clipboardData.setData("Text", text);

        } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
            // fallback for old browsers (probably not needed)
            var textarea = document.createElement("textarea");
            textarea.textContent = text;
            textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
            document.body.appendChild(textarea);
            textarea.select();
            try {
                return document.execCommand("copy");  // Security exception may be thrown by some browsers.
            } catch (ex) {
                console.warn("Copy to clipboard failed.", ex);
                return prompt("Copy to clipboard: Ctrl+C, Enter", text);
            } finally {
                document.body.removeChild(textarea);
            }
        }
    }
</script>

But that could also be loaded with a js file in the /web/ folder, that then goes to the static resources in app.Handler instead.

In Go, I then just do:

func copyToClipboard(text string) {
	dbg.Logf("Copying to clipboard: %q", text)
	app.Window().Call("copyToClipboard", text)
}

This is effortless. It gets a bit harder when calling JavaScript that uses promises. I like to use https://github.com/js-max-pub/idbkv for indexdb access and there you need to do things like this

app.Window().Get("idbkv").Call("set", "mykey", buf.String()).Then(func(v app.Value) {
	dbg.Logf("Exported %s in %s", humz.Bytes(int64(buf.Len())), humz.Duration(time.Since(started)))
})

@suntong
Copy link
Author

suntong commented Aug 14, 2023

About the clipboard and calling JavaScript. In one of our projects, I do this:

That works like a charm! Thanks for the high-quality production-grade code!!!

For anyone who might be benefit from it, here is the fully working code

The minimum changes to get things working is here

@suntong
Copy link
Author

suntong commented Aug 14, 2023

Did you try another browser or OS yet?

I don't have any other browsers on three of my Linux machines, but I do have two browsers on my Android, which I tried, but neither is working. One is Google-Chrome.

@oderwat would you give it a try at your end please?
https://github.com/suntong/go-app-demos/tree/master/0B2C-codecopy

$ make run
GOARCH=wasm GOOS=js go build -o web/app.wasm
go build -o ./boostrap
./boostrap
2023/08/14 10:49:55 Listening on http://:8000

Thanks a lot.

@mlctrez what OS and which browser are you using? thx.

@mlctrez
Copy link
Contributor

mlctrez commented Aug 14, 2023

@suntong I'm using Chrome Version 115.0.5790.170 on Ubuntu 22.04
The original codebase is running at https://mlctrez.github.io/imgtofactbp/ if you need another point to test with.

@suntong
Copy link
Author

suntong commented Aug 14, 2023

Strange, I upgraded my google-chrome-stable from v114.0.5735.133-1 to v115.0.5790.170-1 and still NOK.

The original codebase is running at https://mlctrez.github.io/imgtofactbp/ if you need another point to test with.

"Clicking on the copy blueprint button will place the blueprint string into the clipboard" Oh, even that doesn't work for me. I have now tried on my Debian Desktop, Android Mobile and Win 10 Chrome Version 115.0.5790.170. None of them are working for me. Thanks

@mlctrez
Copy link
Contributor

mlctrez commented Aug 14, 2023

@suntong
For the https://mlctrez.github.io/imgtofactbp/ site, make sure you paste an image from the clipboard and select some sizes and types in the check boxes, otherwise the copy button does nothing.
You can check in the JS console for logging to confirm.

@suntong
Copy link
Author

suntong commented Aug 14, 2023

Ah, yes, the https://mlctrez.github.io/imgtofactbp/ site is working for me now. I only pasted an image before.

@suntong
Copy link
Author

suntong commented Aug 14, 2023

See #872 (comment)

@suntong suntong closed this as completed Aug 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants