diff --git a/front/front.go b/front/front.go index 3ef654a..a4e4e17 100644 --- a/front/front.go +++ b/front/front.go @@ -1,12 +1,14 @@ package front import ( + "fmt" + "strconv" + "time" + "github.com/goombaio/namegenerator" "github.com/maxence-charriere/go-app/v9/pkg/app" "github.com/nats-io/nats.go" "nhooyr.io/websocket" - "strconv" - "time" ) type appControl struct { @@ -137,7 +139,10 @@ func (uc *appControl) Render() app.UI { } }), app.Range(uc.messages).Slice(func(i int) app.UI { - return app.Div().Text(uc.messages[len(uc.messages)-1-i]) + //return app.Div().Text(uc.messages[len(uc.messages)-1-i]) + id := len(uc.messages) - 1 - i + app.Logf("chat[%d]: %s\n", id, uc.messages[id]) + return &CodeBlock{code: uc.messages[id], id: fmt.Sprintf("chat%02d", id)} }), app.H4().Text("For an echo use:"), app.Pre().Text(`nats -s 127.0.0.1:8501 req echo.`+uc.whoami+` '{{ Random 10 100 }}'`), @@ -145,6 +150,66 @@ func (uc *appControl) Render() app.UI { ) } +type CodeBlock struct { + app.Compo + id string + code string +} + +func (m *CodeBlock) Render() app.UI { + app.Logf("Rendering chat[%s]: %s\n", m.id, m.code) + return app.Div().Class("code-block").Body( + copySVG(), + &CopyButton{text: "Copy chat", from: m}, + app.Pre().Body( + app.Code().ID(m.id).Text(m.code), + ), + ) +} + +func copySVG() app.UI { + return app.Raw(``) +} + +type CopyButton struct { + app.Compo + from *CodeBlock + text string +} + +func (cb *CopyButton) Render() app.UI { + return app.Button().Class("copy-button").Text(cb.text).OnClick(cb.onClick) +} + +func (cb *CopyButton) onClick(ctx app.Context, e app.Event) { + // // using go + // app.Log("copy via go\n", cb.from.code) + + // // using element id + // val := app.Window().GetElementByID(cb.from.id).Get("innerHTML") + // app.Log("copy via dom\n", val.String()) + + isSecure := app.Window().Get("isSecureContext") + // app.Log("isSecureContext:", isSecure) + if isSecure.Bool() { + app.Window().Get("navigator").Get("clipboard"). + Call("writeText", cb.from.code) + } else { + copyToClipboard(cb.from.code) + } + cb.text = "Copied" + ctx.After(2*time.Second, cb.revertText) +} + +func (cb *CopyButton) revertText(ctx app.Context) { + cb.text = "Copy chat" +} + +func copyToClipboard(text string) { + //app.Log("Copying to clipboard: %q", text) + app.Window().Call("copyToClipboard", text) +} + func Create() { app.RouteWithRegexp("/.*", &appControl{}) }