diff --git a/jupyter_ydoc/__init__.py b/jupyter_ydoc/__init__.py index 9450058..72304f0 100644 --- a/jupyter_ydoc/__init__.py +++ b/jupyter_ydoc/__init__.py @@ -7,6 +7,7 @@ from .yblob import YBlob as YBlob from .yfile import YFile as YFile from .ynotebook import YNotebook as YNotebook +from .ystdin import add_stdin as add_stdin from .yunicode import YUnicode as YUnicode # See compatibility note on `group` keyword in diff --git a/jupyter_ydoc/ystdin.py b/jupyter_ydoc/ystdin.py new file mode 100644 index 0000000..9c27da0 --- /dev/null +++ b/jupyter_ydoc/ystdin.py @@ -0,0 +1,33 @@ +from pycrdt import Map, Text + + +def add_stdin(cell: Map, prompt: str = "", password: bool = False) -> None: + """ + Adds an stdin Map in the cell outputs. + + Schema: + + .. code-block:: json + + { + "state": Map[ + "pending": bool, + "password": bool + ], + "prompt": str, + "input": Text + } + """ + stdin = Map( + { + "output_type": "stdin", + "state": { + "pending": True, + "password": password, + }, + "prompt": prompt, + "input": Text(), + } + ) + outputs = cell.get("outputs") + outputs.append(stdin) diff --git a/tests/test_ydocs.py b/tests/test_ydocs.py index c9fdd3e..e003dc5 100644 --- a/tests/test_ydocs.py +++ b/tests/test_ydocs.py @@ -1,7 +1,7 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. -from jupyter_ydoc import YBlob +from jupyter_ydoc import YBlob, YNotebook, add_stdin def test_yblob(): @@ -22,3 +22,34 @@ def callback(topic, event): assert topic == "source" assert event.keys["bytes"]["oldValue"] == b"012" assert event.keys["bytes"]["newValue"] == b"345" + + +def test_stdin(): + ynotebook = YNotebook() + ynotebook.append_cell( + { + "cell_type": "code", + "source": "", + } + ) + ycell = ynotebook.ycells[0] + add_stdin(ycell) + cell = ycell.to_py() + # cell ID is random, ignore that + del cell["id"] + assert cell == { + "outputs": [ + { + "output_type": "stdin", + "input": "", + "prompt": "", + "state": { + "password": False, + "pending": True, + }, + } + ], + "source": "", + "metadata": {}, + "cell_type": "code", + }