wails/v3/internal/generator/render/create.go
Ian VanSchooten bbd5d99667
[v3] Typed Events, revisited (#4633)
* Add strong event typings

* Make `EmitEvent` take one data argument only

* Add event registration logic

* Report event cancellation to the emitter

* Prevent registration of system events

* Add support for typed event data initialisation

* Binding generation for events

* Tests for event bindings

* Add vite plugin for typed events

* Fix dev command execution order

Co-authored-by: Fabio Massaioli <fabio.massaioli@gmail.com>

* Propagate module path to templates

* Update templates

Co-authored-by: Ian VanSchooten <ian.vanschooten@gmail.com>

* Go mod tidy for examples

* Switch to tsconfig.json for jetbrains IDE support

* Replace jsconfig in example

* Convert vite plugin to typescript

* Downgrade vite for now

The templates all use 5.x

* Remove root plugins dir from npm files

It's now '/dist/plugins'

* Include types for Create

But keep out of the docs

* Assign a type for cancelAll results

* Restore variadic argument in EmitEvent methods

* Support registered events with void data

* Test cases for void alias support

* Support strict mode

* Support custom event hooks

* Update docs

* Update changelog

* Testdata for typed events

* Test data for void alias support

* fix webview_window emit event

* Update changelog.mdx

* Update events

* Fix generator test path normalization for cross-platform compatibility

The generator tests were failing on CI because they compared absolute file paths
in warning messages. These paths differ between development machines and CI environments.

Changes:
- Normalize file paths in warnings to be relative to testcases/ directory
- Handle both Unix and Windows path separators
- Use Unix line endings consistently in test output
- Update all test expectation files to use normalized paths

This ensures tests pass consistently across different environments including
Windows, macOS, Linux, and CI systems.

* Remove stale comment

* Handle errors returned from validation

* Restore variadic argument to Emit (fix bad rebase)

* Event emitters return a boolean

* Don't use `EmitEvent` in docs

Supposedly it's for internal use, according to comment

* Fix event docs (from rebase)

* Ensure all templates specify @wailsio/runtime: "latest"

* Fix Windows test failure due to CRLF line endings

The test was failing on Windows because:
1. Hardcoded "\n" was being used instead of render.Newline when writing
   warning logs, causing CRLF vs LF mismatch
2. The render package import was missing
3. .got.log files weren't being skipped when building expected file list

Changes:
- Add render package import
- Use render.Newline instead of hardcoded "\n" for cross-platform compatibility
- Skip .got.log files in test file walker

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix template tests by using local runtime package

The template tests were failing because they were installing @wailsio/runtime@latest from npm, which doesn't have the new vite plugin yet. This change packs the local runtime and uses it in template tests instead.

Changes:
- Pack the runtime to a tarball in test_js job
- Upload the runtime package as an artifact
- Download and install the local runtime in template tests before building
- Update cleanup job to delete the runtime package artifact

* Apply suggestion from @leaanthony

* Fix: Install local runtime in frontend directory with correct path

The previous fix wasn't working because:
1. npm install was run in the project root, not in frontend/
2. wails3 build runs npm install again, which would reinstall from npm

Fixed by:
- Using npm pkg set to modify package.json to use file:// protocol
- This ensures subsequent npm install calls use the local tarball

* Fix Vue template syntax conflicts with Go template delimiters

The Vue templates were converted to .tmpl files to support dynamic module
paths, but Vue's template syntax {{ }} conflicts with Go's template syntax.

Fixed by escaping Vue template braces:
- {{ becomes {{"{{"}}
- }} becomes {{"}}"}}

This allows the Go template engine to output the literal {{ }} for Vue to process.

* Fix Vue template escaping and Windows shell compatibility

Two issues fixed:

1. Vue template escaping: Changed from {{"{{"}} to {{ "{{" }}
   - The previous syntax caused "missing value for command" error
   - Correct Go template syntax uses spaces between delimiters and strings

2. Windows PowerShell compatibility: Added 'shell: bash' to template generation step
   - The bash syntax (ls, head, $()) doesn't work in PowerShell
   - Git Bash is available on all GitHub runners including Windows

* Fix: test_templates depends on test_js for runtime package artifact

The runtime-package artifact is created in test_js job, not test_go.
Added test_js to the needs array so the artifact is available for download.

* Fix Windows path compatibility for runtime package artifact

Changed from absolute Unix path '/tmp/wails-runtime' to relative path
'wails-runtime-temp' which works cross-platform. Using realpath to
convert to absolute path for file:// URL in npm pkg set command.

* Fix realpath issue on Windows for runtime package

realpath on Windows Git Bash was producing malformed paths with duplicate
drive letters (D:\d\a\...). Replaced with portable solution using pwd
that works correctly across all platforms.

* Use pwd -W on Windows to get native Windows paths

Git Bash's pwd returns Unix-style paths (/d/a/wails/wails) which npm
then incorrectly resolves as D:/d/a/wails/wails. Using pwd -W returns
native Windows paths (D:\a\wails\wails) that npm can handle correctly.

This is the root cause of all the Windows path issues.

* Improve typechecking for Events.Emit()

* [docs] Clarify where `Events` is imported from in each example

* Add docs for runtime Events.Emit()

* Revert to v2-style Events.Emit (name, data)

* Update changelog

---------

Co-authored-by: Fabio Massaioli <fabio.massaioli@gmail.com>
Co-authored-by: Atterpac <Capretta.Michael@gmail.com>
Co-authored-by: Lea Anthony <lea.anthony@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-11-11 20:25:57 +11:00

359 lines
9.2 KiB
Go

package render
import (
"fmt"
"go/types"
"strings"
"text/template"
"github.com/wailsapp/wails/v3/internal/generator/collect"
"golang.org/x/tools/go/types/typeutil"
)
// SkipCreate returns true if the given array of types needs no creation code.
func (m *module) SkipCreate(ts []types.Type) bool {
for _, typ := range ts {
if m.NeedsCreate(typ) {
return false
}
}
return true
}
// NeedsCreate returns true if the given type needs some creation code.
func (m *module) NeedsCreate(typ types.Type) bool {
return m.needsCreateImpl(typ, new(typeutil.Map))
}
// needsCreateImpl provides the actual implementation of NeedsCreate.
// The visited parameter is used to break cycles.
func (m *module) needsCreateImpl(typ types.Type, visited *typeutil.Map) bool {
switch t := typ.(type) {
case *types.Alias:
if m.collector.IsVoidAlias(t.Obj()) {
return false
}
return m.needsCreateImpl(types.Unalias(typ), visited)
case *types.Named:
if visited.Set(typ, true) != nil {
// The only way to hit a cycle here
// is through a chain of structs, nested pointers and arrays (not slices).
// We can safely return false at this point
// as the final answer is independent of the cycle.
return false
}
if t.Obj().Pkg() == nil {
// Builtin named type: render underlying type.
return m.needsCreateImpl(t.Underlying(), visited)
}
if m.collector.IsVoidAlias(t.Obj()) {
return false
}
if collect.IsAny(typ) || collect.IsStringAlias(typ) {
break
} else if collect.IsClass(typ) {
return true
} else {
return m.needsCreateImpl(t.Underlying(), visited)
}
case *types.Array, *types.Pointer:
return m.needsCreateImpl(typ.(interface{ Elem() types.Type }).Elem(), visited)
case *types.Map, *types.Slice:
return true
case *types.Struct:
if t.NumFields() == 0 || collect.MaybeJSONMarshaler(typ) != collect.NonMarshaler || collect.MaybeTextMarshaler(typ) != collect.NonMarshaler {
return false
}
info := m.collector.Struct(t)
info.Collect()
for _, field := range info.Fields {
if m.needsCreateImpl(field.Type, visited) {
return true
}
}
case *types.TypeParam:
return true
}
return false
}
// JSCreate renders JS/TS code that creates an instance
// of the given type from JSON data.
//
// JSCreate's output may be incorrect
// if m.Imports.AddType has not been called for the given type.
func (m *module) JSCreate(typ types.Type) string {
return m.JSCreateWithParams(typ, "")
}
// JSCreateWithParams renders JS/TS code that creates an instance
// of the given type from JSON data. For generic types,
// it renders parameterised code.
//
// JSCreateWithParams's output may be incorrect
// if m.Imports.AddType has not been called for the given type.
func (m *module) JSCreateWithParams(typ types.Type, params string) string {
if len(params) > 0 && !collect.IsParametric(typ) {
// Forget params for non-generic types.
params = ""
}
switch t := typ.(type) {
case *types.Alias:
if m.collector.IsVoidAlias(t.Obj()) {
return "$Create.Any"
}
return m.JSCreateWithParams(types.Unalias(typ), params)
case *types.Array, *types.Pointer:
pp, ok := m.postponedCreates.At(typ).(*postponed)
if ok {
return fmt.Sprintf("$$createType%d%s", pp.index, params)
}
createElement := m.JSCreateWithParams(typ.(interface{ Elem() types.Type }).Elem(), params)
if createElement != "$Create.Any" {
pp = &postponed{m.postponedCreates.Len(), params}
m.postponedCreates.Set(typ, pp)
return fmt.Sprintf("$$createType%d%s", pp.index, params)
}
case *types.Map:
pp, ok := m.postponedCreates.At(typ).(*postponed)
if !ok {
m.JSCreateWithParams(t.Elem(), params)
pp = &postponed{m.postponedCreates.Len(), params}
m.postponedCreates.Set(typ, pp)
}
return fmt.Sprintf("$$createType%d%s", pp.index, params)
case *types.Named:
if t.Obj().Pkg() == nil {
// Builtin named type: render underlying type.
return m.JSCreateWithParams(t.Underlying(), params)
}
if m.collector.IsVoidAlias(t.Obj()) {
return "$Create.Any"
}
if !m.NeedsCreate(typ) {
break
}
pp, ok := m.postponedCreates.At(typ).(*postponed)
if !ok {
if t.TypeArgs() != nil && t.TypeArgs().Len() > 0 {
// Postpone type args.
for i := range t.TypeArgs().Len() {
m.JSCreateWithParams(t.TypeArgs().At(i), params)
}
}
pp = &postponed{m.postponedCreates.Len(), params}
m.postponedCreates.Set(typ, pp)
if !collect.IsClass(typ) {
m.JSCreateWithParams(t.Underlying(), params)
}
}
return fmt.Sprintf("$$createType%d%s", pp.index, params)
case *types.Slice:
if types.Identical(typ, typeByteSlice) {
return "$Create.ByteSlice"
}
pp, ok := m.postponedCreates.At(typ).(*postponed)
if !ok {
m.JSCreateWithParams(t.Elem(), params)
pp = &postponed{m.postponedCreates.Len(), params}
m.postponedCreates.Set(typ, pp)
}
return fmt.Sprintf("$$createType%d%s", pp.index, params)
case *types.Struct:
if t.NumFields() == 0 || collect.MaybeJSONMarshaler(typ) != collect.NonMarshaler || collect.MaybeTextMarshaler(typ) != collect.NonMarshaler {
break
}
pp, ok := m.postponedCreates.At(typ).(*postponed)
if ok {
return fmt.Sprintf("$$createType%d%s", pp.index, params)
}
info := m.collector.Struct(t)
info.Collect()
postpone := false
for _, field := range info.Fields {
if m.JSCreateWithParams(field.Type, params) != "$Create.Any" {
postpone = true
}
}
if postpone {
pp = &postponed{m.postponedCreates.Len(), params}
m.postponedCreates.Set(typ, pp)
return fmt.Sprintf("$$createType%d%s", pp.index, params)
}
case *types.TypeParam:
return fmt.Sprintf("$$createParam%s", typeparam(t.Index(), t.Obj().Name()))
}
return "$Create.Any"
}
// PostponedCreates returns the list of postponed create functions
// for the given module.
func (m *module) PostponedCreates() []string {
result := make([]string, m.postponedCreates.Len())
m.postponedCreates.Iterate(func(key types.Type, value any) {
pp := value.(*postponed)
pre, post := "", ""
if pp.params != "" {
if m.TS {
pre = createParamRegex.ReplaceAllString(pp.params, "${0}: any") + " => "
} else {
pre = "/** @type {(...args: any[]) => any} */(" + pp.params + " => "
post = ")"
}
}
switch t := key.(type) {
case *types.Array, *types.Slice:
result[pp.index] = fmt.Sprintf("%s$Create.Array(%s)%s", pre, m.JSCreateWithParams(t.(interface{ Elem() types.Type }).Elem(), pp.params), post)
case *types.Map:
result[pp.index] = fmt.Sprintf("%s$Create.Map($Create.Any, %s)%s", pre, m.JSCreateWithParams(t.Elem(), pp.params), post)
case *types.Named:
if !collect.IsClass(key) {
// Creation functions for non-struct named types
// require an indirect assignment to break cycles.
// Typescript cannot infer the return type on its own: add hints.
cast, argType, returnType := "", "", ""
if m.TS {
argType = ": any[]"
returnType = ": any"
} else {
cast = "/** @type {(...args: any[]) => any} */"
}
result[pp.index] = fmt.Sprintf(`
%s(function $$initCreateType%d(...args%s)%s {
if ($$createType%d === $$initCreateType%d) {
$$createType%d = %s%s%s;
}
return $$createType%d(...args);
})`,
cast, pp.index, argType, returnType,
pp.index, pp.index,
pp.index, pre, m.JSCreateWithParams(t.Underlying(), pp.params), post,
pp.index,
)[1:] // Remove initial newline.
// We're done.
break
}
var builder strings.Builder
builder.WriteString(pre)
if t.Obj().Pkg().Path() == m.Imports.Self {
if m.Imports.ImportModels {
builder.WriteString("$models.")
}
} else {
builder.WriteString(jsimport(m.Imports.External[t.Obj().Pkg().Path()]))
builder.WriteRune('.')
}
builder.WriteString(jsid(t.Obj().Name()))
builder.WriteString(".createFrom")
if t.TypeArgs() != nil && t.TypeArgs().Len() > 0 {
builder.WriteString("(")
for i := range t.TypeArgs().Len() {
if i > 0 {
builder.WriteString(", ")
}
builder.WriteString(m.JSCreateWithParams(t.TypeArgs().At(i), pp.params))
}
builder.WriteString(")")
}
builder.WriteString(post)
result[pp.index] = builder.String()
case *types.Pointer:
result[pp.index] = fmt.Sprintf("%s$Create.Nullable(%s)%s", pre, m.JSCreateWithParams(t.Elem(), pp.params), post)
case *types.Struct:
info := m.collector.Struct(t)
info.Collect()
var builder strings.Builder
builder.WriteString(pre)
builder.WriteString("$Create.Struct({")
for _, field := range info.Fields {
createField := m.JSCreateWithParams(field.Type, pp.params)
if createField == "$Create.Any" {
continue
}
builder.WriteString("\n \"")
template.JSEscape(&builder, []byte(field.JsonName))
builder.WriteString("\": ")
builder.WriteString(createField)
builder.WriteRune(',')
}
if len(info.Fields) > 0 {
builder.WriteRune('\n')
}
builder.WriteString("})")
builder.WriteString(post)
result[pp.index] = builder.String()
default:
result[pp.index] = pre + "$Create.Any" + post
}
})
if Newline != "\n" {
// Replace newlines according to local git config.
for i := range result {
result[i] = strings.ReplaceAll(result[i], "\n", Newline)
}
}
return result
}
type postponed struct {
index int
params string
}