Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(ui): a text field can accept only digits

yhha28bfd2e364c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bbf7561ef..5cf0dcff8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **A text field can accept only digits.** `TextInput.inputFilter` (`TextInputFilter.Digits`) keeps a field to 0-9 for a count or a price: a letter typed or pasted never reaches `value`, and the caret stays where the kept characters put it. A script that cleaned the value itself each frame lost to the field: while a field is being edited its own editor is the source of `value`, so the cleaned value was overwritten with what was typed and the screen kept showing the letters. The filter runs where the editor's text is read in, beside `maxLength`, so what is on screen and what a script reads are the same. Off by default; a `maxLength` still applies after it.
- **A web build can say which servers its game connects to.** The exported page's Content-Security-Policy let a game talk only to the page it came from, so a game with a server of its own could not reach it: the browser refused the connection and said nothing the game could see. A project now lists the origins in `packaging.platforms.web.connect` (`wss://play.example.com`, `ws://127.0.0.1:*` for any port on a host, or a bare `wss:` for any secure WebSocket) and each becomes a `connect-src` source. An entry is checked rather than pasted in: a path, a wildcard host, a space, a semicolon or a quote fails the export and names the entry, so no entry can end the directive and start another. Web only; a mini-game's server addresses are the platform's own list.
- **A session can be told to redial now, and says why its link ended.** `ClientSession.retryNow()` dials at once instead of waiting out the backoff, for a player who pressed "try again"; it does nothing when the session is ready, already dialling, or closed. `lastClose` is the WebSocket close code of the last link that ended (4003, `SessionCloseCode.unavailable`, is the server saying it is full or going away) until the next one is ready, and `attempts` counts dials since the session was last ready, so a screen can tell "reconnecting" from "the server is full" and say which attempt this is.
- **A session layer for online games that do not share a tick.** `esengine/session` is the request and reply side of a game played asynchronously over a shared world. A `SessionHost` on the server authenticates each connection before it serves anything, limits frame size and message rate, pings the client, and lets a newer connection for the same player replace the older one. A `ClientSession` on the device dials, redials with backoff and jitter when the link drops, waits for the server before a request goes out, and keeps its event subscriptions across reconnects. Every request carries a key, so one that was lost on the way back and is sent again is answered from memory instead of running twice (a purchase, a departure); `serverNow()` gives the server's clock, corrected for the link's delay. `defineContract` writes every request and event once, with `s.object`, `s.int` and the other validators: the server checks each request against it, the client checks each reply, and both are typed from it; its `fingerprint` lets a server turn away a client built against another contract. `acceptWebSocket` hands a `ws` socket to a host, and `IdempotencyStore` is where a server with several processes keeps the answers in one place. `NetChannel` gained the keyed requests, a heartbeat, a rate limit, a frame size limit and `NetRequestError` (`timeout`, `closed`, `rate-limited`, `retry`, `remote`) for them. Replication is untouched.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 0ef84b80a..cc41ec737 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1897 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1898 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5622,6 +5622,8 @@ depthWrite: boolean
dirty_: boolean
overrides: Set<string>
parent: number | undefined
+pushed_: boolean | undefined
+sent_: Map<string, number[]> | undefined
shader: number
switches: Record<string, boolean>
uniforms: Map<string, UniformValue>
@@ -10528,6 +10530,7 @@ focused: boolean
font: number
fontFamily: string
fontSize: number
+inputFilter: TextInputFilter
maxLength: number
multiline: boolean
padding: number
@@ -10541,6 +10544,11 @@ textAlign: TextAlign
value: string
```
+## TextInputFilter — type @experimental
+```
+typeof TextInputFilter[keyof typeof TextInputFilter]
+```
+
## TextInputHandle — interface @experimental
```
dispose: () => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index e324cf6b1..ee43842f1 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 1916 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1917 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5630,6 +5630,8 @@ depthWrite: boolean
dirty_: boolean
overrides: Set<string>
parent: number | undefined
+pushed_: boolean | undefined
+sent_: Map<string, number[]> | undefined
shader: number
switches: Record<string, boolean>
uniforms: Map<string, UniformValue>
@@ -10741,6 +10743,7 @@ focused: boolean
font: number
fontFamily: string
fontSize: number
+inputFilter: TextInputFilter
maxLength: number
multiline: boolean
padding: number
@@ -10754,6 +10757,11 @@ textAlign: TextAlign
value: string
```
+## TextInputFilter — type @experimental
+```
+typeof TextInputFilter[keyof typeof TextInputFilter]
+```
+
## TextInputHandle — interface @experimental
```
dispose: () => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 0801e1905..4996120af 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 161 beta · 1896 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1897 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5617,6 +5617,8 @@ depthWrite: boolean
dirty_: boolean
overrides: Set<string>
parent: number | undefined
+pushed_: boolean | undefined
+sent_: Map<string, number[]> | undefined
shader: number
switches: Record<string, boolean>
uniforms: Map<string, UniformValue>
@@ -10523,6 +10525,7 @@ focused: boolean
font: number
fontFamily: string
fontSize: number
+inputFilter: TextInputFilter
maxLength: number
multiline: boolean
padding: number
@@ -10536,6 +10539,11 @@ textAlign: TextAlign
value: string
```
+## TextInputFilter — type @experimental
+```
+typeof TextInputFilter[keyof typeof TextInputFilter]
+```
+
## TextInputHandle — interface @experimental
```
dispose: () => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 89b5f6bb6..dc0e605c3 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1918 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1919 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5617,6 +5617,8 @@ depthWrite: boolean
dirty_: boolean
overrides: Set<string>
parent: number | undefined
+pushed_: boolean | undefined
+sent_: Map<string, number[]> | undefined
shader: number
switches: Record<string, boolean>
uniforms: Map<string, UniformValue>
@@ -10816,6 +10818,7 @@ focused: boolean
font: number
fontFamily: string
fontSize: number
+inputFilter: TextInputFilter
maxLength: number
multiline: boolean
padding: number
@@ -10829,6 +10832,11 @@ textAlign: TextAlign
value: string
```
+## TextInputFilter — type @experimental
+```
+typeof TextInputFilter[keyof typeof TextInputFilter]
+```
+
## TextInputHandle — interface @experimental
```
dispose: () => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 1749bdcd6..28279e3d9 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1909 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1910 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5624,6 +5624,8 @@ depthWrite: boolean
dirty_: boolean
overrides: Set<string>
parent: number | undefined
+pushed_: boolean | undefined
+sent_: Map<string, number[]> | undefined
shader: number
switches: Record<string, boolean>
uniforms: Map<string, UniformValue>
@@ -10530,6 +10532,7 @@ focused: boolean
font: number
fontFamily: string
fontSize: number
+inputFilter: TextInputFilter
maxLength: number
multiline: boolean
padding: number
@@ -10543,6 +10546,11 @@ textAlign: TextAlign
value: string
```
+## TextInputFilter — type @experimental
+```
+typeof TextInputFilter[keyof typeof TextInputFilter]
+```
+
## TextInputHandle — interface @experimental
```
dispose: () => void
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 7b5de1b4d..3f0fca600 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -72,6 +72,7 @@ export {
uiPickAllWorld,
type PickableWorld,
TextInput,
+ TextInputFilter,
FillMethod,
FillOrigin,
Draggable,
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index a91403051..2708d3a18 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -396,6 +396,8 @@ export { UIInteractionPlugin, uiInteractionPlugin } from './input/interaction';
export {
TextInput,
type TextInputData,
+ TextInputFilter,
+ applyTextInputFilter,
} from './text/text-input';
export { TextInputPlugin, textInputPlugin } from './text/text-input-plugin';
diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.ts
index ae0033d19..115bfbb5f 100644
--- a/sdk/src/ui/text/text-input-plugin.ts
+++ b/sdk/src/ui/text/text-input-plugin.ts
@@ -4,7 +4,7 @@ import type { App, Plugin } from '../../app/app';
import type { Entity } from '../../types';
import { defineSystem, Schedule } from '../../ecs/system';
import { registerComponent } from '../../ecs/component';
-import { TextInput, type TextInputData } from './text-input';
+import { TextInput, applyTextInputFilter, type TextInputData } from './text-input';
import { UINode, UIPositionType, type UINodeData } from '../core/ui-node';
import { UIVisual, UIVisualType } from '../core/ui-visual';
import type { UIVisualData } from '../core/ui-visual';
@@ -210,7 +210,16 @@ export class TextInputPlugin implements Plugin {
if (ti.readOnly) return;
const state = editor!.read();
- let val = state.value;
+ let val = applyTextInputFilter(state.value, ti.inputFilter);
+ if (val !== state.value) {
+ // The caret stays after the same kept characters, where the removed ones were before it.
+ const caret = applyTextInputFilter(state.value.slice(0, state.selectionStart), ti.inputFilter).length;
+ const rest = { value: val, selectionStart: caret, selectionEnd: caret, backward: false };
+ editor!.write(rest);
+ state.value = val;
+ state.selectionStart = caret;
+ state.selectionEnd = caret;
+ }
if (ti.maxLength > 0 && val.length > ti.maxLength) {
val = val.substring(0, ti.maxLength);
// maxLength counts UTF-16 units, but a cut between a surrogate
diff --git a/sdk/src/ui/text/text-input.ts b/sdk/src/ui/text/text-input.ts
index 7bcac7950..63834c657 100644
--- a/sdk/src/ui/text/text-input.ts
+++ b/sdk/src/ui/text/text-input.ts
@@ -4,6 +4,23 @@ import { defineComponent, enumOptions } from '../../ecs/component';
import type { Color } from '../../types';
import { TextAlign, TextRenderMode } from '../core/text';
+/**
+ * Which characters a field accepts as they are typed or pasted. The rest never reach `value`: they are
+ * removed from the field itself, so what is on screen and what a script reads are the same.
+ */
+export const TextInputFilter = {
+ /** Anything. */
+ None: 0,
+ /** Only 0-9, for a count or a price. */
+ Digits: 1,
+} as const;
+export type TextInputFilter = typeof TextInputFilter[keyof typeof TextInputFilter];
+
+/** `value` with the characters the filter does not allow taken out. */
+export function applyTextInputFilter(value: string, filter: TextInputFilter | undefined): string {
+ return filter === TextInputFilter.Digits ? value.replace(/[^0-9]/g, '') : value;
+}
+
export interface TextInputData {
value: string;
placeholder: string;
@@ -20,6 +37,8 @@ export interface TextInputData {
backgroundColor: Color;
padding: number;
maxLength: number;
+ /** Characters the field accepts; see {@link TextInputFilter}. */
+ inputFilter: TextInputFilter;
multiline: boolean;
password: boolean;
readOnly: boolean;
@@ -46,6 +65,7 @@ export const TextInput = defineComponent<TextInputData>('TextInput', {
backgroundColor: { r: 0.15, g: 0.15, b: 0.15, a: 1 },
padding: 6,
maxLength: 0,
+ inputFilter: TextInputFilter.None,
multiline: false,
password: false,
readOnly: false,
@@ -59,6 +79,10 @@ export const TextInput = defineComponent<TextInputData>('TextInput', {
placeholderI18nKey: { label: 'Placeholder I18n Key', enumSource: 'localeKeys', tooltip: 'Translate the empty-field hint through the Localization resource. Leave empty for a literal placeholder.' },
font: { label: 'Font', tooltip: 'A font file this project ships (.ttf / .otf). Overrides Font Family when set; leave empty to use a font the host already has.' },
fontFamily: { tooltip: 'A font the HOST already has (system or page-loaded). Ignored when Font is set.' },
+ inputFilter: {
+ enum: enumOptions(TextInputFilter),
+ tooltip: 'Which characters the field accepts. Digits keeps only 0-9, whether typed or pasted, for a count or a price.',
+ },
textAlign: {
enum: enumOptions(TextAlign),
tooltip: 'Where the value sits in the field. A single line holds the alignment while it fits, then scrolls to follow the caret.',
diff --git a/sdk/tests/text-input-plugin-lifecycle.test.ts b/sdk/tests/text-input-plugin-lifecycle.test.ts
index 8ad986c9c..abd4bf025 100644
--- a/sdk/tests/text-input-plugin-lifecycle.test.ts
+++ b/sdk/tests/text-input-plugin-lifecycle.test.ts
@@ -301,3 +301,44 @@ it.each([
expect(app.world.get(field, TextInput).cursorPos).toBe(expected.length);
expect(surfaces[0].write).toHaveBeenCalledWith({ value: expected, selectionStart: expected.length, selectionEnd: expected.length, backward: false });
});
+
+it.each([
+ { typed: 'x5y', caret: 3, filter: 1, expected: '5', expectedCaret: 1 },
+ { typed: '12ab34', caret: 4, filter: 1, expected: '1234', expectedCaret: 2 },
+ { typed: '٣45', caret: 3, filter: 1, expected: '5', expectedCaret: 1 },
+ { typed: '', caret: 0, filter: 1, expected: '', expectedCaret: 0 },
+])('a digits field removes what it does not accept and keeps the caret in place: $typed', async ({ typed, caret, filter, expected, expectedCaret }) => {
+ const app = build(new TextInputPlugin());
+ const field = app.world.spawn();
+ app.world.insert(field, TextInput, { value: '', inputFilter: filter });
+ app.getResource(FocusManager).focus(field);
+ await app.tick(1 / 60);
+ vi.spyOn(surfaces[0], 'read').mockReturnValue({ value: typed, selectionStart: caret, selectionEnd: caret, backward: false });
+ for (const listener of surfaces[0].listeners) listener({ kind: 'change' });
+ expect(app.world.get(field, TextInput).value).toBe(expected);
+ expect(app.world.get(field, TextInput).cursorPos).toBe(expectedCaret);
+ if (typed !== expected) {
+ expect(surfaces[0].write).toHaveBeenCalledWith({ value: expected, selectionStart: expectedCaret, selectionEnd: expectedCaret, backward: false });
+ }
+});
+
+it('a field with no filter takes every character, and a digits field still honours its length limit', async () => {
+ const app = build(new TextInputPlugin());
+ const open = app.world.spawn();
+ app.world.insert(open, TextInput, { value: '' });
+ app.getResource(FocusManager).focus(open);
+ await app.tick(1 / 60);
+ vi.spyOn(surfaces[0], 'read').mockReturnValue({ value: 'x5y', selectionStart: 3, selectionEnd: 3, backward: false });
+ for (const listener of surfaces[0].listeners) listener({ kind: 'change' });
+ expect(app.world.get(open, TextInput).value).toBe('x5y');
+ expect(surfaces[0].write).not.toHaveBeenCalled();
+
+ const priced = app.world.spawn();
+ app.world.insert(priced, TextInput, { value: '', inputFilter: 1, maxLength: 3 });
+ app.getResource(FocusManager).focus(priced);
+ await app.tick(1 / 60);
+ const second = surfaces.at(-1)!;
+ vi.spyOn(second, 'read').mockReturnValue({ value: '1a2b3c4d5', selectionStart: 9, selectionEnd: 9, backward: false });
+ for (const listener of second.listeners) listener({ kind: 'change' });
+ expect(app.world.get(priced, TextInput).value).toBe('123');
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 2247302d3..1705f8adf 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3020,6 +3020,8 @@ export const NOTED = {
{"note":"A session can be told to redial now, and says why its link ended."},
'feat(export): a web build lists the origins its game connects to':
{"note":"A web build can say which servers its game connects to."},
+ 'feat(ui): a text field can accept only digits':
+ {"note":"A text field can accept only digits."},
"perf(sdk): a blank mini-game package no longer carries terrain and water":
{"note":"A blank mini-game package no longer carries terrain and water."},
"perf(ecs): one stable sort for every component type, 239KB off the engine wasm":