-
-
Notifications
You must be signed in to change notification settings - Fork 663
feat: @melonjs/capacitor-plugin + create-melonjs --template capacitor #1439
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e6a6bd4
feat(capacitor-plugin): new @melonjs/capacitor-plugin package
obiot f807637
feat(create-melonjs): --template flag with capacitor option
obiot 79cd9cf
docs(capacitor-plugin): use new Application class in quick-start
obiot 9bfed8c
fix(capacitor-plugin): address Copilot review on PR #1439
obiot 40f2056
fix(capacitor-plugin): address Copilot review (round 2)
obiot c606be8
chore(capacitor-plugin): lower melonjs peer dep floor to 18.3.0
obiot 877917b
refactor(capacitor-plugin): source peer dep version from package.json
obiot f6f109a
refactor(capacitor-plugin): align peer-dep-version pattern with the e…
obiot e02ecc4
fix(capacitor-plugin): bindStageBack idempotent across reset cycles
obiot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| # Temp files | ||
| .DS_Store | ||
| Thumbs.db | ||
| Desktop.ini | ||
| npm-debug.log | ||
|
|
||
| # Project specific ignore | ||
| node_modules/ | ||
| package-lock.json | ||
| build/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| # Changelog | ||
|
|
||
| ## [1.0.0] - _unreleased_ | ||
|
|
||
| ### Added | ||
| - Initial release. `CapacitorPlugin` (`BasePlugin` subclass) bridges Capacitor's `appStateChange` → `state.pause` / `state.resume`, and forwards `backButton` events into the melonJS event bus as a `CapacitorBackEvent` with a `preventDefault()` API. Defaults: pause/resume on background, also pause/resume audio, exit the app when no handler intercepts the back press. | ||
| - `bindStageBack(stage, handler)` — wires a per-stage back-button handler whose lifetime matches the stage's `onResetEvent` / `onDestroyEvent`, removing the manual `event.on` / `event.off` boilerplate. | ||
| - `onBackButton(handler)` — subscribe a global, stage-agnostic back-button handler. Returns an unsubscribe function. | ||
| - `lockOrientation(o)` / `unlockOrientation()` — lazy wrappers around `@capacitor/screen-orientation` (optional peer dep, dynamically imported only when called). | ||
| - `hideSplash(opts?)` — lazy wrapper around `@capacitor/splash-screen` (optional peer dep, dynamically imported only when called). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| MIT License | ||
|
|
||
| Copyright (C) 2011 - 2026 Olivier Biot (AltByte Pte Ltd) | ||
|
|
||
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| # @melonjs/capacitor-plugin | ||
|
|
||
| A [melonJS](https://melonjs.org/) plugin that bridges [Capacitor](https://capacitorjs.com/)'s native lifecycle and hardware back-button events into the engine — so a melonJS game wrapped as an iOS or Android app pauses on background, resumes on foreground, and lets each `Stage` intercept the hardware back press without manual `event.on` / `event.off` boilerplate. | ||
|
|
||
| melonJS games already run inside Capacitor's WebView with zero engine changes — this plugin is purely an ergonomics layer over the standard `@capacitor/app` events, plus optional helpers for orientation lock and splash-screen dismissal. | ||
|
|
||
| ## Install | ||
|
|
||
| ```sh | ||
| npm install melonjs @melonjs/capacitor-plugin @capacitor/app | ||
| ``` | ||
|
|
||
| The plugin's required runtime peer is `@capacitor/app`. The orientation and splash helpers are optional and pull their respective peer deps lazily — only install them if you call those helpers: | ||
|
|
||
| ```sh | ||
| # only if you call lockOrientation / unlockOrientation | ||
| npm install @capacitor/screen-orientation | ||
|
|
||
| # only if you call hideSplash | ||
| npm install @capacitor/splash-screen | ||
| ``` | ||
|
|
||
| ## Quick start | ||
|
|
||
| ```ts | ||
| import { Application, plugin, state, Stage } from "melonjs"; | ||
| import { | ||
| CapacitorPlugin, | ||
| bindStageBack, | ||
| hideSplash, | ||
| lockOrientation, | ||
| } from "@melonjs/capacitor-plugin"; | ||
|
|
||
| await lockOrientation("landscape"); | ||
|
|
||
| // `new Application(...)` boots the engine and creates the renderer | ||
| // in a single call — replaces the legacy `boot()` + `video.init(...)` | ||
| // pair. | ||
| const app = new Application(1024, 768, { | ||
| parent: "screen", | ||
| scaleMethod: "flex", | ||
| }); | ||
|
|
||
| // One register call wires lifecycle (appStateChange → state.pause/resume) | ||
| // and forwards hardware back-button presses into the engine event bus. | ||
| plugin.register(CapacitorPlugin, "capacitor", { | ||
| pauseAudio: true, | ||
| }); | ||
|
|
||
| class PlayStage extends Stage { | ||
| onResetEvent() { | ||
| // Bind a back-button handler that lives as long as this stage. | ||
| // Calling `evt.preventDefault()` keeps the engine from running | ||
| // the default action (App.exitApp). | ||
| bindStageBack(this, (evt) => { | ||
| state.change(state.MENU); | ||
| evt.preventDefault(); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| state.set(state.PLAY, new PlayStage()); | ||
| state.change(state.PLAY); | ||
| await hideSplash({ fadeOutDuration: 300 }); | ||
| ``` | ||
|
|
||
| ## API | ||
|
|
||
| ### `CapacitorPlugin` | ||
|
|
||
| A `BasePlugin` subclass. Register it via the engine's plugin system: | ||
|
|
||
| ```ts | ||
| plugin.register(CapacitorPlugin, "capacitor", options?); | ||
| ``` | ||
|
|
||
| Once registered the instance is reachable at `plugin.cache.capacitor` (or `plugin.get(CapacitorPlugin)`). | ||
|
|
||
| Options (`ConnectCapacitorOptions`): | ||
|
|
||
| | key | default | description | | ||
| |---|---|---| | ||
| | `pauseOnBackground` | `true` | When the OS sends the app to background, call `state.pause()`; resume on foreground. | | ||
| | `pauseAudio` | `true` | Forwarded to `state.pause(music)` / `state.resume(music)`. Set `false` if you want background audio to keep playing. | | ||
| | `forwardBackButton` | `true` | Forward Capacitor's `backButton` event to the engine bus so subscribers can intercept it. | | ||
| | `onUnhandledBack` | `() => App.exitApp()` | Called when no subscriber calls `evt.preventDefault()`. Override to e.g. show a confirm dialog. | | ||
|
|
||
| The instance exposes a `teardown()` method that removes every Capacitor listener it installed. Mostly useful for hot-reload and unit tests. It is async: `await cap.teardown()` to wait for all removals to settle, or fire-and-forget for opportunistic detachment. | ||
|
|
||
| ### `bindStageBack(stage, handler)` | ||
|
|
||
| Subscribe a hardware-back handler whose lifetime matches the given `Stage`'s reset/destroy lifecycle. The handler is attached in `onResetEvent` and detached in `onDestroyEvent` automatically. | ||
|
|
||
| The handler receives a `CapacitorBackEvent`: | ||
|
|
||
| ```ts | ||
| interface CapacitorBackEvent { | ||
| readonly defaultPrevented: boolean; | ||
| preventDefault(): void; | ||
| } | ||
| ``` | ||
|
|
||
| If any handler calls `evt.preventDefault()`, the plugin's `onUnhandledBack` action is suppressed for that press. | ||
|
|
||
| ### `onBackButton(handler)` | ||
|
|
||
| Subscribe a global handler (not tied to any stage). Returns an unsubscribe function. Useful if you want a back-button policy that applies regardless of the active stage. Most code should prefer `bindStageBack` for per-screen behavior. | ||
|
|
||
| ### `lockOrientation(o)` / `unlockOrientation()` | ||
|
|
||
| Thin lazy wrappers around `@capacitor/screen-orientation`. The dependency is `import()`-ed only when these are called. | ||
|
|
||
| ### `hideSplash(opts?)` | ||
|
|
||
| Thin lazy wrapper around `@capacitor/splash-screen`'s `hide()`. Same lazy-import pattern. | ||
|
|
||
| ## Capacitor project setup | ||
|
|
||
| This plugin is a runtime adapter — it doesn't replace the standard Capacitor project setup. After scaffolding a melonJS game (e.g. via `npm create melonjs my-game`) wire Capacitor as you normally would: | ||
|
|
||
| ```sh | ||
| npm install -D @capacitor/cli | ||
| npm install @capacitor/core @capacitor/app | ||
| npx cap init my-game com.example.mygame | ||
| npx cap add ios | ||
| npx cap add android | ||
| npm run build | ||
| npx cap copy | ||
| npx cap open ios # or: npx cap open android | ||
| ``` | ||
|
|
||
| melonJS's Vite-based build outputs to `dist/`, which is Capacitor's default `webDir`. No additional config required. | ||
|
|
||
| ## License | ||
|
|
||
| MIT — see `LICENSE`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| { | ||
| "name": "@melonjs/capacitor-plugin", | ||
| "version": "1.0.0", | ||
| "description": "melonJS Capacitor plugin", | ||
| "homepage": "https://www.npmjs.com/package/@melonjs/capacitor-plugin", | ||
| "type": "module", | ||
| "keywords": [ | ||
| "2D", | ||
| "HTML5", | ||
| "javascript", | ||
| "TypeScript", | ||
| "ES6", | ||
| "Canvas", | ||
| "WebGL", | ||
| "WebGL2", | ||
| "melonjs", | ||
| "plugin", | ||
| "capacitor", | ||
| "ionic", | ||
| "mobile", | ||
| "hybrid", | ||
| "ios", | ||
| "android" | ||
| ], | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/melonjs/melonJS.git", | ||
| "directory": "packages/capacitor-plugin" | ||
| }, | ||
| "bugs": { | ||
| "url": "https://github.com/melonjs/melonJS/issues" | ||
| }, | ||
| "license": "MIT", | ||
| "author": "AltByte Pte Ltd", | ||
| "funding": "https://github.com/sponsors/melonjs", | ||
| "engines": { | ||
| "node": ">=24.0.0" | ||
| }, | ||
| "exports": { | ||
| ".": "./build/index.js" | ||
| }, | ||
| "types": "./build/index.d.ts", | ||
| "sideEffects": false, | ||
| "files": [ | ||
| "build/", | ||
| "package.json", | ||
| "README.md", | ||
| "LICENSE", | ||
| "CHANGELOG.md" | ||
| ], | ||
| "peerDependencies": { | ||
| "melonjs": ">=18.3.0", | ||
| "@capacitor/app": ">=6.0.0", | ||
| "@capacitor/screen-orientation": ">=6.0.0", | ||
| "@capacitor/splash-screen": ">=6.0.0" | ||
| }, | ||
| "peerDependenciesMeta": { | ||
| "@capacitor/screen-orientation": { | ||
| "optional": true | ||
| }, | ||
| "@capacitor/splash-screen": { | ||
| "optional": true | ||
| } | ||
|
obiot marked this conversation as resolved.
|
||
| }, | ||
| "devDependencies": { | ||
| "@capacitor/app": "^6.0.0", | ||
| "@capacitor/screen-orientation": "^6.0.0", | ||
| "@capacitor/splash-screen": "^6.0.0", | ||
| "concurrently": "^9.2.1", | ||
| "esbuild": "^0.28.0", | ||
| "melonjs": "workspace:*", | ||
| "tsconfig": "workspace:*", | ||
| "tsx": "^4.21.0", | ||
| "typescript": "^6.0.2" | ||
| }, | ||
| "scripts": { | ||
| "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", | ||
| "build": "tsx scripts/build.ts && pnpm types", | ||
| "build:watch": "tsx scripts/build.ts watch", | ||
| "prepublishOnly": "pnpm clean && pnpm build", | ||
| "clean": "tsx scripts/clean.ts", | ||
| "types": "tsc --project tsconfig.build.json", | ||
| "tsc:watch": "tsc --project tsconfig.build.json --watch --noUnusedParameters false --noUnusedLocals false --preserveWatchOutput" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import esbuild, { type BuildOptions } from "esbuild"; | ||
| import packageJson from "../package.json" with { type: "json" }; | ||
|
|
||
| const banner = [ | ||
| "/*!", | ||
| ` * ${packageJson.description} - ${packageJson.version}`, | ||
| " * http://www.melonjs.org", | ||
| ` * ${packageJson.name} is licensed under the MIT License.`, | ||
| " * http://www.opensource.org/licenses/mit-license", | ||
| ` * @copyright (C) 2011 - ${new Date().getFullYear()} ${packageJson.author}`, | ||
| " */", | ||
| ].join("\n"); | ||
|
|
||
| const buildOptions = { | ||
| entryPoints: ["src/index.ts"], | ||
| external: [ | ||
| "melonjs", | ||
| "@capacitor/app", | ||
| "@capacitor/screen-orientation", | ||
| "@capacitor/splash-screen", | ||
| ], | ||
| splitting: true, | ||
| format: "esm", | ||
| outdir: "build", | ||
| sourcemap: true, | ||
| bundle: true, | ||
| define: { __VERSION__: JSON.stringify(packageJson.version) }, | ||
| banner: { | ||
| js: banner, | ||
| }, | ||
| } satisfies BuildOptions; | ||
|
|
||
| if (process.argv[2] === "watch") { | ||
| const ctx = await esbuild.context(buildOptions); | ||
| await ctx.watch({}); | ||
| } else { | ||
| await esbuild.build(buildOptions); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { rm } from "node:fs/promises"; | ||
|
|
||
| await rm("build", { recursive: true, force: true }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import { event } from "melonjs"; | ||
| import type { CapacitorBackEvent } from "./types.ts"; | ||
|
|
||
| /** Internal event name used on the melonJS event bus. */ | ||
| export const BACK_EVENT = "@melonjs/capacitor-plugin:backButton"; | ||
|
|
||
| // `event.on` / `event.emit` / `event.off` are typed against an | ||
| // internal `keyof Events` registry that this plugin can't augment | ||
| // from outside. The cast is contained: the BACK_EVENT name is unique | ||
| // to this plugin, and the listener signature is enforced by the | ||
| // public `onBackButton` / `bindStageBack` APIs. | ||
| type BackBus = { | ||
| on(name: string, h: (evt: CapacitorBackEvent) => void): void; | ||
| off(name: string, h: (evt: CapacitorBackEvent) => void): void; | ||
| emit(name: string, evt: CapacitorBackEvent): void; | ||
| }; | ||
| const bus = event as unknown as BackBus; | ||
|
|
||
| /** | ||
| * Dispatch a fresh `CapacitorBackEvent` on the engine bus. | ||
| * @returns `true` if any handler called `preventDefault()`, `false` otherwise. | ||
| */ | ||
| export function emitBackEvent(): boolean { | ||
| const evt: CapacitorBackEvent = { | ||
| defaultPrevented: false, | ||
| preventDefault() { | ||
| (this as { defaultPrevented: boolean }).defaultPrevented = true; | ||
| }, | ||
| }; | ||
| bus.emit(BACK_EVENT, evt); | ||
| return evt.defaultPrevented; | ||
| } | ||
|
|
||
| /** | ||
| * Subscribe a global hardware-back handler. Use `bindStageBack()` | ||
| * instead if the handler should only be active while a specific | ||
| * `Stage` is reset. | ||
| * @param handler - called with a `CapacitorBackEvent` on every back press. | ||
| * @returns an unsubscribe function. | ||
| */ | ||
| export function onBackButton( | ||
| handler: (evt: CapacitorBackEvent) => void, | ||
| ): () => void { | ||
| bus.on(BACK_EVENT, handler); | ||
| return () => { | ||
| bus.off(BACK_EVENT, handler); | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * @internal | ||
| * @param handler - back-button handler to subscribe. | ||
| */ | ||
| export function subscribeBackHandler( | ||
| handler: (evt: CapacitorBackEvent) => void, | ||
| ): void { | ||
| bus.on(BACK_EVENT, handler); | ||
| } | ||
|
|
||
| /** | ||
| * @internal | ||
| * @param handler - back-button handler to unsubscribe. | ||
| */ | ||
| export function unsubscribeBackHandler( | ||
| handler: (evt: CapacitorBackEvent) => void, | ||
| ): void { | ||
| bus.off(BACK_EVENT, handler); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.