Skip to content
\n

components/xterm.txs

\n
/**\nMIT License\n\nCopyright (c) 2020 Robert Harbison\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n/* eslint @typescript-eslint/unbound-method: 0 */\n\nimport React from \"react\";\nimport {\n    forwardRef,\n    useEffect,\n    useImperativeHandle,\n    useLayoutEffect,\n    useRef,\n    useState,\n  } from \"react\";\n  import type { ITerminalOptions, ITerminalAddon } from \"@xterm/xterm\";\n  import { Terminal } from \"@xterm/xterm\";\n  import \"@xterm/xterm/css/xterm.css\";\n\n  interface Props {\n    /**\n     * Class name to add to the terminal container.\n     */\n    className?: string;\n  \n    /**\n     * Options to initialize the terminal with.\n     */\n    options?: ITerminalOptions;\n  \n    /**\n     * An array of XTerm addons to load along with the terminal.current.\n     */\n    addons?: Array<ITerminalAddon>;\n  \n    /**\n     * Adds an event listener for when a binary event fires. This is used to\n     * enable non UTF-8 conformant binary messages to be sent to the backend.\n     * Currently this is only used for a certain type of mouse reports that\n     * happen to be not UTF-8 compatible.\n     * The event value is a JS string, pass it to the underlying pty as\n     * binary data, e.g. `pty.write(Buffer.from(data, 'binary'))`.\n     */\n    onBinary?(data: string): void;\n  \n    /**\n     * Adds an event listener for the cursor moves.\n     */\n    onCursorMove?(): void;\n  \n    /**\n     * Adds an event listener for when a data event fires. This happens for\n     * example when the user types or pastes into the terminal.current. The event value\n     * is whatever `string` results, in a typical setup, this should be passed\n     * on to the backing pty.\n     */\n    onData?(data: string): void;\n  \n    /**\n     * Adds an event listener for when a key is pressed. The event value contains the\n     * string that will be sent in the data event as well as the DOM event that\n     * triggered it.\n     */\n    onKey?(event: { key: string; domEvent: KeyboardEvent }): void;\n  \n    /**\n     * Adds an event listener for when a line feed is added.\n     */\n    onLineFeed?(): void;\n  \n    /**\n     * Adds an event listener for when a scroll occurs. The event value is the\n     * new position of the viewport.\n     * @returns an `IDisposable` to stop listening.\n     */\n    onScroll?(newPosition: number): void;\n  \n    /**\n     * Adds an event listener for when a selection change occurs.\n     */\n    onSelectionChange?(): void;\n  \n    /**\n     * Adds an event listener for when rows are rendered. The event value\n     * contains the start row and end rows of the rendered area (ranges from `0`\n     * to `terminal.current.rows - 1`).\n     */\n    onRender?(event: { start: number; end: number }): void;\n  \n    /**\n     * Adds an event listener for when the terminal is resized. The event value\n     * contains the new size.\n     */\n    onResize?(event: { cols: number; rows: number }): void;\n  \n    /**\n     * Adds an event listener for when an OSC 0 or OSC 2 title change occurs.\n     * The event value is the new title.\n     */\n    onTitleChange?(newTitle: string): void;\n  \n    /**\n     * Attaches a custom key event handler which is run before keys are\n     * processed, giving consumers of xterm.js ultimate control as to what keys\n     * should be processed by the terminal and what keys should not.\n     *\n     * @param event The custom KeyboardEvent handler to attach.\n     * This is a function that takes a KeyboardEvent, allowing consumers to stop\n     * propagation and/or prevent the default action. The function returns\n     * whether the event should be processed by xterm.js.\n     */\n    customKeyEventHandler?(event: KeyboardEvent): boolean;\n  \n    /**\n     * This callback porovides an interface for running actions directly after\n     * the terminal is open. Some useful cations includes resizing the terminal\n     * or focusing on the terminal etc.\n     */\n    onOpen?(): void;\n  }\n  \n  export default forwardRef<Terminal, Props>(function Xterm(\n    {\n      options = {},\n      addons,\n      className,\n      onBinary,\n      onCursorMove,\n      onData,\n      onKey,\n      onLineFeed,\n      onScroll,\n      onSelectionChange,\n      onRender,\n      onResize,\n      onTitleChange,\n      customKeyEventHandler,\n      onOpen,\n    }: Props,\n    ref,\n  ) {\n    const [terminalOpen, setTerminalOpen] = useState(false);\n    const terminalRef = useRef<HTMLDivElement>(null);\n    const xtermRef = useRef<Terminal>(new Terminal(options));\n  \n    useImperativeHandle(ref, () => {\n      return xtermRef.current;\n    });\n  \n    const initialiseXterm = () => {\n      // Load addons if the prop exists.\n      if (addons) {\n        addons.forEach((addon) => {\n          xtermRef.current?.loadAddon(addon);\n        });\n      }\n  \n      // Create Listeners\n      if (onBinary) xtermRef.current.onBinary(onBinary);\n      if (onCursorMove) xtermRef.current.onCursorMove(onCursorMove);\n      if (onData) xtermRef.current.onData(onData);\n      if (onKey) xtermRef.current.onKey(onKey);\n      if (onLineFeed) xtermRef.current.onLineFeed(onLineFeed);\n      if (onScroll) xtermRef.current.onScroll(onScroll);\n      if (onSelectionChange)\n        xtermRef.current.onSelectionChange(onSelectionChange);\n      if (onRender) xtermRef.current.onRender(onRender);\n      if (onResize) xtermRef.current.onResize(onResize);\n      if (onTitleChange) xtermRef.current.onTitleChange(onTitleChange);\n  \n      // Add Custom Key Event Handler\n      if (customKeyEventHandler) {\n        xtermRef.current.attachCustomKeyEventHandler(customKeyEventHandler);\n      }\n    };\n  \n    useEffect(() => {\n      const terminal = terminalRef.current;\n      if (terminal) {\n        initialiseXterm();\n        xtermRef.current?.open(terminal);\n        setTerminalOpen(true);\n      }\n  \n      return () => {\n        xtermRef.current?.dispose();\n      };\n    }, []);\n  \n    useLayoutEffect(() => {\n      if (terminalOpen && onOpen) {\n        onOpen();\n      }\n    }, [terminalOpen]);\n  \n    return <div className={className} ref={terminalRef} />;\n  });
\n

Screen shots:

\n

\"Image\"

\n

\"Image\"

\n

\"Image\"

","upvoteCount":1,"answerCount":2,"acceptedAnswer":{"@type":"Answer","text":"

Hmm, your code looks like a control flow nightmare to me, so it is somewhat hard to comprehend. When you focus the terminal widget and try typing something, does your console.log(\"Ws\", dataWs); in the onData handler output anything at all?

\n

If not - the problem lies within the frontend code. Might be a race condition, when things get attached/assigned and the execution order. I see you have many someVar?. constructs there, could be, that someVar never turns to true due to issues in the setup execution. In that case - check every of those maybe vars.

\n

If yes - the problem lies on the server part. Check whether the server can correctly read data from the websocket. To debug that, simply place the websocket in global scope and enter text vs. byte data manually at the console. If your backend is picky, it might only work with text or bytes exclusively, but not both.

","upvoteCount":2,"url":"https://github.com/xtermjs/xterm.js/discussions/5332#discussioncomment-12961389"}}}

Unable to Send Data from xterm Console to LXD WebSocket #5332

Closed Answered by jerch
irtaza9 asked this question in Q&A
Discussion options

You must be logged in to vote

Hmm, your code looks like a control flow nightmare to me, so it is somewhat hard to comprehend. When you focus the terminal widget and try typing something, does your console.log("Ws", dataWs); in the onData handler output anything at all?

If not - the problem lies within the frontend code. Might be a race condition, when things get attached/assigned and the execution order. I see you have many someVar?. constructs there, could be, that someVar never turns to true due to issues in the setup execution. In that case - check every of those maybe vars.

If yes - the problem lies on the server part. Check whether the server can correctly read data from the websocket. To debug that, simply place…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by irtaza9
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #5331 on April 27, 2025 15:02.