This commit is contained in:
Star 2024-06-07 15:33:03 +08:00
commit 467289ceb2
19 changed files with 461 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.*
!.gitignore
go.sum
/build

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 apigo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

59
README.md Normal file
View File

@ -0,0 +1,59 @@
# client
create a web client
client plugin for web client framework by https://github.com/webview/webview_go
### create project and init client project
```shell
go install apigo.cloud/git/apigo/ag@latest
mkdir demo && cd demo
ag init client
```
### edit main.js
```javascript
import client from 'apigo.cloud/git/apigo/client'
let w = client.new('Hello', 800, 500)
w.loadFile('www/index.html')
w.run()
```
### tidy & run
```shell
ag tidy
ag run
```
### build
```shell
CGO_ENABLED=1 go build -o demo *.go
```
### build on windows
```shell
CGO_ENABLED=1 go build -o demo.exe -ldflags '-H windowsgui' *.go
```
[//]: # (### build for windows)
[//]: # (```shell)
[//]: # (CGO_ENABLED=1 GOOS=windows GOARCH=amd64 CGO_LDFLAGS="-static" CC=/usr/local/Cellar/mingw-w64/9.0.0_2/bin/x86_64-w64-mingw32-gcc CXX=/usr/local/Cellar/mingw-w64/9.0.0_2/bin/x86_64-w64-mingw32-g++ go build -o demo.exe -ldflags '-H windowsgui' *.go)
[//]: # (```)

9
_project/main.go Normal file
View File

@ -0,0 +1,9 @@
package main
import (
"apigo.cloud/git/apigo/gojs"
)
func main() {
gojs.RunFile("main.js", nil)
}

5
_project/main.js Normal file
View File

@ -0,0 +1,5 @@
import client from 'apigo.cloud/git/apigo/client'
let w = client.new('Hello', 800, 500)
w.loadFile('www/index.html')
w.run()

11
_project/www/index.html Normal file
View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello</title>
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>

8
go.mod Normal file
View File

@ -0,0 +1,8 @@
module apigo.cloud/git/apigo/client
go 1.18
require (
apigo.cloud/git/apigo/plugin v1.0.1
github.com/webview/webview_go v0.0.0-20240217094020-f8e8d34d29dd
)

6
node_modules/apigo.cloud/git/apigo/client.ts generated vendored Normal file
View File

@ -0,0 +1,6 @@
import {Webview} from 'apigo.cloud/git/apigo/clientType'
export default {
"newApp": function (title: string, width: number, height: number, sizeMode?: string, isDebug?: boolean): Webview {return},
"new": function (title: string, width: number, height: number, sizeMode?: string, isDebug?: boolean): Webview {return},
}

11
node_modules/apigo.cloud/git/apigo/clientType.ts generated vendored Normal file
View File

@ -0,0 +1,11 @@
export interface Webview {
close(): void
dispatch(f: () => void): void
eval(code: string): void
loadFile(file: string): void
loadURL(url: string): void
run(): void
setHtml(html: string): void
setSize(width: number, height: number, sizeMode?: string): void
setTitle(title: string): void
}

View File

@ -0,0 +1,6 @@
export default {
"os": function (): string {return},
"arch": function (): string {return},
"shell": function (command: string, ...args: Array<string>): Array<string> {return},
"sleep": function (ms: number): void {return},
}

9
node_modules/console/index.ts generated vendored Normal file
View File

@ -0,0 +1,9 @@
export default {
"input": function (prompt?: string): string {return},
"print": function (...args: Array<any>): void {return},
"println": function (...args: Array<any>): void {return},
"log": function (...args: Array<any>): void {return},
"info": function (...args: Array<any>): void {return},
"warn": function (...args: Array<any>): void {return},
"error": function (...args: Array<any>): void {return},
}

6
node_modules/logger/index.ts generated vendored Normal file
View File

@ -0,0 +1,6 @@
export default {
"debug": function (message: string, args?: Object): void {return},
"info": function (message: string, args?: Object): void {return},
"warn": function (message: string, args?: Object): void {return},
"error": function (message: string, args?: Object): void {return},
}

8
package.json Normal file
View File

@ -0,0 +1,8 @@
{
"devDependencies": {
"console": "v0.0.0",
"logger": "v0.0.0",
"apigo.cloud": "v0.0.0"
}
}

222
plugin.go Normal file
View File

@ -0,0 +1,222 @@
package client
import (
"apigo.cloud/git/apigo/plugin"
webview "github.com/webview/webview_go"
"os"
"path/filepath"
"sync"
)
var binds = map[string]interface{}{}
var bindsLock = sync.RWMutex{}
func Bind(name string, fn interface{}) {
bindsLock.Lock()
binds[name] = fn
bindsLock.Unlock()
}
func Unbind(name string) {
bindsLock.Lock()
delete(binds, name)
bindsLock.Unlock()
}
type Webview struct {
w webview.WebView
isRunning bool
isAsync bool
}
func (w *Webview) Run() {
w.isRunning = true
w.w.Run()
if w.isRunning {
w.isRunning = false
w.w.Destroy()
}
}
func (w *Webview) Close() {
if w.isRunning {
w.w.Terminate()
}
}
func (w *Webview) SetHtml(html string) {
w.w.SetHtml(html)
}
func (w *Webview) LoadURL(url string) {
w.w.Navigate(url)
}
func (w *Webview) LoadFile(file string) {
if filepath.IsAbs(file) {
w.w.Navigate("file://" + file)
} else {
curPath, _ := os.Getwd()
w.w.Navigate("file://" + filepath.Join(curPath, file))
}
}
func (w *Webview) Dispatch(f func()) {
w.w.Dispatch(f)
}
func (w *Webview) SetTitle(title string) {
w.w.SetTitle(title)
}
func (w *Webview) SetSize(width int, height int, sizeMode *string) {
hint := "none"
if sizeMode != nil {
hint = *sizeMode
}
switch hint {
case "none":
w.w.SetSize(width, height, webview.HintNone)
case "fixed":
w.w.SetSize(width, height, webview.HintFixed)
case "min":
w.w.SetSize(width, height, webview.HintMin)
case "max":
w.w.SetSize(width, height, webview.HintMax)
default:
w.w.SetSize(width, height, webview.HintNone)
}
}
func (w *Webview) Eval(code string) {
w.w.Eval(code)
}
//func (w *Webview) Bind(name string, f interface{}) error {
// fmt.Println(">>>>>>>>.bind", name, f)
// return w.w.Bind(name, f)
//}
//
//func (w *Webview) Unbind(name string) error {
// return w.w.Unbind(name)
//}
func (w *Webview) binds() {
tmpBinds := map[string]interface{}{}
bindsLock.RLock()
for k, v := range binds {
tmpBinds[k] = v
}
bindsLock.RUnlock()
for k, v := range tmpBinds {
_ = w.w.Bind(k, v)
}
_ = w.w.Bind("__closeWindow", w.Close)
_ = w.w.Bind("__setTitle", w.w.SetTitle)
_ = w.w.Bind("__setSize", w.SetSize)
_ = w.w.Bind("__eval", w.w.Eval)
w.w.Init(dialogCode)
w.w.Init(appCode)
}
func newWindow(title string, width int, height int, sizeMode *string, isDebug *bool) *Webview {
isDebugV := false
if isDebug != nil {
isDebugV = *isDebug
}
w := &Webview{w: webview.New(isDebugV)}
w.SetTitle(title)
w.SetSize(width, height, sizeMode)
w.binds()
return w
}
const appCode = `
let app = {
close: __closeWindow,
setTitle: __setTitle,
setSize: __setSize,
eval: __eval,
}
`
const dialogCode = `
window._dialogTexts = {'zh':{'Close':'关闭','Cancel':'取消','Confirm':'确定'}}
function _getDialogDefaultText(text) {return (window._dialogTexts[navigator.language] && window._dialogTexts[navigator.language][text]) || (window._dialogTexts[navigator.language.split('-')[0]] && window._dialogTexts[navigator.language.split('-')[0]][text]) || text}
window.alert = function (msg, buttonText) {return showDialog(msg, [buttonText || _getDialogDefaultText('Close')])}
window.confirm = function (msg, confirmButtonText, cancelButtonText) {return showDialog(msg, [cancelButtonText || _getDialogDefaultText('Cancel'), cancelButtonText || _getDialogDefaultText('Confirm')])}
window.prompt = function (msg, defaultValue, confirmButtonText, cancelButtonText) {return showDialog(msg, [cancelButtonText || _getDialogDefaultText('Cancel'), cancelButtonText || _getDialogDefaultText('Confirm')], [{value:defaultValue||''}])}
window.showDialog = function (msg, buttons, inputs) {
if(!document.querySelector('#_dialogStyle')){
let sDom = document.createElement('style')
sDom.id = '_dialogStyle'
sDom.textContent = '._dialogMask {position:fixed;left:0;right:0;top:0;bottom:0;background:rgba(128,128,128,0.7);display:flex;justify-content:center;align-items:center}\n' +
'._dialogPanel {background:#eee;padding:16px;min-width:300px;max-width:80%;max-height:80%;margin:auto;border-radius:10px;display:flex;flex-flow:column;overflow:auto}\n' +
'._dialogMessage {font-size:0.875rem;flex:1;overflow:auto;white-space:pre-wrap}\n' +
'._dialogInputs {display:flex;flex-flow:column;margin-top:8px}\n' +
'._dialogInputs input {flex:1;border:1px solid #aaa;border-radius:4px;min-height:28px;padding:0 8px}\n' +
'._dialogLine {text-align:end;padding:4px 0}\n' +
'._dialogButtons {text-align:end}\n' +
'._dialogButtons button {background:none;border:none;color:#999;min-height:28px;cursor:pointer;font-size:1rem;margin-left:10px}\n' +
'._dialogButtons button:hover {color:#999}\n' +
'._dialogButtons button:last-child {color:#06f}'
document.head.append(sDom)
}
return new Promise(resolve => {
let a = ['<div class="_dialogPanel">']
if (msg) a.push('<div class="_dialogMessage">__MSG__</div>'.replace(/__MSG__/, msg))
if (inputs && inputs.length) {
let a1 = ['<div class="_dialogInputs">']
for (let i = 0; i < inputs.length; i++){
a1.push('<input id="_dialogInput__ID_____INPUT_INDEX__" placeholder="__INPUT_HINT__" value="__INPUT_VALUE__"/>'.replace(/__INPUT_INDEX__/, i + '').replace(/__INPUT_HINT__/, inputs[i].hint||'').replace(/__INPUT_VALUE__/, inputs[i].value||''))
}
a1.push('</div>')
a.push(a1.join(''))
}
a.push('<div class="_dialogLine"><hr/></div>')
let a2 = ['<div class="_dialogButtons">']
for (let i = 0; i < buttons.length; i++) a2.push('<button class="_dialogButton" onclick="_dialogAction__ID__(__BUTTON_INDEX__)">__BUTTON_LABEL__</button>'.replace(/__BUTTON_INDEX__/, i + '').replace(/__BUTTON_LABEL__/, buttons[i]))
a2.push('</div>')
a.push(a2.join(''))
let dialogId = Math.ceil(Math.random() * 10000000000).toString(36)
let w = document.createElement('div')
w.id = '_dialogWindow' + dialogId
w.className = '_dialogMask'
window['_dialogAction' + dialogId] = function (index) {
let isOK = index === buttons.length - 1
if (inputs && inputs.length) {
if (isOK) {
let inputValues = []
for (let i = 0; i < inputs.length; i++) inputValues.push(document.querySelector('#_dialogInput' + dialogId + '_' + i).value)
resolve(inputs.length === 1 ? inputValues[0] : inputValues)
} else {
resolve(false)
}
} else {
resolve(isOK ? true : index)
}
document.body.removeChild(document.querySelector('#_dialogWindow' + dialogId))
}
w.innerHTML = a.join('').replace(/__ID__/g, dialogId)
document.body.append(w)
})
}
`
func init() {
plugin.Register(plugin.Plugin{
Id: "apigo.cloud/git/apigo/client",
Name: "web client framework by github.com/webview/webview",
Objects: map[string]interface{}{
"newApp": func(title string, width int, height int, sizeMode *string, isDebug *bool) *Webview {
w := newWindow(title, width, height, sizeMode, isDebug)
// svc 框架
//w.w.Init(``)
return w
},
"new": func(title string, width int, height int, sizeMode *string, isDebug *bool) *Webview {
return newWindow(title, width, height, sizeMode, isDebug)
},
},
})
}

21
tests/go.mod Normal file
View File

@ -0,0 +1,21 @@
module tests
go 1.18
require (
apigo.cloud/git/apigo/gojs v0.0.8
current-plugin v0.0.0
github.com/ssgo/u v1.7.5
)
require (
apigo.cloud/git/apigo/plugin v1.0.1 // indirect
apigo.cloud/git/apigo/qjs v0.0.1 // indirect
github.com/ssgo/config v1.7.5 // indirect
github.com/ssgo/log v1.7.5 // indirect
github.com/ssgo/standard v1.7.5 // indirect
github.com/webview/webview_go v0.0.0-20240217094020-f8e8d34d29dd // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace current-plugin v0.0.0 => ../

BIN
tests/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

31
tests/plugin_run.go Normal file
View File

@ -0,0 +1,31 @@
package main
import (
"apigo.cloud/git/apigo/gojs"
"current-plugin"
"fmt"
"github.com/ssgo/u"
"os"
"strings"
)
func main() {
testOK := false
client.Bind("setTestOK", func(testIsOK bool) {
testOK = testIsOK
})
if files, err := os.ReadDir("."); err == nil {
for _, f := range files {
if !f.IsDir() && strings.HasSuffix(f.Name(), "_test.js") {
testName := f.Name()[0 : len(f.Name())-8]
r, err := gojs.RunFile(f.Name(), nil)
if err != nil || r != true || !testOK {
fmt.Println(u.BRed("test "+testName+" failed"), r, err)
} else {
fmt.Println(u.Green("test "+testName), u.BGreen("OK"))
}
}
}
}
}

8
tests/plugin_test.js Normal file
View File

@ -0,0 +1,8 @@
import client from 'apigo.cloud/git/apigo/client'
let w = client.new('Hello', 400, 400, 'none', true)
w.loadFile('test.html')
w.setTitle('测试')
w.setSize(800, 600)
w.run()
return true

28
tests/test.html Normal file
View File

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<script>
window.addEventListener('load', () => {
setTimeout(() => {
app.setTitle('测试标题')
alert('test')
app.setSize(600, 500, "fixed")
setTimeout(() => {
setTestOK(true)
app.close()
}, 1000)
}, 1000)
})
</script>
</head>
<body>
<img src="logo.png" width="20" onclick="showDialog('', ['No', 'Yes'], [{hint:'aaa',value:111},{hint:'bbb',value:222}]).then(v=>{console.info(v)})"/>
<h1>Hello, world!</h1>
<br/>
<button onclick="app.close()">关闭</button>
</div>
</body>
</html>