diff --git a/examples/height_changes.ipynb b/examples/height_changes.ipynb new file mode 100644 index 00000000..3cec5960 --- /dev/null +++ b/examples/height_changes.ipynb @@ -0,0 +1,493 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "0121fdae-74e8-472f-95ad-8443ae09467c", + "metadata": {}, + "outputs": [], + "source": [ + "from IPython.display import IFrame\n", + "\n", + "from lonboard import Map" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "48fb4374-8135-4926-89d3-d3f30694eeb9", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "e8079e0cc4dd43fbb45c4e861432f1a9", + "version_major": 2, + "version_minor": 1 + }, + "text/plain": [ + "Map(custom_attribution='', layout=Layout(height='100%', width='100%'), view_state=ViewState(longitude=0, latit…" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# without specifying height, defaults to 24rem or (500px in Vscode and colab) like before\n", + "# map will remain this soze, no matter if it is displayed in a notebook output cell\n", + "# or being displayed inside something else with a fixed height\n", + "height_none_map = Map(layers=[])\n", + "display(height_none_map)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69d62103-2fbb-4e87-914f-f6200dc4c830", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "height_none_map.to_html(\"height_None_map.html\", title=\"height_None_map\")\n", + "# displaying the map in 200px high IFrame results in the bottom of the map being hidden\n", + "# because it's the frame it is displayed inside is shorter than the map\n", + "# note the attribution is missing from the bottom of the map display because of this\n", + "# no one should do this, but if they did, this is what would happen\n", + "\n", + "## we could the body's overflow to scroll or something instead of hidden if that would be prefered\n", + "## that's in the _HTML_TEMPLATE. Looks like we'd need to tweak the margins if we want scroll\n", + "## bars instead of just hiding the overflow\n", + "\n", + "IFrame(\"height_None_map.html\", width=720, height=\"200px\")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "b2309663-9d0f-4bd4-835f-be0ab46708af", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "d3b1aa81e1524481b8ac800d7811ce23", + "version_major": 2, + "version_minor": 1 + }, + "text/plain": [ + "Map(custom_attribution='', height='100px', layout=Layout(height='100%', width='100%'), view_state=ViewState(lo…" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# Specify a height when making the map, and the map will stay that height in a notebook's output cell\n", + "# or when displayed inside something else just like when using the default height of 500px\n", + "height_100px_map = Map(layers=[], height=\"100px\")\n", + "display(height_100px_map)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "b2adf29d-cc57-4f77-8ed9-7865de877797", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "height_100px_map.to_html(\"height_100px_map.html\", title=\"height_100px_map\")\n", + "# displaying 100px high map in 200px high iframe results in 100 empty pixels below the map\n", + "IFrame(\"height_100px_map.html\", width=720, height=\"200px\")" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "b3347e36-1db0-4528-9018-6230c522acc5", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "455cd421882f49a9b7411dae804f6e71", + "version_major": 2, + "version_minor": 1 + }, + "text/plain": [ + "Map(custom_attribution='', height='100%', layout=Layout(height='100%', width='100%'), view_state=ViewState(lon…" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# specify height 100% and the map will not display by default in a notbook because the\n", + "# output widget in the notebook which the map is rendered inside does not have a fixed height\n", + "# and 100% of a non fixed height doesn't work. if you do this, it will not show up in a normal\n", + "# output cell in a notebook\n", + "height_100percent_map = Map(layers=[], height=\"100%\")\n", + "display(height_100percent_map)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "6d9dda26-9de1-4300-aa88-17e811b2ff69", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "height_100percent_map.to_html(\n", + " \"height_100percent_map.html\",\n", + " title=\"height_100percent_map\",\n", + ")\n", + "# If we take our 100% height map and display it inside an IFrame or other widget which has a fixed height\n", + "# the map expands to the full size of the widget. here we show the map inside a 200 and 400px IFrame\n", + "display(IFrame(\"height_100percent_map.html\", width=720, height=\"200px\"))\n", + "IFrame(\"height_100percent_map.html\", width=720, height=\"400px\")" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "87502cdf-5489-4c3e-a1fc-634fca7f98a4", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/javascript": "(function(root) {\n function now() {\n return new Date();\n }\n\n const force = true;\n const py_version = '3.7.3'.replace('rc', '-rc.').replace('.dev', '-dev.');\n const reloading = false;\n const Bokeh = root.Bokeh;\n\n // Set a timeout for this load but only if we are not already initializing\n if (typeof (root._bokeh_timeout) === \"undefined\" || (force || !root._bokeh_is_initializing)) {\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_failed_load = false;\n }\n\n function run_callbacks() {\n try {\n root._bokeh_onload_callbacks.forEach(function(callback) {\n if (callback != null)\n callback();\n });\n } finally {\n delete root._bokeh_onload_callbacks;\n }\n console.debug(\"Bokeh: all callbacks have finished\");\n }\n\n function load_libs(css_urls, js_urls, js_modules, js_exports, callback) {\n if (css_urls == null) css_urls = [];\n if (js_urls == null) js_urls = [];\n if (js_modules == null) js_modules = [];\n if (js_exports == null) js_exports = {};\n\n root._bokeh_onload_callbacks.push(callback);\n\n if (root._bokeh_is_loading > 0) {\n // Don't load bokeh if it is still initializing\n console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n return null;\n } else if (js_urls.length === 0 && js_modules.length === 0 && Object.keys(js_exports).length === 0) {\n // There is nothing to load\n run_callbacks();\n return null;\n }\n\n function on_load() {\n root._bokeh_is_loading--;\n if (root._bokeh_is_loading === 0) {\n console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n run_callbacks()\n }\n }\n window._bokeh_on_load = on_load\n\n function on_error(e) {\n const src_el = e.srcElement\n console.error(\"failed to load \" + (src_el.href || src_el.src));\n }\n\n const skip = [];\n if (window.requirejs) {\n window.requirejs.config({'packages': {}, 'paths': {}, 'shim': {}});\n root._bokeh_is_loading = css_urls.length + 0;\n } else {\n root._bokeh_is_loading = css_urls.length + js_urls.length + js_modules.length + Object.keys(js_exports).length;\n }\n\n const existing_stylesheets = []\n const links = document.getElementsByTagName('link')\n for (let i = 0; i < links.length; i++) {\n const link = links[i]\n if (link.href != null) {\n existing_stylesheets.push(link.href)\n }\n }\n for (let i = 0; i < css_urls.length; i++) {\n const url = css_urls[i];\n const escaped = encodeURI(url)\n if (existing_stylesheets.indexOf(escaped) !== -1) {\n on_load()\n continue;\n }\n const element = document.createElement(\"link\");\n element.onload = on_load;\n element.onerror = on_error;\n element.rel = \"stylesheet\";\n element.type = \"text/css\";\n element.href = url;\n console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n document.body.appendChild(element);\n } var existing_scripts = []\n const scripts = document.getElementsByTagName('script')\n for (let i = 0; i < scripts.length; i++) {\n var script = scripts[i]\n if (script.src != null) {\n existing_scripts.push(script.src)\n }\n }\n for (let i = 0; i < js_urls.length; i++) {\n const url = js_urls[i];\n const escaped = encodeURI(url)\n if (skip.indexOf(escaped) !== -1 || existing_scripts.indexOf(escaped) !== -1) {\n if (!window.requirejs) {\n on_load();\n }\n continue;\n }\n const element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error;\n element.async = false;\n element.src = url;\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n for (let i = 0; i < js_modules.length; i++) {\n const url = js_modules[i];\n const escaped = encodeURI(url)\n if (skip.indexOf(escaped) !== -1 || existing_scripts.indexOf(escaped) !== -1) {\n if (!window.requirejs) {\n on_load();\n }\n continue;\n }\n var element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error;\n element.async = false;\n element.src = url;\n element.type = \"module\";\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n for (const name in js_exports) {\n const url = js_exports[name];\n const escaped = encodeURI(url)\n if (skip.indexOf(escaped) >= 0 || root[name] != null) {\n if (!window.requirejs) {\n on_load();\n }\n continue;\n }\n var element = document.createElement('script');\n element.onerror = on_error;\n element.async = false;\n element.type = \"module\";\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n element.textContent = `\n import ${name} from \"${url}\"\n window.${name} = ${name}\n window._bokeh_on_load()\n `\n document.head.appendChild(element);\n }\n if (!js_urls.length && !js_modules.length) {\n on_load()\n }\n };\n\n function inject_raw_css(css) {\n const element = document.createElement(\"style\");\n element.appendChild(document.createTextNode(css));\n document.body.appendChild(element);\n }\n\n const js_urls = [\"https://cdn.holoviz.org/panel/1.7.1/dist/bundled/reactiveesm/es-module-shims@^1.10.0/dist/es-module-shims.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-3.7.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-3.7.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-3.7.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-3.7.3.min.js\", \"https://cdn.holoviz.org/panel/1.7.1/dist/panel.min.js\"];\n const js_modules = [];\n const js_exports = {};\n const css_urls = [\"https://cdn.holoviz.org/panel/1.7.1/dist/bundled/font-awesome/css/all.min.css\"];\n const inline_js = [ function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\nfunction(Bokeh) {} // ensure no trailing comma for IE\n ];\n\n function run_inline_js() {\n if ((root.Bokeh !== undefined) || (force === true)) {\n for (let i = 0; i < inline_js.length; i++) {\n try {\n inline_js[i].call(root, root.Bokeh);\n } catch(e) {\n if (!reloading) {\n throw e;\n }\n }\n }\n // Cache old bokeh versions\n if (Bokeh != undefined && !reloading) {\n var NewBokeh = root.Bokeh;\n if (Bokeh.versions === undefined) {\n Bokeh.versions = new Map();\n }\n if (NewBokeh.version !== Bokeh.version) {\n Bokeh.versions.set(NewBokeh.version, NewBokeh)\n }\n root.Bokeh = Bokeh;\n }\n } else if (Date.now() < root._bokeh_timeout) {\n setTimeout(run_inline_js, 100);\n } else if (!root._bokeh_failed_load) {\n console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n root._bokeh_failed_load = true;\n }\n root._bokeh_is_initializing = false\n }\n\n function load_or_wait() {\n // Implement a backoff loop that tries to ensure we do not load multiple\n // versions of Bokeh and its dependencies at the same time.\n // In recent versions we use the root._bokeh_is_initializing flag\n // to determine whether there is an ongoing attempt to initialize\n // bokeh, however for backward compatibility we also try to ensure\n // that we do not start loading a newer (Panel>=1.0 and Bokeh>3) version\n // before older versions are fully initialized.\n if (root._bokeh_is_initializing && Date.now() > root._bokeh_timeout) {\n // If the timeout and bokeh was not successfully loaded we reset\n // everything and try loading again\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_is_initializing = false;\n root._bokeh_onload_callbacks = undefined;\n root._bokeh_is_loading = 0\n console.log(\"Bokeh: BokehJS was loaded multiple times but one version failed to initialize.\");\n load_or_wait();\n } else if (root._bokeh_is_initializing || (typeof root._bokeh_is_initializing === \"undefined\" && root._bokeh_onload_callbacks !== undefined)) {\n setTimeout(load_or_wait, 100);\n } else {\n root._bokeh_is_initializing = true\n root._bokeh_onload_callbacks = []\n const bokeh_loaded = root.Bokeh != null && (root.Bokeh.version === py_version || (root.Bokeh.versions !== undefined && root.Bokeh.versions.has(py_version)));\n if (!reloading && !bokeh_loaded) {\n if (root.Bokeh) {\n root.Bokeh = undefined;\n }\n console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n }\n load_libs(css_urls, js_urls, js_modules, js_exports, function() {\n console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n run_inline_js();\n });\n }\n }\n // Give older versions of the autoload script a head-start to ensure\n // they initialize before we start loading newer version.\n setTimeout(load_or_wait, 100)\n}(window));", + "application/vnd.holoviews_load.v0+json": "" + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/javascript": "\nif ((window.PyViz === undefined) || (window.PyViz instanceof HTMLElement)) {\n window.PyViz = {comms: {}, comm_status:{}, kernels:{}, receivers: {}, plot_index: []}\n}\n\n\n function JupyterCommManager() {\n }\n\n JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {\n if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n comm_manager.register_target(comm_id, function(comm) {\n comm.on_msg(msg_handler);\n });\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {\n comm.onMsg = msg_handler;\n });\n } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n google.colab.kernel.comms.registerTarget(comm_id, (comm) => {\n var messages = comm.messages[Symbol.asyncIterator]();\n function processIteratorResult(result) {\n var message = result.value;\n var content = {data: message.data, comm_id};\n var buffers = []\n for (var buffer of message.buffers || []) {\n buffers.push(new DataView(buffer))\n }\n var metadata = message.metadata || {};\n var msg = {content, buffers, metadata}\n msg_handler(msg);\n return messages.next().then(processIteratorResult);\n }\n return messages.next().then(processIteratorResult);\n })\n }\n }\n\n JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {\n if (comm_id in window.PyViz.comms) {\n return window.PyViz.comms[comm_id];\n } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);\n if (msg_handler) {\n comm.on_msg(msg_handler);\n }\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);\n let retries = 0;\n const open = () => {\n if (comm.active) {\n comm.open();\n } else if (retries > 3) {\n console.warn('Comm target never activated')\n } else {\n retries += 1\n setTimeout(open, 500)\n }\n }\n if (comm.active) {\n comm.open();\n } else {\n setTimeout(open, 500)\n }\n if (msg_handler) {\n comm.onMsg = msg_handler;\n }\n } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n var comm_promise = google.colab.kernel.comms.open(comm_id)\n comm_promise.then((comm) => {\n window.PyViz.comms[comm_id] = comm;\n if (msg_handler) {\n var messages = comm.messages[Symbol.asyncIterator]();\n function processIteratorResult(result) {\n var message = result.value;\n var content = {data: message.data};\n var metadata = message.metadata || {comm_id};\n var msg = {content, metadata}\n msg_handler(msg);\n return messages.next().then(processIteratorResult);\n }\n return messages.next().then(processIteratorResult);\n }\n })\n var sendClosure = (data, metadata, buffers, disposeOnDone) => {\n return comm_promise.then((comm) => {\n comm.send(data, metadata, buffers, disposeOnDone);\n });\n };\n var comm = {\n send: sendClosure\n };\n }\n window.PyViz.comms[comm_id] = comm;\n return comm;\n }\n window.PyViz.comm_manager = new JupyterCommManager();\n \n\n\nvar JS_MIME_TYPE = 'application/javascript';\nvar HTML_MIME_TYPE = 'text/html';\nvar EXEC_MIME_TYPE = 'application/vnd.holoviews_exec.v0+json';\nvar CLASS_NAME = 'output';\n\n/**\n * Render data to the DOM node\n */\nfunction render(props, node) {\n var div = document.createElement(\"div\");\n var script = document.createElement(\"script\");\n node.appendChild(div);\n node.appendChild(script);\n}\n\n/**\n * Handle when a new output is added\n */\nfunction handle_add_output(event, handle) {\n var output_area = handle.output_area;\n var output = handle.output;\n if ((output.data == undefined) || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n return\n }\n var id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n if (id !== undefined) {\n var nchildren = toinsert.length;\n var html_node = toinsert[nchildren-1].children[0];\n html_node.innerHTML = output.data[HTML_MIME_TYPE];\n var scripts = [];\n var nodelist = html_node.querySelectorAll(\"script\");\n for (var i in nodelist) {\n if (nodelist.hasOwnProperty(i)) {\n scripts.push(nodelist[i])\n }\n }\n\n scripts.forEach( function (oldScript) {\n var newScript = document.createElement(\"script\");\n var attrs = [];\n var nodemap = oldScript.attributes;\n for (var j in nodemap) {\n if (nodemap.hasOwnProperty(j)) {\n attrs.push(nodemap[j])\n }\n }\n attrs.forEach(function(attr) { newScript.setAttribute(attr.name, attr.value) });\n newScript.appendChild(document.createTextNode(oldScript.innerHTML));\n oldScript.parentNode.replaceChild(newScript, oldScript);\n });\n if (JS_MIME_TYPE in output.data) {\n toinsert[nchildren-1].children[1].textContent = output.data[JS_MIME_TYPE];\n }\n output_area._hv_plot_id = id;\n if ((window.Bokeh !== undefined) && (id in Bokeh.index)) {\n window.PyViz.plot_index[id] = Bokeh.index[id];\n } else {\n window.PyViz.plot_index[id] = null;\n }\n } else if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n var bk_div = document.createElement(\"div\");\n bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n var script_attrs = bk_div.children[0].attributes;\n for (var i = 0; i < script_attrs.length; i++) {\n toinsert[toinsert.length - 1].childNodes[1].setAttribute(script_attrs[i].name, script_attrs[i].value);\n }\n // store reference to server id on output_area\n output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n }\n}\n\n/**\n * Handle when an output is cleared or removed\n */\nfunction handle_clear_output(event, handle) {\n var id = handle.cell.output_area._hv_plot_id;\n var server_id = handle.cell.output_area._bokeh_server_id;\n if (((id === undefined) || !(id in PyViz.plot_index)) && (server_id !== undefined)) { return; }\n var comm = window.PyViz.comm_manager.get_client_comm(\"hv-extension-comm\", \"hv-extension-comm\", function () {});\n if (server_id !== null) {\n comm.send({event_type: 'server_delete', 'id': server_id});\n return;\n } else if (comm !== null) {\n comm.send({event_type: 'delete', 'id': id});\n }\n delete PyViz.plot_index[id];\n if ((window.Bokeh !== undefined) & (id in window.Bokeh.index)) {\n var doc = window.Bokeh.index[id].model.document\n doc.clear();\n const i = window.Bokeh.documents.indexOf(doc);\n if (i > -1) {\n window.Bokeh.documents.splice(i, 1);\n }\n }\n}\n\n/**\n * Handle kernel restart event\n */\nfunction handle_kernel_cleanup(event, handle) {\n delete PyViz.comms[\"hv-extension-comm\"];\n window.PyViz.plot_index = {}\n}\n\n/**\n * Handle update_display_data messages\n */\nfunction handle_update_output(event, handle) {\n handle_clear_output(event, {cell: {output_area: handle.output_area}})\n handle_add_output(event, handle)\n}\n\nfunction register_renderer(events, OutputArea) {\n function append_mime(data, metadata, element) {\n // create a DOM node to render to\n var toinsert = this.create_output_subarea(\n metadata,\n CLASS_NAME,\n EXEC_MIME_TYPE\n );\n this.keyboard_manager.register_events(toinsert);\n // Render to node\n var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n render(props, toinsert[0]);\n element.append(toinsert);\n return toinsert\n }\n\n events.on('output_added.OutputArea', handle_add_output);\n events.on('output_updated.OutputArea', handle_update_output);\n events.on('clear_output.CodeCell', handle_clear_output);\n events.on('delete.Cell', handle_clear_output);\n events.on('kernel_ready.Kernel', handle_kernel_cleanup);\n\n OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n safe: true,\n index: 0\n });\n}\n\nif (window.Jupyter !== undefined) {\n try {\n var events = require('base/js/events');\n var OutputArea = require('notebook/js/outputarea').OutputArea;\n if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n register_renderer(events, OutputArea);\n }\n } catch(err) {\n }\n}\n", + "application/vnd.holoviews_load.v0+json": "" + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.holoviews_exec.v0+json": "", + "text/html": [ + "
\n", + "
\n", + "
\n", + "" + ] + }, + "metadata": { + "application/vnd.holoviews_exec.v0+json": { + "id": "44d317a2-b78f-4258-88f3-71bcffa18f94" + } + }, + "output_type": "display_data" + }, + { + "data": {}, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "application/vnd.holoviews_exec.v0+json": "", + "text/html": [ + "
\n", + "
\n", + "
\n", + "" + ], + "text/plain": [ + "IPyWidget(Map, height=500, sizing_mode='fixed', width=1000)" + ] + }, + "execution_count": 8, + "metadata": { + "application/vnd.holoviews_exec.v0+json": { + "id": "74add4b9-8fbf-42f9-86b5-80e299999012" + } + }, + "output_type": "execute_result" + } + ], + "source": [ + "# also works within a panel IPyWidget pane!\n", + "import panel as pn\n", + "\n", + "pn.extension(\"ipywidgets\")\n", + "pn.pane.IPyWidget(height_100percent_map, height=500, width=1000).servable()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "lonboard", + "language": "python", + "name": "lonboard" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.11" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lonboard/_environment.py b/lonboard/_environment.py index 080c313d..9137c409 100644 --- a/lonboard/_environment.py +++ b/lonboard/_environment.py @@ -55,9 +55,8 @@ def detect_environment() -> Environment: # noqa: PLR0911 def default_height() -> int | None: if ENVIRONMENT in [Environment.Vscode, Environment.Colab]: - return 500 - - return None + return "500px" + return "24rem" DEFAULT_HEIGHT = default_height() diff --git a/lonboard/_map.py b/lonboard/_map.py index 8a3801b6..e6044af3 100644 --- a/lonboard/_map.py +++ b/lonboard/_map.py @@ -11,13 +11,13 @@ from ipywidgets.embed import dependency_state, embed_minimal_html from lonboard._base import BaseAnyWidget -from lonboard._environment import DEFAULT_HEIGHT from lonboard._layer import BaseLayer from lonboard._viewport import compute_view from lonboard.basemap import CartoBasemap from lonboard.traits import ( DEFAULT_INITIAL_VIEW_STATE, BasemapUrl, + HeightTrait, VariableLengthTuple, ViewStateTrait, ) @@ -48,7 +48,7 @@ @@ -120,6 +120,8 @@ def _handle_anywidget_dispatch( super().__init__(layers=layers, **kwargs) self._click_handlers = CallbackDispatcher() self.on_msg(_handle_anywidget_dispatch) + self.layout.height = "100%" + self.layout.width = "100%" def on_click(self, callback: Callable, *, remove: bool = False) -> None: """Register a callback to execute when the map is clicked. @@ -177,8 +179,8 @@ def on_click(self, callback: Callable, *, remove: bool = False) -> None: Indicates if a click handler has been registered. """ - _height = t.Int(default_value=DEFAULT_HEIGHT, allow_none=True).tag(sync=True) - """Height of the map in pixels. + height = HeightTrait().tag(sync=True) + """Height of the map in pixels, or valid CSS height property. This API is not yet stabilized and may change in the future. """ @@ -565,16 +567,23 @@ def to_html( """ def inner(fp: str | Path | TextIO | IO[str]) -> None: - embed_minimal_html( - fp, - views=[self], - title=title or "Lonboard export", - template=_HTML_TEMPLATE, - drop_defaults=False, - # Necessary to pass the state of _this_ specific map. Otherwise, the - # state of all known widgets will be included, ballooning the file size. - state=dependency_state((self), drop_defaults=False), - ) + original_height = self.height + try: + with self.hold_trait_notifications(): + self.height = "100%" + embed_minimal_html( + fp, + views=[self], + title=title or "Lonboard export", + template=_HTML_TEMPLATE, + drop_defaults=False, + # Necessary to pass the state of _this_ specific map. Otherwise, the + # state of all known widgets will be included, ballooning the file size. + state=dependency_state((self), drop_defaults=False), + ) + finally: + # If the map had a height before the HTML was generated, reset it. + self.height = original_height if filename is None: with StringIO() as sio: diff --git a/lonboard/traits.py b/lonboard/traits.py index 59cfc6ad..090432dd 100644 --- a/lonboard/traits.py +++ b/lonboard/traits.py @@ -27,6 +27,7 @@ from traitlets import TraitError, Undefined from traitlets.utils.descriptions import class_of, describe +from lonboard._environment import DEFAULT_HEIGHT from lonboard._serialization import ( ACCESSOR_SERIALIZATION, TABLE_SERIALIZATION, @@ -1160,3 +1161,29 @@ def validate_elements(self, obj: Any, value: Any) -> Any: validated.append(v) return tuple(validated) + + +class HeightTrait(FixedErrorTraitType): + """Trait to validate map height input.""" + + allow_none = True + default_value = DEFAULT_HEIGHT + + def __init__( + self: TraitType, + *args: Any, + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + + self.tag(sync=True) + + def validate(self, obj: Any, value: Any) -> str: + if isinstance(value, int): + return f"{value}px" + + if isinstance(value, str): + return value + + self.error(obj, value) + assert False diff --git a/src/globals.css b/src/globals.css index 25ad1403..3b88b8c3 100644 --- a/src/globals.css +++ b/src/globals.css @@ -28,5 +28,12 @@ div.lonboard { @tailwind base; } +[data-overlay-container] { + height: 100%; + width: 100%; + margin-top: -5px; + margin-bottom: -5px; +} + @tailwind components; @tailwind utilities; diff --git a/src/index.tsx b/src/index.tsx index cea874a4..51ea2cea 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -97,7 +97,7 @@ function App() { const model = useModel(); const [mapStyle] = useModelState("basemap_style"); - const [mapHeight] = useModelState("_height"); + const [mapHeight] = useModelState("height"); const [showTooltip] = useModelState("show_tooltip"); const [showSidePanel] = useModelState("show_side_panel"); const [pickingRadius] = useModelState("picking_radius"); @@ -215,11 +215,11 @@ function App() { ); return ( -
+