wails/v3/examples/gin-service/assets/index.html
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

249 lines
8.6 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gin Service Example</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
h1 {
color: #0078d7;
text-align: center;
}
.card {
background-color: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
button {
background-color: #0078d7;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
margin-right: 8px;
margin-bottom: 8px;
}
button:hover {
background-color: #0063b1;
}
pre {
background-color: #f0f0f0;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
}
input {
padding: 8px;
margin: 8px 0;
border: 1px solid #ddd;
border-radius: 4px;
width: 100%;
}
label {
display: block;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Gin Service Example</h1>
<div class="card">
<h2>API Endpoints</h2>
<p>Try the Gin API endpoints mounted at /api:</p>
<button id="getInfo">Get Service Info</button>
<button id="getUsers">Get All Users</button>
<button id="getUser">Get User by ID</button>
<button id="createUser">Create User</button>
<button id="deleteUser">Delete User</button>
<div id="apiResult" style="margin-top: 1rem;">
<pre id="apiResponse">Results will appear here...</pre>
</div>
</div>
<div class="card">
<h2>Event Communication</h2>
<p>Trigger an event to communicate with the Gin service:</p>
<button id="triggerEvent">Trigger Event</button>
<div id="eventResult" style="margin-top: 1rem;">
<pre id="eventResponse">Event responses will appear here...</pre>
</div>
</div>
<div class="card" id="createUserForm" style="display: none; border: 2px solid #0078d7;">
<h2>Create New User</h2>
<div>
<label for="userName">Name:</label>
<input type="text" id="userName" placeholder="Enter name">
</div>
<div>
<label for="userEmail">Email:</label>
<input type="email" id="userEmail" placeholder="Enter email">
</div>
<button id="submitUser">Submit</button>
<button id="cancelCreate">Cancel</button>
</div>
<script type="module">
// Import the Wails runtime
import * as wails from "/wails/runtime.js";
// Helper function to fetch API endpoints
async function fetchAPI(endpoint, options = {}) {
try {
const response = await fetch(`/api${endpoint}`, options);
const data = await response.json();
document.getElementById('apiResponse').textContent = JSON.stringify(data, null, 2);
return data;
} catch (error) {
document.getElementById('apiResponse').textContent = `Error: ${error.message}`;
console.error('API Error:', error);
}
}
// Event listeners for API buttons
document.getElementById('getInfo').addEventListener('click', () => {
fetchAPI('/info');
});
document.getElementById('getUsers').addEventListener('click', () => {
fetchAPI('/users');
});
document.getElementById('getUser').addEventListener('click', async () => {
const userId = prompt('Enter user ID:');
if (userId) {
await fetchAPI(`/users/${userId}`);
}
});
document.getElementById('createUser').addEventListener('click', () => {
const form = document.getElementById('createUserForm');
form.style.display = 'block';
form.scrollIntoView({ behavior: 'smooth' });
});
document.getElementById('cancelCreate').addEventListener('click', () => {
document.getElementById('createUserForm').style.display = 'none';
});
document.getElementById('submitUser').addEventListener('click', async () => {
const name = document.getElementById('userName').value;
const email = document.getElementById('userEmail').value;
if (!name || !email) {
alert('Please enter both name and email');
return;
}
try {
await fetchAPI('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, email })
});
document.getElementById('createUserForm').style.display = 'none';
document.getElementById('userName').value = '';
document.getElementById('userEmail').value = '';
// Automatically fetch the updated user list
await fetchAPI('/users');
// Show a success message
const apiResponse = document.getElementById('apiResponse');
const currentData = JSON.parse(apiResponse.textContent);
apiResponse.textContent = JSON.stringify({
message: "User created successfully!",
users: currentData
}, null, 2);
} catch (error) {
console.error('Error creating user:', error);
}
});
document.getElementById('deleteUser').addEventListener('click', async () => {
const userId = prompt('Enter user ID to delete:');
if (userId) {
try {
await fetchAPI(`/users/${userId}`, {
method: 'DELETE'
});
// Show success message
document.getElementById('apiResponse').textContent = JSON.stringify({
message: `User with ID ${userId} deleted successfully`
}, null, 2);
// Refresh the user list
setTimeout(() => fetchAPI('/users'), 1000);
} catch (error) {
console.error('Error deleting user:', error);
}
}
});
// Using Wails Events API for event communication
document.getElementById('triggerEvent').addEventListener('click', async () => {
// Display the event being sent
document.getElementById('eventResponse').textContent = JSON.stringify({
status: "Sending event to backend...",
data: { timestamp: new Date().toISOString() }
}, null, 2);
// Use the Wails runtime to emit an event - matching the format in the events demo
const eventData = {
message: "Hello from the frontend!",
timestamp: new Date().toISOString()
};
wails.Events.Emit('gin-api-event', eventData);
});
// Set up event listener for responses from the backend
window.addEventListener('DOMContentLoaded', () => {
// Register event listener using Wails runtime
wails.Events.On("gin-api-response", (data) => {
document.getElementById('eventResponse').textContent = JSON.stringify(data, null, 2);
});
// Also listen for user-created events
wails.Events.On("user-created", (data) => {
document.getElementById('eventResponse').textContent = JSON.stringify({
event: "user-created",
user: data
}, null, 2);
});
// Initial API call to get service info
fetchAPI('/info');
});
</script>
</body>
</html>