# ui/uiinputfield (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/ui/uiinputfield/

Input field (canvas based).

## UIInputField extends WorldNode

Input field (canvas based).
- Text rendering uses two UILabel child nodes (value label + placeholder label).
- Click/drag/cursor movement/selection are all handled directly on the canvas side.
- Using a DOM <input> is optional (setUseDOMInput, default false). Korean IME /
  mobile soft keyboard / system clipboard work only when true. When false, the keyboard is handled directly, mostly ASCII.
- Context menu on right click (cut / copy / paste / select all). Direct-touch fields (setUseDirectTouch) also get this menu instead of the browser edit-field menu.
- Cursor movement and Delete work per grapheme cluster like Chrome, Backspace removes one code point like Blink's BackspaceStateMachine (emoji sequences as a whole).
- With DOM input, a mouse double click selects a word (with trailing whitespace on Windows) and a triple click selects all text, like a Chrome text field. (The click count is the mousedown detail)
- In canvas mode, word movement and deletion use Ctrl on Windows and Linux and Option on Mac with the left and right arrows, Backspace and Delete, like Chrome. (Blink NextWordPosition, PreviousWordPosition)
- Undo and redo are handled by an engine history in both modes. (The same Blink grouping rules as TextEditBuffer in the Rust edition: consecutively typed characters undo at once, moving the cursor or changing the selection breaks the group,
  a new edit clears the redo list, setText clears the lists) Keys are Ctrl (Cmd on Mac) + Z, Ctrl (Cmd on Mac) + Shift + Z, Ctrl + Y on Windows and Linux, and also Alt + Backspace on Windows.
  DOM input blocks the browser's undo keys and historyUndo, historyRedo and uses the engine history. It does not undo during IME composition.
- With setMultiline(true) it is a multiline input like a Chrome textarea. (DOM input uses a hidden textarea) Text is split by line break characters and width
  like white-space: pre-wrap, overflow-wrap: break-word. Line break opportunities are read from Chrome's own line breaking. (the same computation as ui/textarealayout.rs in the Rust edition)
  Enter inserts a line, up, down and page keys move by the engine layout, Home and End go to the start and end of the visible line, and Ctrl (Cmd on Mac) + Home, End go to the start and end of the text. When it overflows it scrolls to keep the caret visible.

Example: Make a name input field

```js
import { Engine, EngineConfiguration, UIScene, UIInputField, Vector2 } from "./build/vanilla.js";

class MainScene extends UIScene {
	constructor() {
		super();
		this.setLoadingMinDurationMs(0);
	}

	initialize(engine) {
		super.initialize(engine);
		const inputField = new UIInputField();
		inputField.setEngine(engine);
		inputField.setLocalPosition(Vector2.create(40, 40));
		inputField.setContentSize(Vector2.create(320, 56));
		inputField.setPlaceholder("Your name");
		inputField.setMaxLength(16);
		inputField.setOnChange((value) => {
			console.log("change", value);
		});
		inputField.setOnSubmit((value) => {
			console.log("submit", value);
		});
		const root = this.getRoot();
		root.addChild(inputField);
		inputField.attach();
		inputField.setText("Player");
		console.log(inputField.getText(), inputField.getCursorIndex());
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.canvasId = "mainCanvas";
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
engineConfiguration.autoResizeOnWindowResize = true;
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.2.1): Constructor.
- `setEngine(engine)` (method, since 0.2.1): Settings.
  - `engine` Engine: Engine. (used for the DOM input position, canvas events and the context menu; Engine.getEngine() is used when not given)
- `setUseDOMInput(use)` (method, since 0.2.1): Sets whether to use the DOM input. (read at attach, so set it before)
  - `use` boolean: If true, takes text through a hidden DOM input. (enables Korean IME, mobile on-screen keyboards and the system clipboard, default false)

  Example: An input field that takes the mobile keyboard and IME

  ```js
  import { Engine, EngineConfiguration, UIScene, UIInputField, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const inputField = new UIInputField();
  		inputField.setEngine(engine);
  		inputField.setUseDOMInput(true);
  		inputField.setUseTouchEndFocus(true);
  		inputField.setLocalPosition(Vector2.create(40, 40));
  		inputField.setContentSize(Vector2.create(320, 56));
  		inputField.setPlaceholder("Message");
  		const root = this.getRoot();
  		root.addChild(inputField);
  		inputField.attach();
  		console.log(inputField.isUsingDOMInput(), inputField.isFocused());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `isUsingDOMInput()` (method, since 0.2.1): Returns whether the DOM input is used.
  - returns boolean: True if the DOM input is used.
- `setUseTouchEndFocus(use)` (method, since 0.3.2): Whether to also give focus on release (touchend) for DOM input. (default false, when off it is given only on touchstart)
  When on, focus obtained while there was no user activation yet (the page's first touchstart) is given again on release,
  so the keyboard appears even in browsers that do not show the keyboard for such focus (Android Chrome, webviews).
  - `use` boolean: If true, also gives focus on touchend. (default false)
- `isUsingTouchEndFocus()` (method, since 0.3.2): Returns whether touchend focus is used.
  - returns boolean: True if focus is also given on touchend.
- `setUseDirectTouch(use)` (method, since 0.3.2): Whether to let the finger (mouse) press the DOM input directly over the field. (default false, when off the DOM input does not receive presses and the canvas gives focus)
  When on, while the field is visible a transparent DOM input receives presses at the field's position and, through the browser's default behavior, opens focus (including that frame for a cross-origin iframe) and
  the keyboard. Used in webviews that do not accept focus given by code (iframes inside apps, etc). On focus, the cursor is placed at the end of the text.
  Right-clicking that DOM input opens the same engine context menu as other fields instead of the browser edit-field menu. (the same items as the Rust desktop)
  - `use` boolean: If true, a transparent DOM input takes presses directly over the field. (default false)
- `isUsingDirectTouch()` (method, since 0.3.2): Returns whether direct touch is used.
  - returns boolean: True if the DOM input takes presses directly.
- `setMultiline(isMultiline)` (method, since 0.4.0): Sets multiline. (Like a Chrome textarea, DOM input uses a hidden textarea, changing it resets the scroll to the top)
  - When multiline, Enter inserts a line (the submit callback is not called), text wraps to the width, the caret moves up and down, and it scrolls when it overflows.
  - It is not an original field property written to UI documents. (the Rust edition also leaves it out of reflection)
  - `isMultiline` boolean: True for multiline, false for single line. (false at first)

  Example: Multiline memo field

  ```js
  import { Engine, EngineConfiguration, UIScene, UIInputField, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const inputField = new UIInputField();
  		inputField.setEngine(engine);
  		inputField.setMultiline(true);
  		inputField.setTabSize(4);
  		inputField.setLineHeight(32);
  		inputField.setLocalPosition(Vector2.create(40, 40));
  		inputField.setContentSize(Vector2.create(320, 160));
  		inputField.setPlaceholder("Memo");
  		const root = this.getRoot();
  		root.addChild(inputField);
  		inputField.attach();
  		inputField.setText("first line\nsecond line");
  		console.log(inputField.isMultiline(), inputField.getLineHeight(), inputField.getTabSize());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `isMultiline()` (method, since 0.4.0): Whether it is multiline.
  - returns boolean: True if multiline.
- `setLineHeight(lineHeight)` (method, since 0.4.0): Sets the line height. (Multiline field, null is CSS normal. Like Chrome it is computed from the ascent, descent and line gap of the primary font)
  - `lineHeight` number | null: Line height. (content size units, null for CSS normal)
- `getLineHeight()` (method, since 0.4.0): Returns the line height. (multiline field)
  - returns number: Line height. (the measured CSS normal value if not set, or the font size times 1.2 rounded when there is no document to measure with)
- `setTabSize(tabSize)` (method, since 0.4.0): Sets the tab size. (multiline field, width in spaces, CSS tab-size)
  - `tabSize` number: Tab size. (width in spaces, negative becomes 0, default 8)
- `getTabSize()` (method, since 0.4.0): Returns the tab size.
  - returns number: Tab size. (width in spaces)
- `getScrollTop()` (method, since 0.4.0): Returns the amount scrolled up. (multiline field, textarea scrollTop)
  - returns number: Amount scrolled up. (content size units)
- `setScrollTop(scrollTop)` (method, since 0.4.0): Scrolls up. (Multiline field, clamped within the end of the text on the next draw)
  - `scrollTop` number: Amount to scroll up. (content size units, negative becomes 0)
- `canUndo()` (method, since 0.4.0): Whether there is anything to undo.
  - returns boolean: True if there is a group to undo.

  Example: Undo consecutively typed characters at once

  ```js
  import { Engine, EngineConfiguration, UIScene, UIInputField, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const inputField = new UIInputField();
  		inputField.setEngine(engine);
  		inputField.setLocalPosition(Vector2.create(40, 40));
  		inputField.setContentSize(Vector2.create(320, 56));
  		const root = this.getRoot();
  		root.addChild(inputField);
  		inputField.attach();
  		inputField.replaceSelection("a");
  		inputField.replaceSelection("b");
  		console.log(inputField.getText(), inputField.canUndo(), inputField.canRedo());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `canRedo()` (method, since 0.4.0): Whether there is anything to redo.
  - returns boolean: True if there is a group to redo.
- `setText(text)` (method, since 0.2.1): Sets the value. (Cuts it to the maximum length without splitting a surrogate pair and puts the cursor at the end, does not call the change callback, clears the undo and redo lists and the composition text)
  - `text` string: Text to set. (empty for a falsy value, otherwise converted with String)
- `getText()` (method, since 0.2.1): Returns the value.
  - returns string: The entered text. (text being composed is not included)
- `setPlaceholder(text)` (method, since 0.2.1): Sets the placeholder.
  - `text` string: Text shown when the value is empty. (empty for a falsy value)
- `setMaxLength(n)` (method, since 0.2.1): Sets the maximum length.
  - `n` number: Maximum character count. (counted by the string length, the fraction is dropped, no limit if 0 or less, the current value is not cut)
- `setFontSize(size)` (method, since 0.2.1): Sets the font size.
  - `size` number: Font size. (content size units, default 28)
- `setFont(font)` (method, since 0.2.1): Sets the font.
  - `font` FontFace | FontAsset | null: Font. (A FontAsset uses its fontFace, null or undefined means the system font, other types are ignored)
- `setPadding(padding)` (method, since 0.2.1): Sets the inner padding.
  - `padding` number: Left and right inner padding. (content size units, default 16)
- `setBackgroundColor(color)` (method, since 0.2.1): Sets the background color.
  - `color` Color | string: Background color. (default white)
- `setRoundSize(roundSize)` (method, since 0.2.1): Sets the corner roundness.
  - `roundSize` number: Corner radius of the background and the focus border. (default 8)
- `setTextColor(color)` (method, since 0.2.1): Sets the text color.
  - `color` Color | string: Color of the value text. (default #222222)
- `setPlaceholderColor(color)` (method, since 0.2.1): Sets the placeholder color.
  - `color` Color | string: Color of the placeholder text. (default #999999)
- `setCursorColor(color)` (method, since 0.2.1): Sets the cursor color. (also changes the composition underline color)
  - `color` Color | string: Color of the cursor and the composition underline. (default #5b8def)
- `setFocusBorderColor(color)` (method, since 0.2.1): Sets the focus border color.
  - `color` Color | string: Focus border color. (default #f97316)
- `setFocusBorderWidth(width)` (method, since 0.2.1): Sets the focus border width.
  - `width` number: Focus border width. (not drawn if 0 or less, default 3)
- `setSelectionColor(color)` (method, since 0.2.1): Sets the selection color.
  - `color` Color | string: Color to fill the selection with. (default blue with alpha 0.35)
- `getPlaceholder()` (method, since 0.4.0): Returns the placeholder.
  - returns string: Placeholder text.
- `getMaxLength()` (method, since 0.4.0): Returns the maximum length.
  - returns number: Maximum character count. (0 means no limit)
- `getFontSize()` (method, since 0.4.0): Returns the font size.
  - returns number: Font size.
- `getPadding()` (method, since 0.4.0): Returns the inner padding.
  - returns number: Left and right inner padding.
- `getBackgroundColor()` (method, since 0.4.0): Returns the background color.
  - returns Color: Background color.
- `getRoundSize()` (method, since 0.4.0): Returns the corner roundness.
  - returns number: Corner radius of the background.
- `getTextColor()` (method, since 0.4.0): Returns the text color.
  - returns Color: Color of the value text.
- `getPlaceholderColor()` (method, since 0.4.0): Returns the placeholder color.
  - returns Color: Color of the placeholder text.
- `getCursorColor()` (method, since 0.4.0): Returns the cursor color.
  - returns Color: Cursor color.
- `getCursorIndex()` (method, since 0.4.0): Returns the cursor position.
  - returns number: Cursor position. (character position in the value, 0 ~ value length)
- `getSelectionStart()` (method, since 0.4.0): Returns the selection start position.
  - returns number: The fixed end of the selection. (no selection if equal to the cursor position)
- `getComposition()` (method, since 0.4.0): Returns the text being composed.
  - returns string: Text being composed by the IME. (empty if none)
- `getDisplayText()` (method, since 0.4.0): Returns the visible text. (The value with the composition text inserted at the cursor position, or replacing the selected text when composing with a selection)
  - returns string: The displayed text. (the value itself when not composing)
- `isComposing()` (method, since 0.4.0): Whether IME composition is in progress.
  - returns boolean: True while composing.
- `setOnChange(callback)` (method, since 0.2.1): Sets the change callback.
  - `callback` (value: string) => void: Function called whenever user input changes the value. (the argument is the new value, not called when changed with setText, not called if null)
- `setOnSubmit(callback)` (method, since 0.2.1): Sets the submit callback.
  - `callback` (value: string) => void: Function called when Enter is pressed while focused. (the argument is the current value, not called if null)
- `attach()` (method, since 0.2.1): Input lifecycle: activation (attach) / deactivation (detach).
- `detach()` (method, since 0.2.1): Turns input off. (removes the DOM input, keyboard and context menu events and closes the menu)
- `focus()` (method, since 0.2.1): External API.
- `blur()` (method, since 0.2.1): Releases focus.
- `isFocused()` (method, since 0.2.1): Returns whether it has focus.
  - returns boolean: True if it has focus.
- `selectAll()` (method, since 0.2.1): Selects all.
- `tick(timeDelta)` (method, since 0.2.1): Every frame: label position / text sync, DOM position sync, cursor blink, selection polling.
  - `timeDelta` number: Time since the last frame. (Seconds)
- `touchPress(viewInputPosition)` (method, since 0.2.1): Canvas side touch (position based cursor / drag selection). Since the DOM input with pointer-events: none
  does not intercept clicks, input always comes here.
  - `viewInputPosition` Vector2: Press position. (view coordinates)
- `touchMove(viewInputPosition)` (method, since 0.2.1): Touch move. (selects from the press position to the current position)
  - `viewInputPosition` Vector2: Moved position. (view coordinates)
- `touchRelease()` (method, since 0.2.1): Touch release. (ends drag selection)
- `touchCancel()` (method, since 0.2.1): Touch cancel. (ends drag selection)
- `measureIndexAtLocalX(localX)` (method, since 0.2.1): localX (node local X) → character index. Measured with an offscreen 2D ctx.
    (The main canvas is a WebGL2 context, so 2D measurement is not possible)
  - `localX` number: X inside the node. (0 at the left of the content area)
  - returns number: The grapheme cluster boundary nearest to that point. (UTF-16 units, 0 to the value length, the value length if there is no context to measure with)
- `handleCanvasKeydown(event)` (method, since 0.2.1): Handles canvas mode key input. (only while focused, Ctrl or Cmd with A, C, X, V, deletion, arrows, Home, End, Enter, a single character)
  - `event` KeyboardEvent: The document's keydown event.
- `moveCursor(newIndex, extendSelection)` (method, since 0.2.1): Moves the cursor.
  - `newIndex` number: Index to move to. (UTF-16 units, clamped to 0 to the value length, an index inside a surrogate pair is taken as after that character)
  - `extendSelection` boolean: If true, keeps the fixed end of the selection and extends the selection.
- `hasSelection()` (method, since 0.2.1): Selection / clipboard.
  - returns boolean: True if text is selected.
- `getSelectionRange()` (method, since 0.2.1): Returns the selection range.
  - returns { start: number, end: number } | null: Selection range. (start is the smaller side, null if there is no selection)
- `getSelectionText()` (method, since 0.2.1): Returns the selected text.
  - returns string: The selected text. (empty if none)
- `replaceSelection(text)` (method, since 0.2.1): Replaces the selection with text. (Inserts at the cursor if there is no selection, calls the change callback)
  - With a maximum length, inserts only as much of the text as the remaining length allows, like a Blink text field. (Surrogate pairs are not split)
  - `text` string: Text to insert. (an empty string deletes the selection, it is an insert text undo group)
- `cut()` (method, since 0.2.1): Cut. (writes the selected text to the clipboard and deletes it, does nothing if there is no selection)
- `copy()` (method, since 0.2.1): Copy. (writes the selected text to the clipboard, does nothing if there is no selection)
- `paste()` (method, since 0.2.1): Paste. (reads the clipboard text asynchronously and inserts it at the selection, ignored if it cannot be read or is empty)
- `requestMenuAction(menuAction)` (method, since 0.4.0): Requests a context menu item. (Done on the next tick, UIInputFieldMenuAction)
  - `menuAction` string: Item to perform. (a UIInputFieldMenuAction value)

  Example: Request a copy from the game's own menu

  ```js
  import { Engine, EngineConfiguration, UIScene, UIInputField, UIInputFieldMenuAction, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const inputField = new UIInputField();
  		inputField.setEngine(engine);
  		inputField.setLocalPosition(Vector2.create(40, 40));
  		inputField.setContentSize(Vector2.create(320, 56));
  		const root = this.getRoot();
  		root.addChild(inputField);
  		inputField.attach();
  		inputField.setText("Invite code 1234");
  		inputField.selectAll();
  		inputField.requestMenuAction(UIInputFieldMenuAction.copy);
  		console.log(inputField.getSelectionText());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `showContextMenu(viewPosition)` (method, since 0.2.1): Shows the context menu. (An engine-drawn cut, copy, paste and select all menu, same as show_context_menu in the Rust edition)
  - It is made as the last child node of the root (a UIInputFieldContextMenu component) and drawn on top. The menu top left is the pressed point.
  - It closes when pressed outside the menu, or when the field loses focus or leaves the tree.
  - `viewPosition` Vector2: Top left of the menu. (view coordinates)

## UIInputFieldMenuAction (enum)

Context menu item. (cut / copy / paste / select all, received by requestMenuAction)

- `cut` = `cut`: Cut.
- `copy` = `copy`: Copy.
- `paste` = `paste`: Paste.
- `selectAll` = `selectAll`: Selects all.
