Coverage for pyquickhelper/ipythonhelper/html_forms.py: 91%
35 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1"""
2@file
3@brief Some functions to interact better with Notebook
4"""
6import re
8_reg_var = re.compile("^[a-zA-Z_]([a-zA-Z_0-9]*)$")
11def open_html_form(params, title='', key_save="",
12 style="background-color:gainsboro; padding:2px; border:0px;",
13 raw=False, hook=None):
14 """
15 The function displays a form onto a notebook,
16 it requires a notebook to be open.
18 @param params dictionary of parameters (see comment below)
19 @param title titre of the added box
20 @param style style of the form
21 @param key_save name of the variable to add to the notebook (as a dictionary)
22 @param raw returns the raw HTML and not ``HTML( text )``
23 @param hook an instruction as a string which will be executed if the button is clicked (None for none)
24 @return HTML
26 The code comes from
27 `IPython Notebook: Javascript/Python Bi-directional Communication
28 <https://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/>`_.
29 When the notebook is converted into a HTML document, the values in the form do not appear.
30 This behaviour is expected in case one of the field contains a password. On a notebook, it
31 gives the following result:
33 .. exref::
34 :title: Open a add a form in a notebook to ask parameters to a user
36 .. image:: images/form.png
38 Cell 1::
40 from pyquickhelper.ipythonhelper import open_html_form
41 params = { "module":, "version":"v..." }
42 open_html_form (params, title="try the password *", key_save="form1")
44 Cell 2::
46 print(form1)
48 We can execute a simple action after the button *Ok* is pressed. This second trick
49 comes from `this notebook <https://raw.githubusercontent.com/fluxtream/fluxtream-ipy/master/
50 Communication%20between%20kernel%20and%20javascript%20in%20iPython%202.0.ipynb>`_.
51 The code displays whatever comes from function ``custom_action`` in this case.
52 You should return ``""`` to display nothing.
54 ::
56 def custom_action(x):
57 x["combined"] = x["first_name"] + " " + x["last_name"]
58 return x
60 params = { "first_name":"", "last_name":"" }
61 open_html_form(params, title="enter your name", key_save="my_address",
62 hook="custom_action(my_address)")
64 The function generates javascript based on the keys the dictionary ``params`` contains.
65 The keys must follows the same as a javascript identifier (no space).
66 """
67 global _reg_var
68 for k in params:
69 if not _reg_var.match(k):
70 raise KeyError( # pragma: no cover
71 "keys in params must look like a variable, it is not the case for "
72 "'{}'.".format(k))
74 row = """<br />{0} <input type="{3}" id="{2}{0}" value="{1}" size="80" />"""
76 rows = [f"""<div style="{style}"><b>{title}</b>"""]
77 for k, v in sorted(params.items()):
78 if k.startswith("password"):
79 typ = "password"
80 else:
81 typ = "text"
82 rows.append(row.format(k, "" if v is None else str(v), key_save, typ))
83 rows.append(
84 f"""<br /><button onclick="set_value{key_save}()">Ok</button></div>""")
85 if hook is not None:
86 rows.append(f"<div id='out{key_save.replace('_', '')}'></div>")
88 rows.append("""<script type="text/Javascript">""")
89 rows.append("function %scallback(msg) {" % key_save)
90 rows.append(" var ret = msg.content.data['text/plain'];")
91 rows.append(f" $('#out{key_save.replace('_', '')}').text(ret);")
92 rows.append("}")
93 rows.append("function set_value__KEY__(){".replace("__KEY__", key_save))
95 rows.append(" command='%s = {' ;" % key_save)
96 for k, v in sorted(params.items()):
97 rows.append(
98 """ var {0}{1}var_value = document.getElementById('{0}{1}').value;""".format(key_save, k))
99 rows.append(f""" command += '"{k}":"' + """ +
100 f"{key_save}{k}var_value" + """ + '",';""")
101 rows.append(""" command += '}';""")
102 rows.append(""" var kernel = IPython.notebook.kernel;""")
103 rows.append(""" kernel.execute(command);""")
104 if hook is not None:
105 rows.append(""" kernel.execute('%s', {iopub: {output: %scallback}}, {silent: false});""" % (
106 hook, key_save))
107 rows.append("""}""")
108 rows.append("</script>")
110 text = "\n".join(rows)
112 if raw:
113 return text
114 from IPython.display import HTML # pragma: no cover
115 return HTML(text) # pragma: no cover