Skip to content

Commit

Permalink
- [#] change to use text area; NOK
Browse files Browse the repository at this point in the history
  • Loading branch information
suntong committed Aug 18, 2023
1 parent c6369c0 commit 44d30b9
Showing 1 changed file with 68 additions and 3 deletions.
71 changes: 68 additions & 3 deletions 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 {
Expand Down Expand Up @@ -137,14 +139,77 @@ 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 }}'`),
app.Div().Text("Echos sent: "+strconv.Itoa(uc.echoCount)),
)
}

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(`<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="copy-svg h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>`)
}

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{})
}
Expand Down

0 comments on commit 44d30b9

Please sign in to comment.