def get_element(self): # Create the HTML content for the toolbar div = document.createElement("span") def add_spacer(): span = document.createElement("span") span.style.minWidth = "16px" span.textContent = "\u00a0" div.appendChild(span) for text, tooltip_text, image_file, name_of_method in self.toolitems: if image_file in _FONTAWESOME_ICONS: if image_file is None: add_spacer() else: button = document.createElement("button") button.classList.add("fa") button.classList.add(_FONTAWESOME_ICONS[image_file]) button.classList.add("matplotlib-toolbar-button") button.addEventListener("click", getattr(self, name_of_method)) div.appendChild(button) for format, mimetype in sorted(list(FILE_TYPES.items())): button = document.createElement("button") button.classList.add("fa") button.textContent = format button.classList.add("matplotlib-toolbar-button") button.id = "text" button.addEventListener("click", self.ondownload) div.appendChild(button) return div
def get_element(self): # Creat the HTML content for the toolbar div = document.createElement('span') def add_spacer(): span = document.createElement('span') span.style.minWidth = '16px' span.textContent = '\u00a0' div.appendChild(span) for text, tooltip_text, image_file, name_of_method in self.toolitems: if image_file in _FONTAWESOME_ICONS: if image_file is None: add_spacer() else: button = document.createElement('button') button.classList.add('fa') button.classList.add(_FONTAWESOME_ICONS[image_file]) button.addEventListener('click', getattr(self, name_of_method)) div.appendChild(button) for format, mimetype in sorted(list(FILE_TYPES.items())): button = document.createElement('button') button.classList.add('fa') button.textContent = format button.addEventListener( 'click', self.ondownload) div.appendChild(button) return div
def create_root_element(self): try: parent = document.getElementById('imagediv') if parent.lastElementChild.tagName == 'DIV': parent.lastElementChild.innerHTML = '' return parent.lastElementChild else: newelement = document.createElement("div") parent.append(newelement) return newelement except Exception as e: print(e) return document.createElement("div")
def _add_matplotlib_styles(self): toolbar_buttons_css_content = """ button.matplotlib-toolbar-button { font-size: 14px; color: #495057; text-transform: uppercase; background: #e9ecef; padding: 9px 18px; border: 1px solid #fff; border-radius: 4px; transition-duration: 0.4s; } button.matplotlib-toolbar-button#text { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } button.matplotlib-toolbar-button:hover { color: #fff; background: #495057; } """ toolbar_buttons_style_element = document.createElement("style") toolbar_buttons_style_element.id = "matplotlib-figure-styles" toolbar_buttons_css = document.createTextNode( toolbar_buttons_css_content) toolbar_buttons_style_element.appendChild(toolbar_buttons_css) return toolbar_buttons_style_element
async def async_create_available_robots_list(self): print_div("Auto discovering..") await self.plugin_discovery.async_autodiscover(None) try: # print_div("Clearing the previous available robot options..") length = self.available_robots_list.options.length i = length-1 while i >= 0: self.available_robots_list.options[i] = None i -= 1 print_div('Creating available robots options..<br>') self.robot_nodeNames = await self.plugin_discovery.async_available_robot_NodeNames(None) print_div(str(self.robot_nodeNames) + "<br>") i = 0 for nodeName in self.robot_nodeNames: # print_div(str(self.robot_nodeNames[key]) + "<br>") # --> Right # Add the available robot nodeName to the available_robots list option = document.createElement("option") option.text = str(i) + ": " + str(nodeName) self.available_robots_list.add(option) i += 1 except: import traceback print_div(traceback.format_exc())
def _create_element(self, parent_element: JsProxy) -> JsProxy: # Create a DOM element to represent this object self.element = document.createElement(self.tag) if self.top_custom_component == self: self.element.setAttribute("identifier", self.identifier) # Set attributes for attribute, value in self.attributes.items(): self._set_attribute(attribute, value) # Add the element to its parent if parent_element is not None: parent_element.appendChild(self.element) # Create event listeners for event, handler in self.event_handlers.items(): self.element.addEventListener(event, handler) # Add any content (text) if self.content is not None: self.element.appendChild(document.createTextNode(self.content)) # Run the onMount function of the component self.on_mount()
def download(self, format, mimetype): """ Creates a temporary `a` element with a URL containing the image content, and then virtually clicks it. Kind of magical, but it works... """ element = document.createElement("a") data = io.BytesIO() if format == "png": FigureCanvasHTMLCanvas.print_png(self.canvas, data) else: try: self.canvas.figure.savefig(data, format=format) except Exception: raise element.setAttribute( "href", "data:{};base64,{}".format( mimetype, base64.b64encode(data.getvalue()).decode("ascii")), ) element.setAttribute("download", f"plot.{format}") element.style.display = "none" document.body.appendChild(element) element.click() document.body.removeChild(element)
def create_root_element(self): # Designed to be overridden by subclasses for use in contexts other # than iodide. from js import iodide if iodide is not None: return iodide.output.element('div') else: return document.createElement('div')
def create_root_element(self): # Designed to be overridden by subclasses for use in contexts other # than iodide. try: from js import iodide return iodide.output.element('div') except ImportError: return document.createElement('div')
def save_cur_pose_func(self): print_div('Saving to "Saved Poses" list..<br>') global d_q # Get the current joint angles in rad ndarray # Convert them into degrees for text view joints_text = "" for i in d_q: joints_text += "%.2f," % (np.rad2deg(i)) joints_text = joints_text[:-1] # Delete the last comma # Add the current joint angles to the saved poses list element_id = "saved_poses_list" poses_list = document.getElementById(element_id) option = document.createElement("option") option.text = joints_text poses_list.add(option)
async def export_data(self): data = {} for db_name in ['recipes', 'plans', 'groceries']: all_docs = await PromiseProxy(PouchDB.new(db_name).allDocs({'include_docs': True})) data[db_name] = [row.doc for row in all_docs.rows] blob = Blob.new([JSON.stringify(data)], {'type': 'application/json'}) print('blob made', blob) url = URL.createObjectURL(blob) print('made url', url) link = document.createElement('a') link.setAttribute('href', url) link.setAttribute('download', 'nutrition_export.json') document.body.appendChild(link) link.click() link.remove() URL.revokeObjectURL(url)
async def async_save_cur_pose_func(): # Get the current joint angles as ndarray and str # _, joints_text = await update_joint_info() # Current Joint angles in radian ndarray, N x 1 and str joints_text = await update_joint_info() # Current Joint angles in radian ndarray, N x 1 and str joints_text = joints_text[:-1] # Delete the last comma # Add the current joint angles to the saved poses list on web browser UI element_id = "saved_poses_list" poses_list = document.getElementById(element_id) option = document.createElement("option") option.text = joints_text poses_list.add(option) # Save the cur pose to plug in as well global plugin_savePlayback await plugin_savePlayback.async_save_cur_pose(None)
def download(self, format, mimetype): # Creates a temporary `a` element with a URL containing the image # content, and then virtually clicks it. Kind of magical, but it # works... element = document.createElement('a') data = io.BytesIO() try: self.canvas.figure.savefig(data, format=format) except Exception as e: raise element.setAttribute('href', 'data:{};base64,{}'.format( mimetype, base64.b64encode(data.getvalue()).decode('ascii'))) element.setAttribute('download', 'plot.{}'.format(format)) element.style.display = 'none' document.body.appendChild(element) element.click() document.body.removeChild(element)
async def async_create_available_cams_list(self): print_div('Creating available cameras options..<br>') # # Get ref to the html element # element_id = "available_cams" # self.available_cams_list = document.getElementById(element_id) self.webcam_names = await self.c_host.async_get_WebcamNames( None ) # string{int32} i.e. a map (dictionary) of strings keyed by an integer. print_div(str(self.webcam_names) + "<br>") # str(self.webcam_names) --> {0:'Right'} for key in self.webcam_names: # print_div(str(self.webcam_names[key]) + "<br>") # --> Right # Add the current joint angles to the available_cams list option = document.createElement("option") option.text = str(key) + ":" + str(self.webcam_names[key]) self.available_cams_list.add(option)
def draw_image(self, gc, x, y, im, transform=None): im = np.flipud(im) h, w, d = im.shape y = self.ctx.height - y - h im = np.ravel(np.uint8(np.reshape(im, (h * w * d, -1)))).tobytes() pixels_proxy = create_proxy(im) pixels_buf = pixels_proxy.getBuffer("u8clamped") img_data = ImageData.new(pixels_buf.data, w, h) self.ctx.save() in_memory_canvas = document.createElement("canvas") in_memory_canvas.width = w in_memory_canvas.height = h in_memory_canvas_context = in_memory_canvas.getContext("2d") in_memory_canvas_context.putImageData(img_data, 0, 0) self.ctx.drawImage(in_memory_canvas, x, y, w, h) self.ctx.restore() pixels_proxy.destroy() pixels_buf.release()
def __init__(self, root: Type[Component], selector: str) -> None: # Gather all components that are defined in the global space self.components = { component.tag: component for component in list([ value for value in globals().values() if isinstance(value, type) and issubclass(value, Component) and value.__name__ != "Component" ]) } # Gather all the CSS self.css = [] for component in self.components.values(): if component.css != "": # Scope the CSS by prefixing it with the component tag css = re.sub( r"([^\r\n,{}\s]+)(,(?=[^}]*{)|\s*{)", f"{component.tag} \\1 {{", component.css, ) lines = list( [line for line in css.split("\n") if line.rstrip() != ""]) self.css.append("\n".join(lines)) # Add the CSS to the head of the document styleElement = document.createElement("style") styleElement.type = "text/css" styleElement.innerHTML = "\n".join(self.css) document.head.appendChild(styleElement) # Create the root component self.root = root(dom=self) self.previous_tree = None self.state = State(dom=self) # Find the root element in the document self.element = document.querySelector(selector) # Render the DOM, starting from the root component self.render()
def write(element_id, value, append=False, exec_id=0): """Writes value to the element with id "element_id""" console.log(f"APPENDING: {append} ==> {element_id} --> {value}") if append: child = document.createElement('div'); element = document.querySelector(f'#{element_id}'); if not element: return exec_id = exec_id or element.childElementCount + 1 element_id = child.id = f"{element_id}-{exec_id}"; element.appendChild(child); element = document.getElementById(element_id) html, mime_type = format_mime(value) if mime_type in ('application/javascript', 'text/html'): scriptEl = document.createRange().createContextualFragment(html) element.appendChild(scriptEl) else: element.innerHTML = html
def show(self): # If we've already shown this canvas elsewhere, don't create a new one, # just reuse it and scroll to the existing one. existing = self.get_element('') if existing is not None: self.draw_idle() existing.scrollIntoView() return # Disable the right-click context menu. # Doesn't work in all browsers. def ignore(event): event.preventDefault() return False window.addEventListener('contextmenu', ignore) # Create the main canvas and determine the physical to logical pixel # ratio canvas = document.createElement('canvas') context = canvas.getContext('2d') self._ratio = self.get_dpi_ratio(context) width, height = self.get_width_height() width *= self._ratio height *= self._ratio div = self.create_root_element() div.setAttribute('style', 'width: {}px'.format(width / self._ratio)) div.id = self._id # The top bar top = document.createElement('div') top.id = self._id + 'top' top.setAttribute('style', 'font-weight: bold; text-align: center') top.textContent = self._title div.appendChild(top) # A div containing two canvases stacked on top of one another: # - The bottom for rendering matplotlib content # - The top for rendering interactive elements, such as the zoom # rubberband canvas_div = document.createElement('div') canvas_div.setAttribute('style', 'position: relative') canvas.id = self._id + 'canvas' canvas.setAttribute('width', width) canvas.setAttribute('height', height) canvas.setAttribute( 'style', 'left: 0; top: 0; z-index: 0; outline: 0;' + 'width: {}px; height: {}px'.format( width / self._ratio, height / self._ratio) ) canvas_div.appendChild(canvas) rubberband = document.createElement('canvas') rubberband.id = self._id + 'rubberband' rubberband.setAttribute('width', width) rubberband.setAttribute('height', height) rubberband.setAttribute( 'style', 'position: absolute; left: 0; top: 0; z-index: 0; outline: 0;' + 'width: {}px; height: {}px'.format( width / self._ratio, height / self._ratio) ) # Canvas must have a "tabindex" attr in order to receive keyboard events rubberband.setAttribute('tabindex', '0') # Event handlers are added to the canvas "on top", even though most of the # activity happens in the canvas below. rubberband.addEventListener('mousemove', self.onmousemove) rubberband.addEventListener('mouseup', self.onmouseup) rubberband.addEventListener('mousedown', self.onmousedown) rubberband.addEventListener('mouseenter', self.onmouseenter) rubberband.addEventListener('mouseleave', self.onmouseleave) rubberband.addEventListener('keyup', self.onkeyup) rubberband.addEventListener('keydown', self.onkeydown) context = rubberband.getContext('2d') context.strokeStyle = '#000000'; context.setLineDash([2, 2]) canvas_div.appendChild(rubberband) div.appendChild(canvas_div) # The bottom bar, with toolbar and message display bottom = document.createElement('div') toolbar = self.toolbar.get_element() bottom.appendChild(toolbar) message = document.createElement('div') message.id = self._id + 'message' message.setAttribute('style', 'min-height: 1.5em') bottom.appendChild(message) div.appendChild(bottom) self.draw()
global pen, lastPoint pen = True lastPoint = (e.offsetX, e.offsetY) def onmouseup(e): global pen pen = False canvas.addEventListener("mousemove", onmousemove) canvas.addEventListener("mousedown", onmousedown) canvas.addEventListener("mouseup", onmouseup) # Colors div = doc.getElementById("colors") colors = ["#F4908E", "#F2F097", "#88B0DC", "#F7B5D1", "#53C4AF", "#FDE38C"] for c in colors: node = doc.createElement("div") node.setAttribute("class", "color") node.setAttribute("id", c) node.setAttribute("style", f"background-color: {c}") def setColor(e): ctx.strokeStyle = e.target.id node.addEventListener("click", setColor) div.appendChild(node)
def create_root_element(self): root_element = document.createElement("div") document.body.appendChild(root_element) return root_element
def add_spacer(): span = document.createElement('span') span.style.minWidth = '16px' span.textContent = '\u00a0' div.appendChild(span)
def add_spacer(): span = document.createElement("span") span.style.minWidth = "16px" span.textContent = "\u00a0" div.appendChild(span)
def show(self): # If we've already shown this canvas elsewhere, don't create a new one, # just reuse it and scroll to the existing one. existing = self.get_element("") if existing is not None: self.draw_idle() existing.scrollIntoView() return # Disable the right-click context menu. # Doesn't work in all browsers. def ignore(event): event.preventDefault() return False # Create the main canvas and determine the physical to logical pixel # ratio canvas = document.createElement("canvas") context = canvas.getContext("2d") self._ratio = self.get_dpi_ratio(context) width, height = self.get_width_height() width *= self._ratio height *= self._ratio div = self.create_root_element() div.addEventListener("contextmenu", ignore) div.setAttribute( "style", "margin: 0 auto; text-align: center;" + f"width: {width / self._ratio}px", ) div.id = self._id # The top bar top = document.createElement("div") top.id = self._id + "top" top.setAttribute("style", "font-weight: bold; text-align: center") top.textContent = self._title div.appendChild(top) # A div containing two canvases stacked on top of one another: # - The bottom for rendering matplotlib content # - The top for rendering interactive elements, such as the zoom # rubberband canvas_div = document.createElement("div") canvas_div.setAttribute("style", "position: relative") canvas.id = self._id + "canvas" canvas.setAttribute("width", width) canvas.setAttribute("height", height) canvas.setAttribute( "style", "left: 0; top: 0; z-index: 0; outline: 0;" + "width: {}px; height: {}px".format(width / self._ratio, height / self._ratio), ) canvas_div.appendChild(canvas) rubberband = document.createElement("canvas") rubberband.id = self._id + "rubberband" rubberband.setAttribute("width", width) rubberband.setAttribute("height", height) rubberband.setAttribute( "style", "position: absolute; left: 0; top: 0; z-index: 0; " + "outline: 0; width: {}px; height: {}px".format( width / self._ratio, height / self._ratio), ) # Canvas must have a "tabindex" attr in order to receive keyboard # events rubberband.setAttribute("tabindex", "0") # Event handlers are added to the canvas "on top", even though most of # the activity happens in the canvas below. rubberband.addEventListener("mousemove", self.onmousemove) rubberband.addEventListener("mouseup", self.onmouseup) rubberband.addEventListener("mousedown", self.onmousedown) rubberband.addEventListener("mouseenter", self.onmouseenter) rubberband.addEventListener("mouseleave", self.onmouseleave) rubberband.addEventListener("keyup", self.onkeyup) rubberband.addEventListener("keydown", self.onkeydown) context = rubberband.getContext("2d") context.strokeStyle = "#000000" context.setLineDash([2, 2]) canvas_div.appendChild(rubberband) div.appendChild(canvas_div) # The bottom bar, with toolbar and message display bottom = document.createElement("div") toolbar = self.toolbar.get_element() bottom.appendChild(toolbar) message = document.createElement("div") message.id = self._id + "message" message.setAttribute("style", "min-height: 1.5em") bottom.appendChild(message) div.appendChild(bottom) self.draw()
def create_root_element(self): # Designed to be overridden by subclasses return document.createElement("div")