Compare commits

...

6 Commits

Author SHA1 Message Date
Lea Anthony dd6235f7d9 Add Fullscreen HTML content hook 2023-07-19 20:54:19 +10:00
github-actions[bot] 7f402bf0c4 chore: update sponsors.svg (#2778)
Co-authored-by: leaanthony <leaanthony@users.noreply.github.com>
2023-07-18 23:04:16 +10:00
Lea Anthony 1e76b0b52e Remove markdown formatter 2023-07-18 21:47:26 +10:00
figuerom16 e0a92712fe SvelteKit Guide: Manual installation, Bash installation, Usage Notes. (#2771)
* Create SvelteKit.mdx

* Rename SvelteKit.mdx to sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update sveltekit.mdx

* Update changelog.mdx
2023-07-15 23:52:33 +10:00
guangwu 150dac9ead chore: slice replace loop (#2757)
Signed-off-by: guoguangwu <guoguangwu@magic-shield.com>
2023-07-13 23:13:47 +10:00
Ethan Reesor 22cfcbd5a1 Override error formatting (#2717) 2023-07-13 20:40:22 +10:00
16 changed files with 201 additions and 59 deletions
@@ -1,33 +0,0 @@
name: Format Markdown Files
jobs:
format_markdown_files:
runs-on: ubuntu-latest
if: github.repository == 'wailsapp/wails'
steps:
- uses: actions/checkout@v3
- name: Setup Nodejs
uses: actions/setup-node@v2
with:
node-version: 18.x
- name: Install Task
uses: arduino/setup-task@v1
with:
version: 3.x
repo-token: ${{ secrets.GITHUB_TOKEN }}
- name: Format All Markdown Files
run: task format-all-md
- name: Create Pull Request
uses: peter-evans/create-pull-request@v4
with:
commit-message: "docs: format document"
title: "docs: format document"
body: "- [x] Format all Markdown(x) documents"
branch: chore/format-markdown-files
delete-branch: true
draft: false
+1 -1
View File
@@ -33,7 +33,7 @@ require (
github.com/tc-hib/winres v0.1.5
github.com/tidwall/sjson v1.1.7
github.com/tkrajina/go-reflector v0.5.6
github.com/wailsapp/go-webview2 v1.0.1
github.com/wailsapp/go-webview2 v1.0.3
github.com/wailsapp/mimetype v1.4.1
github.com/wzshiming/ctc v1.2.3
golang.org/x/mod v0.8.0
+6
View File
@@ -216,6 +216,12 @@ github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQ
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/wailsapp/go-webview2 v1.0.1 h1:dEJIeEApW/MhO2tTMISZBFZPuW7kwrFA1NtgFB1z1II=
github.com/wailsapp/go-webview2 v1.0.1/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo=
github.com/wailsapp/go-webview2 v1.0.2 h1:ypcJYe+f40+n8XjmV2nSsy3Dw506o6KYbt46tW4PFW4=
github.com/wailsapp/go-webview2 v1.0.2/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo=
github.com/wailsapp/go-webview2 v1.0.3-0.20230719093920-78c663df5f6e h1:hx4lfIEbo+GT0leauS5OQPS5GDfeBA9bGf9pcq1YWpc=
github.com/wailsapp/go-webview2 v1.0.3-0.20230719093920-78c663df5f6e/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo=
github.com/wailsapp/go-webview2 v1.0.3 h1:zgZgT58vNZauH0WF7chQbs6QGMybzzkPtZFb5c1Zb3Y=
github.com/wailsapp/go-webview2 v1.0.3/go.mod h1:Uk2BePfCRzttBBjFrBmqKGJd41P6QIHeV9kTgIeOZNo=
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
github.com/wzshiming/ctc v1.2.3 h1:q+hW3IQNsjIlOFBTGZZZeIXTElFM4grF4spW/errh/c=
+1 -1
View File
@@ -213,7 +213,7 @@ func CreateApp(appoptions *options.App) (*App, error) {
eventHandler := runtime.NewEvents(myLogger)
ctx = context.WithValue(ctx, "events", eventHandler)
messageDispatcher := dispatcher.NewDispatcher(ctx, myLogger, appBindings, eventHandler)
messageDispatcher := dispatcher.NewDispatcher(ctx, myLogger, appBindings, eventHandler, appoptions.ErrorFormatter)
// Create the frontends and register to event handler
desktopFrontend := desktop.NewFrontend(ctx, appoptions, myLogger, appBindings, messageDispatcher)
+1 -1
View File
@@ -82,7 +82,7 @@ func CreateApp(appoptions *options.App) (*App, error) {
ctx = context.WithValue(ctx, "buildtype", "production")
}
messageDispatcher := dispatcher.NewDispatcher(ctx, myLogger, appBindings, eventHandler)
messageDispatcher := dispatcher.NewDispatcher(ctx, myLogger, appBindings, eventHandler, appoptions.ErrorFormatter)
appFrontend := desktop.NewFrontend(ctx, appoptions, myLogger, appBindings, messageDispatcher)
eventHandler.AddFrontend(appFrontend)
@@ -453,6 +453,7 @@ func (f *Frontend) setupChromium() {
chromium.MessageCallback = f.processMessage
chromium.WebResourceRequestedCallback = f.processRequest
chromium.NavigationCompletedCallback = f.navigationCompleted
chromium.ContainsFullScreenElementChangedCallback = f.fullscreenChanged
chromium.AcceleratorKeyCallback = func(vkey uint) bool {
w32.PostMessage(f.mainWindow.Handle(), w32.WM_KEYDOWN, uintptr(vkey), 0)
return false
@@ -813,6 +814,18 @@ func (f *Frontend) onFocus(arg *winc.Event) {
f.chromium.Focus()
}
func (f *Frontend) fullscreenChanged(sender *edge.ICoreWebView2, _ *edge.ICoreWebView2ContainsFullScreenElementChangedEventArgs) {
isFullscreen, err := sender.GetContainsFullScreenElement()
if err != nil {
log.Fatal(err)
}
if isFullscreen {
f.mainWindow.Fullscreen()
} else {
f.mainWindow.UnFullscreen()
}
}
func coreWebview2RequestToHttpRequest(coreReq *edge.ICoreWebView2WebResourceRequest) func() (*http.Request, error) {
return func() (r *http.Request, err error) {
header := http.Header{}
+9 -3
View File
@@ -3,8 +3,9 @@ package dispatcher
import (
"encoding/json"
"fmt"
"github.com/wailsapp/wails/v2/internal/frontend"
"strings"
"github.com/wailsapp/wails/v2/internal/frontend"
)
type callMessage struct {
@@ -49,7 +50,12 @@ func (d *Dispatcher) processCallMessage(message string, sender frontend.Frontend
CallbackID: payload.CallbackID,
}
if err != nil {
callbackMessage.Err = err.Error()
// Use the error formatter if one was provided
if d.errfmt != nil {
callbackMessage.Err = d.errfmt(err)
} else {
callbackMessage.Err = err.Error()
}
} else {
callbackMessage.Result = result
}
@@ -66,7 +72,7 @@ func (d *Dispatcher) processCallMessage(message string, sender frontend.Frontend
// CallbackMessage defines a message that contains the result of a call
type CallbackMessage struct {
Result interface{} `json:"result"`
Err string `json:"error"`
Err any `json:"error"`
CallbackID string `json:"callbackid"`
}
@@ -7,6 +7,7 @@ import (
"github.com/wailsapp/wails/v2/internal/binding"
"github.com/wailsapp/wails/v2/internal/frontend"
"github.com/wailsapp/wails/v2/internal/logger"
"github.com/wailsapp/wails/v2/pkg/options"
)
type Dispatcher struct {
@@ -15,15 +16,17 @@ type Dispatcher struct {
events frontend.Events
bindingsDB *binding.DB
ctx context.Context
errfmt options.ErrorFormatter
}
func NewDispatcher(ctx context.Context, log *logger.Logger, bindings *binding.Bindings, events frontend.Events) *Dispatcher {
func NewDispatcher(ctx context.Context, log *logger.Logger, bindings *binding.Bindings, events frontend.Events, errfmt options.ErrorFormatter) *Dispatcher {
return &Dispatcher{
log: log,
bindings: bindings,
events: events,
bindingsDB: bindings.DB(),
ctx: ctx,
errfmt: errfmt,
}
}
+1 -3
View File
@@ -47,9 +47,7 @@ func (c *Command) Stderr() string {
}
func (c *Command) AddArgs(args []string) {
for _, arg := range args {
c.args = append(c.args, arg)
}
c.args = append(c.args, args...)
}
// CreateCommand returns a *Cmd struct that when run, will run the given command + args in the given directory
+1 -3
View File
@@ -99,8 +99,6 @@ func Combo(key string, modifier1 Modifier, modifier2 Modifier, rest ...Modifier)
Key: key,
Modifiers: []Modifier{modifier1, modifier2},
}
for _, extra := range rest {
result.Modifiers = append(result.Modifiers, extra)
}
result.Modifiers = append(result.Modifiers, rest...)
return result
}
+1 -3
View File
@@ -17,9 +17,7 @@ func (m *Menu) Append(item *MenuItem) {
// Merge will append the items in the given menu
// into this menu
func (m *Menu) Merge(menu *Menu) {
for _, item := range menu.Items {
m.Items = append(m.Items, item)
}
m.Items = append(m.Items, menu.Items...)
}
// AddText adds a TextMenu item to the menu
+5
View File
@@ -64,6 +64,9 @@ type App struct {
Bind []interface{}
WindowStartState WindowStartState
// ErrorFormatter overrides the formatting of errors returned by backend methods
ErrorFormatter ErrorFormatter
// CSS property to test for draggable elements. Default "--wails-draggable"
CSSDragProperty string
@@ -90,6 +93,8 @@ type App struct {
Debug Debug
}
type ErrorFormatter func(error) any
type RGBA struct {
R uint8 `json:"r"`
G uint8 `json:"g"`
+133
View File
@@ -0,0 +1,133 @@
# SvelteKit
This guide will go into:
1. Miminal Installation Steps - The steps needed to get a minimum Wails setup working for SvelteKit.
2. Install Script - Bash script for accomplishing the Minimal Installation Steps with optional Wails branding.
3. Important Notes - Issues that can be encountered when using SvelteKit + Wails and fixes.
## 1. Minimal Installation Steps
##### Install Wails for Svelte.
- `wails init -n myapp -t svelte`
##### Delete the svelte frontend.
- Navigate into your newly created myapp folder.
- Delete the folder named "frontend"
##### While in the Wails project root. Use your favorite package manager and install SvelteKit as the new frontend. Follow the prompts.
- `npm create svelte@latest frontend`
##### Modify wails.json.
- Add `"wailsjsdir": "./frontend/src/lib",` Do note that this is where your Go and runtime functions will appear.
- Change your package manager frontend here if not using npm.
##### Modify main.go.
- The first comment `//go:embed all:frontend/dist` needs to be changed to `//go:embed all:frontend/build`
##### Install/remove dependencies using your favorite package manager.
- Navigate into your "frontend" folder.
- `npm i`
- `npm uninstall @sveltejs/adapter-auto`
- `npm i -D @sveltejs/adapter-static`
##### Change adapter in svelte.config.js
- First line of file change `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';`
##### Put SvelteKit into SPA mode with prerendering.
- Create a file under myapp/frontend/src/routes/ named +layout.ts/+layout.js.
- Add two lines into the newly created file `export const prerender = true` and `export const ssr = false`
##### Test installation.
- Navigate back into the Wails project root (one directory up).
- run `wails dev`
- If the application doesn't run please check through the previous steps.
## 2. Install Script
##### This Bash Script does the steps listed above. Make sure to read over the script and understand what the script is doing on your computer.
- Create a file sveltekit-wails.sh
- Copy the below code into the new file then save it.
- Make it executable with `chmod +x sveltekit-wails.sh`
- Brand is an optional param below that adds back in the wails branding. Leave third param blank to not insert the Wails branding.
- Example usage: `./sveltekit-wails.sh pnpm newapp brand`
##### sveltekit-wails.sh:
```
manager=$1
project=$2
brand=$3
wails init -n $project -t svelte
cd $project
sed -i "s|npm|$manager|g" wails.json
sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json
sed -i "s|all:frontend/dist|all:frontend/build|" main.go
if [[ -n $brand ]]; then
mv frontend/src/App.svelte +page.svelte
sed -i "s|'./assets|'\$lib/assets|" +page.svelte
sed -i "s|'../wails|'\$lib/wails|" +page.svelte
mv frontend/src/assets .
fi
rm -r frontend
$manager create svelte@latest frontend
if [[ -n $brand ]]; then
mv +page.svelte frontend/src/routes/+page.svelte
mkdir frontend/src/lib
mv assets frontend/src/lib/
fi
cd frontend
$manager i
$manager uninstall @sveltejs/adapter-auto
$manager i -D @sveltejs/adapter-static
echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts
sed -i "s|-auto';|-static';|" svelte.config.js
cd ..
wails dev
```
## 3. Important Notes
##### Server files will cause build failures.
- +layout.server.ts, +page.server.ts, +server.ts or any file with "server" in the name will fail to build as all routes are prerendered.
##### The Wails runtime unloads with full page navigations!
- Anything that causes full page navigations: `window.location.href = '/<some>/<page>'` or Context menu reload when using wails dev. What this means is that you can end up losing the ability to call any runtime breaking the app. There are two ways to work around this.
- Use `import { goto } from '$app/navigation'` then call `goto('/<some>/<page>')` in your +page.svelte. This will prevent a full page navigation.
- If full page navigation can't be prevented the Wails runtime can be added to all pages by adding the below into the <head> of myapp/frontend/src/app.html
```
<head>
...
<meta name="wails-options" content="noautoinject" />
<script src="/wails/ipc.js"></script>
<script src="/wails/runtime.js"></script>
...
</head>
```
See https://wails.io/docs/guides/frontend for more information.
##### Inital data can be loaded and refreshed from +page.ts/+page.js to +page.svelte.
- +page.ts/+page.js works well with load() https://kit.svelte.dev/docs/load#page-data
- invalidateAll() in +page.svelte will call load() from +page.ts/+page.js https://kit.svelte.dev/docs/load#rerunning-load-functions-manual-invalidation.
##### Error Handling
- Expected errors using Throw error works in +page.ts/+page.js with a +error.svelte page. https://kit.svelte.dev/docs/errors#expected-errors
- Unexpected errors will cause the application to become unusable. Only recovery option (known so far) from unexpected errors is to reload the app. To do this create a file myapp/frontend/src/hooks.client.ts then add the below code to the file.
```
import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime'
export async function handleError() {
WindowReloadApp()
}
```
##### Using Forms and handling functions
- The simplest way is to call a function from the form is the standard, bind:value your variables and prevent submission `<form method="POST" on:submit|preventDefault={handle}>`
- The more advanced way is to use:enhance (progressive enhancement) which will allow for convenient access to formData, formElement, submitter. The important note is to always cancel() the form which prevents server side behavior. https://kit.svelte.dev/docs/form-actions#progressive-enhancement Example:
```
<form method="POST" use:enhance={({cancel, formData, formElement, submitter}) => {
cancel()
console.log(Object.fromEntries(formData))
console.log(formElement)
console.log(submitter)
handle()
}}>
```
+9
View File
@@ -58,6 +58,7 @@ func main() {
Bind: []interface{}{
app,
},
ErrorFormatter: func(err error) any { return err.Error() },
Windows: &windows.Options{
WebviewIsTransparent: false,
WindowIsTranslucent: false,
@@ -477,6 +478,14 @@ A slice of struct instances defining methods that need to be bound to the fronte
Name: Bind<br/>
Type: `[]interface{}`
### ErrorFormatter
A function that determines how errors are formatted when returned by a JS-to-Go
method call. The returned value will be marshalled as JSON.
Name: ErrorFormatter<br/>
Type: `func (error) any`
### Windows
This defines [Windows specific options](#windows).
+2
View File
@@ -27,6 +27,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added `-devtools` production build flag. Added by @mmghv in [PR](https://github.com/wailsapp/wails/pull/2725)
- Added `EnableDefaultContextMenu` option to allow enabling the browser's default context-menu in production . Added by @mmghv in [PR](https://github.com/wailsapp/wails/pull/2733)
- Added smart functionality for the default context-menu in production with CSS styles to control it. Added by @mmghv in [PR](https://github.com/wailsapp/wails/pull/2748)
- Added custom error formatting to allow passing structured errors back to the frontend.
- Added sveltekit.mdx guide. Added by @figuerom16 in [PR](https://github.com/wailsapp/wails/pull/2771)
### Changed
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 140 KiB