def get_abstract_form(self): form_action = "/hsapi/_internal/{}/update-reftimeseries-abstract/" form_action = form_action.format(self.logical_file.id) root_div = div(cls="col-xs-12") # if json file contains abstract then we don't need this form since abstract can't be # edited in that case at the aggregation level if self.has_abstract_in_json: return with root_div: with form(action=form_action, id="filetype-abstract", method="post", enctype="multipart/form-data"): div("{% csrf_token %}") with div(cls="form-group"): with div(cls="control-group"): legend('Abstract') with div(cls="controls"): abstract = "" if self.abstract: abstract = self.abstract textarea(abstract, cls="form-control input-sm textinput textInput", id="file_abstract", cols=40, rows=5, name="abstract") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 col-md-2 col-xs-6"): button("Save changes", cls="btn btn-primary pull-right btn-form-submit", style="display: none;", type="button") return root_div
def open_html_doc(name, letter=None): html_doc = dominate.document(title=u"מילון הראיה") html_doc['dir'] = 'rtl' with html_doc.head: with tags.meta(): tags.attr(charset="utf-8") with tags.meta(): tags.attr(name="viewport", content="width=device-width, initial-scale=1") tags.script(src="jquery/dist/jquery.min.js") tags.link(rel='stylesheet', href='bootstrap-3.3.6-dist/css/bootstrap.min.css') tags.link(rel='stylesheet', href='style.css') tags.script(src="bootstrap-3.3.6-dist/js/bootstrap.min.js") tags.link(rel='stylesheet', href="bootstrap-rtl-3.3.4/dist/css/bootstrap-rtl.css") tags.link(rel='stylesheet', href='html_demos-gh-pages/footnotes.css') tags.script(src="milon.js") tags.script(src="html_demos-gh-pages/footnotes.js") tags.script(src="subjects_db.json") html_doc.footnote_ids_of_this_html_doc = [] html_doc.name = name if letter: html_doc.letter = letter html_doc.section = html_docs_l[-1].section else: html_doc.section = name html_doc.index = len(html_docs_l) + 1 with html_doc.body: with tags.div(): tags.attr(cls="container-fluid") # TODO: call page_loaded to update saved URL also in other links tags.script("page_loaded('%s.html')" % html_doc.index) with tags.div(): tags.attr(cls="fixed_top_left", id="menu_bar") with tags.div(): with tags.button(type="button"): tags.attr(id="search_icon_button", type="button", cls="btn btn-default") with tags.span(): tags.attr(cls="glyphicon glyphicon-search") with tags.span(): tags.attr(cls="dropdown") with tags.button(type="button", cls="btn btn-primary") as b: tags.attr(href="#") #, cls="dropdown-toggle") with tags.span(): tags.attr(cls="glyphicon glyphicon-menu-hamburger") # b['data-toggle'] = "dropdown" with tags.ul(): tags.attr(cls="dropdown-menu dropdown-menu-left scrollable-menu") return html_doc
def get_update_netcdf_file_html_form(self): form_action = "/hsapi/_internal/{}/update-netcdf-file/".format(self.logical_file.id) style = "display:none;" self.refresh_from_db() if self.is_dirty: style = "margin-bottom:15px" root_div = div(id="div-netcdf-file-update", cls="row", style=style) with root_div: with div(cls="col-sm-12"): with div(cls="alert alert-warning alert-dismissible", role="alert"): div("NetCDF file needs to be synced with metadata changes.", cls='space-bottom') input(id="metadata-dirty", type="hidden", value=self.is_dirty) with form(action=form_action, method="post", id="update-netcdf-file"): button("Update NetCDF File", type="button", cls="btn btn-primary", id="id-update-netcdf-file") return root_div
def get_update_netcdf_file_html_form(self): form_action = "/hsapi/_internal/netcdf_update/{}/".\ format(self.resource.short_id) style = "display:none;" root_div = div(id="netcdf-file-update", cls="space-bottom", style=style) with root_div: with div(cls="col-sm-12"): with div(cls="alert alert-warning alert-dismissible", role="alert"): div("NetCDF file needs to be synced with metadata changes.", cls='space-bottom') input(id="metadata-dirty", type="hidden", value="{{ cm.metadata.is_dirty }}") with form(action=form_action, method="post", id="update-netcdf-file",): div('{% csrf_token %}') button("Update NetCDF File", type="submit", cls="btn btn-primary", id="id-update-netcdf-file", ) return root_div
def visit_Navbar(self, node): # create a navbar id that is somewhat fixed, but do not leak any # information about memory contents to the outside node_id = self.id or sha1(str(id(node)).encode()).hexdigest() root = tags.nav() if self.html5 else tags.div(role='navigation') root['class'] = 'navbar navbar-default' cont = root.add(tags.div(_class='container-fluid')) # collapse button header = cont.add(tags.div(_class='navbar-header')) btn = header.add(tags.button()) btn['type'] = 'button' btn['class'] = 'navbar-toggle collapsed' btn['data-toggle'] = 'collapse' btn['data-target'] = '#' + node_id btn['aria-expanded'] = 'false' btn['aria-controls'] = 'navbar' btn.add(tags.span('Toggle navigation', _class='sr-only')) btn.add(tags.span(_class='icon-bar')) btn.add(tags.span(_class='icon-bar')) btn.add(tags.span(_class='icon-bar')) # title may also have a 'get_url()' method, in which case we render # a brand-link if node.title is not None: if hasattr(node.title, 'get_url'): header.add(tags.a(node.title.text, _class='navbar-brand', href=node.title.get_url())) else: header.add(tags.span(node.title, _class='navbar-brand')) bar = cont.add(tags.div( _class='navbar-collapse collapse', id=node_id, )) bar_list = bar.add(tags.ul(_class='nav navbar-nav')) bar_list_right = bar.add(tags.ul(_class='nav navbar-nav navbar-right')) to_right = False for item in node.items: if isinstance(item, SeparatorAlign): to_right = True continue if not to_right: bar_list.add(self.visit(item)) else: bar_list_right.add(self.visit(item)) return root
def visit_Navbar(self, node): # create a navbar id that is somewhat fixed, but do not leak any # information about memory contents to the outside node_id = self.id or sha1(str(id(node)).encode()).hexdigest() root = tags.nav(_class='navbar') if self.html5 else tags.div(role='navigation', _class='navbar') if node.kwargs.get('class_'): root['class'] += (' ' + node.kwargs['class_']) if node.kwargs.get('id'): root['id'] = node.kwargs['id'] # title may also have a 'get_url()' method, in which case we render # a brand-link if node.title is not None: if hasattr(node.title, 'img'): root.add(self.visit(node.title)) elif hasattr(node.title, 'get_url'): root.add(tags.a(node.title.text, _class='navbar-brand', href=node.title.get_url())) else: root.add(tags.span(node.title, _class='navbar-brand')) # collapse button if node.kwargs.get('responsive') in (None, True): btn = root.add(tags.button()) btn['type'] = 'button' btn['class'] = 'navbar-toggler navbar-toggler-right' btn['data-toggle'] = 'collapse' btn['data-target'] = '#' + node_id btn['aria-expanded'] = 'false' btn['aria-controls'] = 'navbar' btn['aria-label'] = 'Toggle navigation' btn.add(tags.span(_class='navbar-toggler-icon')) bar = root.add(tags.div( _class='collapse navbar-collapse', id=node_id, )) item_list = bar.add(tags.div(_class='navbar-nav mr-auto')) item_list_right = bar.add(tags.div(_class='navbar-nav')) for item in node.items: if item.kwargs.get('align') == 'right': item_list_right.add(self.visit(item)) else: item_list.add(self.visit(item)) return root
def visit_Navbar(self, node): # create a navbar id that is somewhat fixed, but do not leak any # information about memory contents to the outside node_id = self.id or sha1(str(id(node)).encode()).hexdigest() root = tags.nav() if self.html5 else tags.div(role="navigation") root["class"] = "navbar navbar-default" cont = root.add(tags.div(_class="container-fluid")) # collapse button header = cont.add(tags.div(_class="navbar-header")) btn = header.add(tags.button()) btn["type"] = "button" btn["class"] = "navbar-toggle collapsed" btn["data-toggle"] = "collapse" btn["data-target"] = "#" + node_id btn["aria-expanded"] = "false" btn["aria-controls"] = "navbar" btn.add(tags.span("Toggle navigation", _class="sr-only")) btn.add(tags.span(_class="icon-bar")) btn.add(tags.span(_class="icon-bar")) btn.add(tags.span(_class="icon-bar")) # title may also have a 'get_url()' method, in which case we render # a brand-link if node.title is not None: if hasattr(node.title, "get_url"): header.add(tags.a(node.title.text, _class="navbar-brand", href=node.title.get_url())) else: header.add(tags.span(node.title, _class="navbar-brand")) bar = cont.add(tags.div(_class="navbar-collapse collapse", id=node_id)) bar_list = bar.add(tags.ul(_class="nav navbar-nav")) for item in node.items: bar_list.add(self.visit(item)) return root
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True): """overrides the base class function""" root_div = div() with root_div: div("{% load crispy_forms_tags %}") if self.has_title_in_json: self.get_dataset_name_html() else: self.get_dataset_name_form() if self.has_keywords_in_json: self.get_keywords_html() else: self.get_keywords_html_form() self.get_extra_metadata_html_form() abstract_div = div(cls="col-xs-12 content-block") with abstract_div: if self.has_abstract_in_json: legend("Abstract") p(self.abstract) else: self.get_abstract_form() if self.file_version: file_ver_div = div(cls="col-xs-12 content-block") with file_ver_div: legend("File Version") p(self.file_version) if self.symbol: symbol_div = div(cls="col-xs-12 content-block") with symbol_div: legend("Symbol") if self.symbol.startswith('http'): with p(): a(self.symbol, href=self.symbol, target="_blank") else: p(self.symbol) self.get_temporal_coverage_html_form() with div(cls="col-lg-6 col-xs-12"): with form(id="id-coverage-spatial-filetype", action="{{ spatial_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy spatial_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;", onclick="metadata_update_ajax_submit(" "'id-coverage-spatial-filetype');") self.get_ts_series_html() self.get_json_file_data_html() template = Template(root_div.render()) context_dict = dict() temp_cov_form = self.get_temporal_coverage_form(allow_edit=False) spatial_cov_form = self.get_spatial_coverage_form() context_dict["temp_form"] = temp_cov_form context_dict["spatial_form"] = spatial_cov_form context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def _get_add_key_value_modal_form(self): form_action = "/hsapi/_internal/{0}/{1}/update-file-keyvalue-metadata/" form_action = form_action.format(self.logical_file.__class__.__name__, self.logical_file.id) modal_div = div(cls="modal fade", id="add-keyvalue-filetype-modal", tabindex="-1", role="dialog", aria_labelledby="add-key-value-metadata", aria_hidden="true") with modal_div: with div(cls="modal-dialog", role="document"): with div(cls="modal-content"): with form(action=form_action, id="add-keyvalue-filetype-metadata", method="post", enctype="multipart/form-data"): div("{% csrf_token %}") with div(cls="modal-header"): button("x", type="button", cls="close", data_dismiss="modal", aria_hidden="true") h4("Add Key/Value Metadata", cls="modal-title", id="add-key-value-metadata") with div(cls="modal-body"): with div(cls="form-group"): with div(cls="control-group"): label("Key", cls="control-label requiredField", fr="file_extra_meta_name") with div(cls="controls"): input( cls= "form-control input-sm textinput textInput", id="file_extra_meta_name", maxlength="100", name="name", type="text") with div(cls="control-group"): label("Value", cls="control-label requiredField", fr="file_extra_meta_value") with div(cls="controls"): textarea( cls= "form-control input-sm textarea", cols="40", rows="10", id="file_extra_meta_value", style="resize: vertical;", name="value", type="text") with div(cls="modal-footer"): button("Cancel", type="button", cls="btn btn-default", data_dismiss="modal") button( "OK", type="button", cls="btn btn-primary", id="btn-confirm-add-metadata") # TODO: TESTING return modal_div
def _get_delete_key_value_modal_forms(self): form_action = "/hsapi/_internal/{0}/{1}/delete-file-keyvalue-metadata/" form_action = form_action.format(self.logical_file.__class__.__name__, self.logical_file.id) counter = 0 root_div = div(id="delete-keyvalue-filetype-modals") with root_div: for k, v in self.extra_metadata.iteritems(): counter += 1 modal_div = div( cls="modal fade", id="delete-keyvalue-filetype-modal-{}".format(counter), tabindex="-1", role="dialog", aria_labelledby="delete-key-value-metadata", aria_hidden="true") with modal_div: with div(cls="modal-dialog", role="document"): with div(cls="modal-content"): form_id = "delete-keyvalue-filetype-metadata-{}".format( counter) with form(action=form_action, id=form_id, method="post", enctype="multipart/form-data"): div("{% csrf_token %}") with div(cls="modal-header"): button("x", type="button", cls="close", data_dismiss="modal", aria_hidden="true") h4("Confirm to Delete Key/Value Metadata", cls="modal-title", id="delete-key-value-metadata") with div(cls="modal-body"): with div(cls="form-group"): with div(cls="control-group"): label( "Key", cls= "control-label requiredField", fr="file_extra_meta_name") with div(cls="controls"): input( cls= "form-control input-sm textinput " "textInput", value=k, id="file_extra_meta_key", maxlength="100", name="key", type="text", readonly="readonly") with div(cls="control-group"): label( "Value", cls= "control-label requiredField", fr="file_extra_meta_value") with div(cls="controls"): textarea( v, cls= "form-control input-sm textarea", cols="40", rows="10", id="file_extra_meta_value", style="resize: vertical;", name="value", type="text", readonly="readonly") with div(cls="modal-footer"): button("Cancel", type="button", cls="btn btn-default", data_dismiss="modal") button("Delete", type="button", cls="btn btn-danger", id="btn-delete-key-value" ) # TODO: TESTING return root_div
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True, **kwargs): """overrides the base class function to generate html needed for metadata editing""" root_div = div("{% load crispy_forms_tags %}") with root_div: super(GeoRasterFileMetaData, self).get_html_forms() with div(id="spatial-coverage-filetype"): with form(id="id-spatial-coverage-file-type", cls='hs-coordinates-picker', data_coordinates_type="point", action="{{ coverage_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy coverage_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;") div("{% crispy orig_coverage_form %}", cls="content-block") div("{% crispy cellinfo_form %}", cls='content-block') with div(id="variables", cls="content-block"): div("{% for form in bandinfo_formset_forms %}") with form(id="{{ form.form_id }}", action="{{ form.action }}", method="post", enctype="multipart/form-data", cls='well'): div("{% crispy form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button( "Save changes", type="button", cls= "btn btn-primary pull-right btn-form-submit", style="display: none;") div("{% endfor %}") template = Template(root_div.render()) context_dict = dict() context_dict["orig_coverage_form"] = self.get_original_coverage_form() context_dict["cellinfo_form"] = self.get_cellinfo_form() temp_cov_form = self.get_temporal_coverage_form() update_action = "/hsapi/_internal/GeoRasterLogicalFile/{0}/{1}/{2}/update-file-metadata/" create_action = "/hsapi/_internal/GeoRasterLogicalFile/{0}/{1}/add-file-metadata/" spatial_cov_form = self.get_spatial_coverage_form(allow_edit=True) if self.spatial_coverage: form_action = update_action.format(self.logical_file.id, "coverage", self.spatial_coverage.id) else: form_action = create_action.format(self.logical_file.id, "coverage") spatial_cov_form.action = form_action if self.temporal_coverage: form_action = update_action.format(self.logical_file.id, "coverage", self.temporal_coverage.id) temp_cov_form.action = form_action else: form_action = create_action.format(self.logical_file.id, "coverage") temp_cov_form.action = form_action context_dict["coverage_form"] = spatial_cov_form context_dict["temp_form"] = temp_cov_form context_dict["bandinfo_formset_forms"] = self.get_bandinfo_formset( ).forms context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def default_button(): """Creates a Hide All button for every show/hide div block created""" tags.button("Default", onclick="defaultAll(" + __get_js_array(shown) + ", " + __get_js_array(hidden) + ")")
class_="hello", # some_invalid_tag="hello", custom={"foo": "bar"}, disabled=True, events=tags.Events(click="alert('Hello world');") )) # Commented-out line gives: # TypeError: __init__() got an unexpected keyword argument 'some_invalid_tag' """ def print_foo(): print( tags.button( "Hello world", class_="hello", # some_invalid_tag="hello", events=tags.Events(click="alert('Hello world');"))) print_foo() print( dom.button("Hello world", cls="hello", some_invalid_tag="hello", onclick="alert('Hello world');"))
def visit_SubmitField(self, node): button = tags.button(node.label.text, _class='btn btn-secondary', type='submit') return button
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True, **kwargs): """overrides the base class function""" root_div = div("{% load crispy_forms_tags %}") with root_div: self.get_update_netcdf_file_html_form() super(NetCDFFileMetaData, self).get_html_forms() with div(cls="row"): with div(cls="col-lg-6 col-xs-12", id="original-coverage-filetype"): with form(id="id-origcoverage-file-type", action="{{ orig_coverage_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy orig_coverage_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;") with div(cls="col-lg-6 col-xs-12", id="spatial-coverage-filetype"): with form(id="id-spatial-coverage-file-type", action="{{ spatial_coverage_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy spatial_coverage_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;") with div(cls="pull-left col-sm-12"): # id has to be variables to get the vertical scrollbar with div(cls="well", id="variables"): with div(cls="row"): with div("{% for form in variable_formset_forms %}"): with div(cls="col-sm-6 col-xs-12"): with form(id="{{ form.form_id }}", action="{{ form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy form %}") with div(cls="row", style="margin-top:10px;"): with div( cls= "col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button( "Save changes", type="button", cls= "btn btn-primary pull-right", style="display: none;") div("{% endfor %}") self.get_ncdump_html() template = Template(root_div.render()) temp_cov_form = self.get_temporal_coverage_form() update_action = "/hsapi/_internal/NetCDFLogicalFile/{0}/{1}/{2}/update-file-metadata/" create_action = "/hsapi/_internal/NetCDFLogicalFile/{0}/{1}/add-file-metadata/" if self.temporal_coverage: temp_action = update_action.format(self.logical_file.id, "coverage", self.temporal_coverage.id) else: temp_action = create_action.format(self.logical_file.id, "coverage") temp_cov_form.action = temp_action orig_cov_form = self.get_original_coverage_form() if self.originalCoverage: temp_action = update_action.format(self.logical_file.id, "originalcoverage", self.originalCoverage.id) else: temp_action = create_action.format(self.logical_file.id, "originalcoverage") orig_cov_form.action = temp_action spatial_cov_form = self.get_spatial_coverage_form(allow_edit=True) if self.spatial_coverage: temp_action = update_action.format(self.logical_file.id, "coverage", self.spatial_coverage.id) else: temp_action = create_action.format(self.logical_file.id, "coverage") spatial_cov_form.action = temp_action context_dict = dict() context_dict["temp_form"] = temp_cov_form context_dict["orig_coverage_form"] = orig_cov_form context_dict["spatial_coverage_form"] = spatial_cov_form context_dict["variable_formset_forms"] = self.get_variable_formset( ).forms context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True): """overrides the base class function""" root_div = div("{% load crispy_forms_tags %}") with root_div: super(GenericFileMetaDataMixin, self).get_html_forms() with div(): with form(id="id-coverage-spatial-filetype", action="{{ spatial_form.action }}", method="post", enctype="multipart/form-data", cls='hs-coordinates-picker', data_coordinates_type="point"): div("{% crispy spatial_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right btn-form-submit", style="display: none;") # TODO: TESTING # for aggregation that contains other aggregations with spatial data, # show option to update spatial coverage from contained aggregations if self.logical_file.has_children_spatial_data: with div(style="margin-top:20px;"): with div(): button("Set spatial coverage from folder contents", type="button", cls="btn btn-primary pull-right", id="btn-update-aggregation-spatial-coverage") template = Template(root_div.render()) context_dict = dict() temp_cov_form = self.get_temporal_coverage_form() spatial_cov_form = self.get_spatial_coverage_form(allow_edit=True) update_action = "/hsapi/_internal/{0}/{1}/{2}/{3}/update-file-metadata/" create_action = "/hsapi/_internal/{0}/{1}/{2}/add-file-metadata/" element_name = "coverage" logical_file_class_name = self.logical_file.__class__.__name__ if self.temporal_coverage or self.spatial_coverage: if self.temporal_coverage: temp_action = update_action.format(logical_file_class_name, self.logical_file.id, element_name, self.temporal_coverage.id) temp_cov_form.action = temp_action else: temp_action = create_action.format(logical_file_class_name, self.logical_file.id, element_name) temp_cov_form.action = temp_action if self.spatial_coverage: spatial_action = update_action.format(logical_file_class_name, self.logical_file.id, element_name, self.spatial_coverage.id) spatial_cov_form.action = spatial_action else: spatial_action = create_action.format(logical_file_class_name, self.logical_file.id, element_name) spatial_cov_form.action = spatial_action else: action = create_action.format(logical_file_class_name, self.logical_file.id, element_name) temp_cov_form.action = action spatial_cov_form.action = action context_dict["temp_form"] = temp_cov_form context_dict["spatial_form"] = spatial_cov_form context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True): """overrides the base class function""" root_div = div("{% load crispy_forms_tags %}") with root_div: super(GenericFileMetaDataMixin, self).get_html_forms() with div(): with form(id="id-coverage-spatial-filetype", action="{{ spatial_form.action }}", method="post", enctype="multipart/form-data", cls='hs-coordinates-picker', data_coordinates_type="point"): div("{% crispy spatial_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button( "Save changes", type="button", cls= "btn btn-primary pull-right btn-form-submit", style="display: none;") # TODO: TESTING # for aggregation that contains other aggregations with spatial data, # show option to update spatial coverage from contained aggregations if self.logical_file.has_children_spatial_data: with div(style="margin-top:20px;"): with div(): button( "Set spatial coverage from folder contents", type="button", cls="btn btn-primary pull-right", id="btn-update-aggregation-spatial-coverage") template = Template(root_div.render()) context_dict = dict() temp_cov_form = self.get_temporal_coverage_form() spatial_cov_form = self.get_spatial_coverage_form(allow_edit=True) update_action = "/hsapi/_internal/{0}/{1}/{2}/{3}/update-file-metadata/" create_action = "/hsapi/_internal/{0}/{1}/{2}/add-file-metadata/" element_name = "coverage" logical_file_class_name = self.logical_file.__class__.__name__ if self.temporal_coverage or self.spatial_coverage: if self.temporal_coverage: temp_action = update_action.format(logical_file_class_name, self.logical_file.id, element_name, self.temporal_coverage.id) temp_cov_form.action = temp_action else: temp_action = create_action.format(logical_file_class_name, self.logical_file.id, element_name) temp_cov_form.action = temp_action if self.spatial_coverage: spatial_action = update_action.format(logical_file_class_name, self.logical_file.id, element_name, self.spatial_coverage.id) spatial_cov_form.action = spatial_action else: spatial_action = create_action.format(logical_file_class_name, self.logical_file.id, element_name) spatial_cov_form.action = spatial_action else: action = create_action.format(logical_file_class_name, self.logical_file.id, element_name) temp_cov_form.action = action spatial_cov_form.action = action context_dict["temp_form"] = temp_cov_form context_dict["spatial_form"] = spatial_cov_form context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def make_region_html(region, args): """Write region-specific HTML page.""" latest = max( m.frame.index.max() for m in region.metrics["covid"].values() if m.emphasis >= 0 ) doc = dominate.document(title=f"{region.name} COVID-19 ({latest.date()})") doc_url = urls.region_page(region) def doc_link(url): return urls.link(doc_url, url) with doc.head: style.add_head_style(doc_url) with doc.body: tags.attr(id="map_key_target", tabindex="-1") with tags.h1(): def write_breadcrumbs(r): if r is not None: write_breadcrumbs(r.parent) tags.a(r.short_name, href=doc_link(urls.region_page(r))) util.text(" » ") write_breadcrumbs(region.parent) util.text(region.name) with tags.div(): pop = region.totals["population"] vax = region.totals.get("vaccinated", 0) pos = region.totals.get("positives", 0) dead = region.totals.get("deaths", 0) nobreak = lambda t: tags.span(t, cls="nobreak") nobreak(f"{pop:,.0f} pop; ") if vax: nobreak(f"{vax:,.0f} ({100 * vax / pop:.2g}%) vacc, ") nobreak(f"{pos:,.0f} ({100 * pos / pop:.2g}%) pos, ") nobreak(f"{dead:,.0f} ({100 * dead / pop:.2g}%) deaths ") nobreak(f"as of {latest.date()}") if urls.has_map(region): with tags.div(cls="graphic"): with tags.video(id="map", preload="auto"): href = urls.link(doc_url, urls.map_video_maybe(region)) tags.source(type="video/webm", src=f"{href}#t=1000") with tags.div(cls="map_controls"): def i(n): return tags.i(cls=f"fas fa-{n}") tags.button(i("pause"), " ", i("play"), " P", id="map_play") tags.button(i("repeat"), " L", id="map_loop") tags.button(i("backward"), " R", id="map_rewind") tags.button(i("step-backward"), " [", id="map_prev") tags.input_(type="range", id="map_slider") tags.button(i("step-forward"), " ]", id="map_next") tags.button(i("forward"), " F", id="map_forward") tags.img(cls="graphic", src=doc_link(urls.chart_image(region))) notables = [p for p in region.policy_changes if p.score] if notables: tags.h2( tags.span("Closing", cls="policy_close"), " and ", tags.span("Reopening", cls="policy_open"), " policy changes", ) with tags.div(cls="policies"): last_date = None for p in notables: date, s = str(p.date.date()), p.score if date != last_date: tags.div(date, cls=f"date") last_date = date tags.div(p.emoji, cls=f"emoji") tags.div( p.text, cls="text" + (" policy_close" if s < 0 else "") + (" policy_open" if s > 0 else "") + (" policy_major" if abs(s) >= 2 else ""), ) subs = [ r for r in region.subregions.values() if r.matches_regex(args.region_regex) ] if subs: sub_pop = sum(s.totals["population"] for s in subs) if len(subs) >= 10 and sub_pop > 0.9 * region.totals["population"]: def pop(r): return r.totals.get("population", 0) def pos(r): m = r.metrics["covid"].get("COVID positives / day / 100Kp") return m.frame.value.iloc[-1] * pop(r) if m else 0 tags.h2("Top 5 by population") for s in list(sorted(subs, key=pop, reverse=True))[:5]: make_subregion_html(doc_url, s) tags.h2("Top 5 by new positives") for s in list(sorted(subs, key=pos, reverse=True))[:5]: make_subregion_html(doc_url, s) tags.h2(f'All {"divisions" if region.parent else "countries"}') else: tags.h2("Subdivisions") for s in sorted(subs, key=lambda r: r.name): make_subregion_html(doc_url, s) r = region credits = dict(c for p in r.policy_changes for c in p.credits.items()) for ms in r.metrics.values(): credits.update(c for m in ms.values() for c in m.credits.items()) with tags.p("Sources: ", cls="credits"): for i, (url, text) in enumerate(credits.items()): util.text(", ") if i > 0 else None tags.a(text, href=url) with open(urls.file(args.site_dir, doc_url), "w") as doc_file: doc_file.write(doc.render())
def render_latest(repo: Path, digest, rendered: Path): logger.info('processing %s', repo) rtype = get_result_type(repo) Format = FormatTrait.for_(rtype) Ignore = IgnoreTrait.for_(rtype) import pytz NOW = datetime.now(tz=pytz.utc) name = repo.stem doc = dominate.document( title=f'axol results for {name}, rendered at {fdate(NOW)}') with doc.head: T.style(STYLE) raw_script(JS) T.link( rel='stylesheet', href= "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/codemirror.min.css" ) T.script( src= 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.2/codemirror.js' ) # TODO use min? citems: Iterator[Tuple[datetime, Item]] = chain.from_iterable( ((d, x) for x in zz) for d, zz in digest.changes.items()) # group according to link, so we can display already occuring items along with newer occurences items2: List[Sequence[Tuple[datetime, Item]]] = [ grp for _, grp in group_by_key(citems, key=lambda p: f'{p[1].link}').items() ] # TODO sort within each group? def min_dt(group: Sequence[Tuple[datetime, Item]]) -> datetime: return min(g[0] for g in group) # TODO ok, this is def too many types here... items3: Mapping[datetime, List[Sequence[Tuple[datetime, Item]]]] = group_by_key(items2, key=min_dt) rss = True if rss: # pip3 install feedgen from feedgen.feed import FeedGenerator # type: ignore fg = FeedGenerator() # TODO memorize items? fg.title(name) fg.id('axol/' + name) first = True for d, items in sorted(items3.items()): litems = list(items) logger.info('%s %s: atom, dumping %d items', name, d, len(litems)) if first: logger.info("SKIPPING first batch to prevent RSS bloat") first = False continue for zz in litems: fe = fg.add_entry() # TODO not sure about css? # TODO not sure which date should use? I gues crawling date makes more sense.. _d, z = zz[0] # TODO meh! id_ = z.uid # TODO FIXME!! fe.id(id_) title = Format.title(zz) or '<no title>' # meh fe.title(title) fe.link(href=Format.link(zz)) # TODO not sure if it's a reasonable date to use... fe.published(published=d) fe.author(author={'name': z.user}) # TODO maybe, concat users? ignored = Ignore.ignore_group(zz) if ignored is not None: # TODO not sure if it highlights with read or something? content = ignored else: content = Format.format(zz) # eh, XML was complaining at some non-utf characters content = str(content) # https://stackoverflow.com/a/25920392/706389 make lxml happy... content = re.sub( u'[^\u0020-\uD7FF\u0009\u000A\u000D\uE000-\uFFFD\U00010000-\U0010FFFF]+', '', content) fe.content(content=content, type='CDATA') # fe.updated(updated=NOW) # TODO assemble a summary similar to HTML? # fe.summary() atomfeed = fg.atom_str(pretty=True) # eh, my feed reader (miniflux) can't handle it if it's 'cdata' # not sure which one is right # ugh, that didn't work because escaping desicion is based on CDATA attribute... atomfeed = atomfeed.replace(b'type="CDATA"', b'type="html"') # fe._FeedEntry__atom_content['type'] = 'html' atomdir = rendered / 'atom' atomdir.mkdir(parents=True, exist_ok=True) (atomdir / (name + '.xml')).write_bytes(atomfeed) with doc: with T.div(id='sidebar'): T.label('Blacklisted:', for_='blacklisted') T.div(id='blacklisted') T.textarea(id='blacklist-edit', rows=10) T.button('apply', id='blacklist-apply') odd = True for d, items in sorted(items3.items(), reverse=True): litems = list(items) odd = not odd logger.info('%s %s: dumping %d items', name, d, len(litems)) with T.div(cls='day-changes'): with T.div(): T.b(fdate(d)) T.span(f'{len(litems)} items') with T.div( cls=f'day-changes-inner {"odd" if odd else "even"}'): for i in items: # TODO FIXME use getattr to specialise trait? # TODO FIXME ignore should be at changes collecting stage? ignored = Ignore.ignore_group(i) if ignored is not None: # TODO maybe let format result handle that... not sure T.div(ignored, cls='item ignored') # TODO log maybe? # TODO eh. need to handle in cumulatives... else: fi = Format.format(i) T.div(fi, cls='item') # f*****g hell.. didn't manage to render content inside iframe no matter how I tried.. # with T.iframe(id='blacklist', src=''): # pass # TODO perhaps needs to be iterative... rf = rendered / (name + '.html') with rf.open('w') as fo: fo.write(str(doc)) return rf
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True): """overrides the base class function""" root_div = div() with root_div: div("{% load crispy_forms_tags %}") if self.has_title_in_json: # title is in json file - we don't allow the user to edit title (dataset name) self.get_dataset_name_html() else: # title is not in json file - we allow the user to edit title (dataset name) self.get_dataset_name_form() if self.has_keywords_in_json: self.get_keywords_html() else: self.get_keywords_html_form() self.get_extra_metadata_html_form() abstract_div = div(cls="content-block") with abstract_div: if self.has_abstract_in_json: # abstract is in json file - we don't allow the user to edit abstract legend("Abstract") p(self.abstract) else: # abstract is not in json file - we allow the user to edit abstract self.get_abstract_form() if self.file_version: file_ver_div = div(cls="content-block") with file_ver_div: legend("File Version") p(self.file_version) if self.symbol: symbol_div = div(cls="content-block") with symbol_div: legend("Symbol") if self.symbol.startswith('http'): with p(): a(self.symbol, href=self.symbol, target="_blank") else: p(self.symbol) self.get_temporal_coverage_html_form() with div(cls="content-block"): with form(id="id-coverage-spatial-filetype", action="{{ spatial_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy spatial_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;", onclick="metadata_update_ajax_submit(" "'id-coverage-spatial-filetype');") self.get_ts_series_html() self.get_json_file_data_html() template = Template(root_div.render()) context_dict = dict() temp_cov_form = self.get_temporal_coverage_form(allow_edit=False) spatial_cov_form = self.get_spatial_coverage_form() context_dict["temp_form"] = temp_cov_form context_dict["spatial_form"] = spatial_cov_form context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def _get_edit_key_value_modal_forms(self): # TODO: See if can use one modal dialog to edit any pair of key/value form_action = "/hsapi/_internal/{0}/{1}/update-file-keyvalue-metadata/" form_action = form_action.format(self.logical_file.__class__.__name__, self.logical_file.id) counter = 0 root_div = div(id="edit-keyvalue-filetype-modals") with root_div: for k, v in self.extra_metadata.iteritems(): counter += 1 modal_div = div( cls="modal fade", id="edit-keyvalue-filetype-modal-{}".format(counter), tabindex="-1", role="dialog", aria_labelledby="edit-key-value-metadata", aria_hidden="true") with modal_div: with div(cls="modal-dialog", role="document"): with div(cls="modal-content"): form_id = "edit-keyvalue-filetype-metadata-{}".format( counter) with form(action=form_action, id=form_id, data_counter="{}".format(counter), method="post", enctype="multipart/form-data"): div("{% csrf_token %}") with div(cls="modal-header"): button("x", type="button", cls="close", data_dismiss="modal", aria_hidden="true") h4("Update Key/Value Metadata", cls="modal-title", id="edit-key-value-metadata") with div(cls="modal-body"): with div(cls="form-group"): with div(cls="control-group"): label( "Key(Original)", cls= "control-label requiredField", fr= "file_extra_meta_key_original") with div(cls="controls"): input( value=k, readonly="readonly", cls= "form-control input-sm textinput " "textInput", id= "file_extra_meta_key_original", maxlength="100", name="key_original", type="text") with div(cls="control-group"): label( "Key", cls= "control-label requiredField", fr="file_extra_meta_key") with div(cls="controls"): input( value=k, cls= "form-control input-sm textinput " "textInput", id="file_extra_meta_key", maxlength="100", name="key", type="text") with div(cls="control-group"): label( "Value", cls= "control-label requiredField", fr="file_extra_meta_value") with div(cls="controls"): textarea( v, cls= "form-control input-sm textarea", cols="40", rows="10", id="file_extra_meta_value", name="value", type="text") with div(cls="modal-footer"): button("Cancel", type="button", cls="btn btn-default", data_dismiss="modal") button("OK", id="btn-confirm-edit-key-value", type="button", cls="btn btn-primary") return root_div
def open_html_doc(name, letter=None): html_doc = dominate.document(title=u"מילון הראיה") html_doc['dir'] = 'rtl' with html_doc.head: with tags.meta(): tags.attr(charset="utf-8") with tags.meta(): tags.attr(name="viewport", content="width=device-width, initial-scale=1") tags.script(src="jquery/dist/jquery.min.js") tags.link(rel='stylesheet', href='bootstrap-3.3.6-dist/css/bootstrap.min.css') tags.link(rel='stylesheet', href='style.css') tags.script(src="bootstrap-3.3.6-dist/js/bootstrap.min.js") tags.link(rel='stylesheet', href="bootstrap-rtl-3.3.4/dist/css/bootstrap-rtl.css") tags.link(rel='stylesheet', href='html_demos-gh-pages/footnotes.css') tags.script(src="milon.js") tags.script(src="html_demos-gh-pages/footnotes.js") tags.script(src="subjects_db.json") html_doc.footnote_ids_of_this_html_doc = [] html_doc.name = name if letter: html_doc.letter = letter html_doc.section = html_docs_l[-1].section else: html_doc.section = name html_doc.index = len(html_docs_l) + 1 with html_doc.body: with tags.div(): tags.attr(cls="container-fluid") # TODO: call page_loaded to update saved URL also in other links tags.script("page_loaded('%s.html')" % html_doc.index) with tags.div(): tags.attr(cls="fixed_top_left", id="menu_bar") with tags.div(): with tags.button(type="button"): tags.attr(id="search_icon_button", type="button", cls="btn btn-default") with tags.span(): tags.attr(cls="glyphicon glyphicon-search") with tags.span(): tags.attr(cls="dropdown") with tags.button(type="button", cls="btn btn-primary") as b: tags.attr(href="#") #, cls="dropdown-toggle") with tags.span(): tags.attr( cls="glyphicon glyphicon-menu-hamburger") # b['data-toggle'] = "dropdown" with tags.ul(): tags.attr( cls= "dropdown-menu dropdown-menu-left scrollable-menu" ) return html_doc
def _to_tag(self): tag = button(_class=self._class) if self.icon: tag.add(self.icon.to_tag()) tag.add(span(self.description)) return tag
contrast = jsonpickle.decode(f.read()) doc = document(title='Comparison of smart cards') with doc.head: if args.exclude_style_and_scripts: tags.link(rel="stylesheet", href="style.css") tags.script(type="text/javascript", src="script.js") else: tags.style(raw(style)) tags.script(raw(script), type="text/javascript") with doc: tags.button("Back to Top", onclick="backToTop()", id="topButton", cls="floatingbutton") intro_div = tags.div(id="intro") with intro_div: tags.h1("Verification of " + contrast.prof_name + " against " + contrast.ref_name) tags.p("Generated on: " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) tags.p("Generated from: " + args.verification_profile) tags.h2("Verification results") tags.h4("Ordered results from tested modules:") worst_contrast_state = ContrastState.MATCH suspicions = 0 with tags.div(id="modules"):
def visit_Navbar(self, node): root = tags.div() root['class'] = 'navbar-fixed-top' node_id = self.id or sha1(str(id(node)).encode()).hexdigest() top = root.add(tags.nav()) top['class'] = 'navbar navbar-default' top['id'] = 'navbar-top' container = top.add(tags.div(_class='container')) header = container.add(tags.div(_class='navbar-header')) button = header.add(tags.button()) button['type'] = 'button' button['class'] = 'navbar-toggle collapsed' button['data-toggle'] = 'collapse' button['data-target'] = '#' + node_id button['aria-expanded'] = 'false' button['aria-controls'] = 'navbar' button.add(tags.span('Toggle navigation', _class='sr-only')) button.add(tags.span(_class='icon-bar')) button.add(tags.span(_class='icon-bar')) button.add(tags.span(_class='icon-bar')) if node.title is not None: if hasattr(node.title, 'get_url'): header.add( tags.a(node.title.text, _class='navbar-brand', href=node.title.get_url())) else: header.add(tags.span(node.title, _class='navbar-brand')) bar = container.add( tags.div(_class='navbar-collapse collapse', id=node_id)) bar_left = bar.add( tags.ul(_class='nav navbar-nav navbar-left visible-xs')) bar_right = bar.add( tags.ul(_class='nav navbar-nav navbar-right hidden-xs')) for item in node.items: bar_left.add(self.visit(item)) if not getattr(item, 'left', True): bar_right.add(self.visit(item)) spacer = root.add(tags.div()) spacer['id'] = 'navbar-spacer' bottom = root.add(tags.nav()) bottom['class'] = 'navbar navbar-inverse hidden-xs' bottom['id'] = 'navbar-bottom' container = bottom.add(tags.div(_class='container')) bar = container.add(tags.div(_class='navbar-collapse collapse')) bar_left = bar.add(tags.ul(_class='nav navbar-nav navbar-left')) for item in node.items: if getattr(item, 'left', True): bar_left.add(self.visit(item)) return root
def visit_SubmitField(self, node): button = tags.button(node.label.text, _class="btn btn-default", type="submit") return button
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True, **kwargs): """overrides the base class function to generate html needed for metadata editing""" root_div = div("{% load crispy_forms_tags %}") with root_div: super(GeoRasterFileMetaData, self).get_html_forms() with div(id="spatial-coverage-filetype"): with form(id="id-spatial-coverage-file-type", cls='hs-coordinates-picker', data_coordinates_type="point", action="{{ coverage_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy coverage_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;") div("{% crispy orig_coverage_form %}", cls="content-block") div("{% crispy cellinfo_form %}", cls='content-block') with div(id="variables", cls="content-block"): div("{% for form in bandinfo_formset_forms %}") with form(id="{{ form.form_id }}", action="{{ form.action }}", method="post", enctype="multipart/form-data", cls='well'): div("{% crispy form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right btn-form-submit", style="display: none;") div("{% endfor %}") template = Template(root_div.render()) context_dict = dict() context_dict["orig_coverage_form"] = self.get_original_coverage_form() context_dict["cellinfo_form"] = self.get_cellinfo_form() temp_cov_form = self.get_temporal_coverage_form() update_action = "/hsapi/_internal/GeoRasterLogicalFile/{0}/{1}/{2}/update-file-metadata/" create_action = "/hsapi/_internal/GeoRasterLogicalFile/{0}/{1}/add-file-metadata/" spatial_cov_form = self.get_spatial_coverage_form(allow_edit=True) if self.spatial_coverage: form_action = update_action.format(self.logical_file.id, "coverage", self.spatial_coverage.id) else: form_action = create_action.format(self.logical_file.id, "coverage") spatial_cov_form.action = form_action if self.temporal_coverage: form_action = update_action.format(self.logical_file.id, "coverage", self.temporal_coverage.id) temp_cov_form.action = form_action else: form_action = create_action.format(self.logical_file.id, "coverage") temp_cov_form.action = form_action context_dict["coverage_form"] = spatial_cov_form context_dict["temp_form"] = temp_cov_form context_dict["bandinfo_formset_forms"] = self.get_bandinfo_formset().forms context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def visit_SubmitField(self, node): button = tags.button(node.label.text, _class='btn btn-default', type='submit') return button
def get_html_forms(self, dataset_name_form=True, temporal_coverage=True, **kwargs): """overrides the base class function""" root_div = div("{% load crispy_forms_tags %}") with root_div: self.get_update_netcdf_file_html_form() super(NetCDFFileMetaData, self).get_html_forms() with div(): with div(cls="content-block", id="original-coverage-filetype"): with form(id="id-origcoverage-file-type", action="{{ orig_coverage_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy orig_coverage_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;") with div(cls="content-block", id="spatial-coverage-filetype"): with form(id="id-spatial-coverage-file-type", cls='hs-coordinates-picker', data_coordinates_type="box", action="{{ spatial_coverage_form.action }}", method="post", enctype="multipart/form-data"): div("{% crispy spatial_coverage_form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;") with div(): legend("Variables") # id has to be variables to get the vertical scrollbar with div(id="variables"): with div("{% for form in variable_formset_forms %}"): with form(id="{{ form.form_id }}", action="{{ form.action }}", method="post", enctype="multipart/form-data", cls="well"): div("{% crispy form %}") with div(cls="row", style="margin-top:10px;"): with div(cls="col-md-offset-10 col-xs-offset-6 " "col-md-2 col-xs-6"): button("Save changes", type="button", cls="btn btn-primary pull-right", style="display: none;") div("{% endfor %}") self.get_ncdump_html() template = Template(root_div.render()) temp_cov_form = self.get_temporal_coverage_form() update_action = "/hsapi/_internal/NetCDFLogicalFile/{0}/{1}/{2}/update-file-metadata/" create_action = "/hsapi/_internal/NetCDFLogicalFile/{0}/{1}/add-file-metadata/" if self.temporal_coverage: temp_action = update_action.format(self.logical_file.id, "coverage", self.temporal_coverage.id) else: temp_action = create_action.format(self.logical_file.id, "coverage") temp_cov_form.action = temp_action orig_cov_form = self.get_original_coverage_form() if self.originalCoverage: temp_action = update_action.format(self.logical_file.id, "originalcoverage", self.originalCoverage.id) else: temp_action = create_action.format(self.logical_file.id, "originalcoverage") orig_cov_form.action = temp_action spatial_cov_form = self.get_spatial_coverage_form(allow_edit=True) if self.spatial_coverage: temp_action = update_action.format(self.logical_file.id, "coverage", self.spatial_coverage.id) else: temp_action = create_action.format(self.logical_file.id, "coverage") spatial_cov_form.action = temp_action context_dict = dict() context_dict["temp_form"] = temp_cov_form context_dict["orig_coverage_form"] = orig_cov_form context_dict["spatial_coverage_form"] = spatial_cov_form context_dict["variable_formset_forms"] = self.get_variable_formset().forms context = Context(context_dict) rendered_html = template.render(context) return rendered_html
def report_header(self, theme='lux', highlight_color='#f1c40f', navbar_bg='primary', custom_css='', **kwargs): """ Controls the link and script tags in the head. This method should always be called at the top :param str theme: Name of any bootswatch theme. Default is lux :param str highlight_color: any rgb color. default is #f1c40f :param str script: warg Pass additional JS/jquery to add to header :param str custom_css: Pass additional custom CSS. This is in the header, and controls style for the whole report :param str navbar_bg: Controls the color of the navbar. :param bool bootstrap: Set to True to get default bootstrap theme. Does not work with local files :return: The head tag for the report. Example showing how to change the default theme: >>> r = report.report_header(theme='flatly') """ if len(self.report_name) > 40: logging.warning('A report_name greater than 40 characters can \ can cause the navbar to expand and break some functionality.') with self.document.head as report_head: # link and script builder for bootstrap 4 tag.comment('Created using reportng by securisec') tag.meta(charset="utf-8", name="viewport", content="width=device-width, initial-scale=1") # main style components tag.script(src=rng.JSCSS.jquery) tag.script(src=rng.JSCSS.popper_js) tag.script(src=rng.JSCSS.bs4_js) if not self.search == False: tag.script(src=rng.JSCSS.mark_js) # JS for tooltip tag.command('JS for tooltip') tag.script(raw(rng.JSCustom.tooltip_js)) # JS for mark_js tag.comment('JS for mark.js') tag.script(raw(rng.JSCustom.markjs_script)) # JS to populate the navbar dropdown tag.comment('JS to populate the navbar dropdown') tag.script(raw(rng.JSCustom.populate_navbar_onload)) # script that allows for smooth scrolling and adds padding for navbar tag.comment( 'script that allows for smooth scrolling and adds padding for navbar' ) tag.script(raw(rng.JSCustom.smoothscroll_navbar_pad)) # js to filter in the dropdown menu tag.comment('js to filter in the dropdown menu') tag.script(raw(rng.JSCustom.dropdown_filter)) # user insterted JS if 'script' in kwargs: tag.comment('User inserted JS') tag.script(raw(kwargs.get('script'))) # bootswatch style sheets tag.comment('style sheets') if 'bootstrap' in kwargs: if kwargs['bootstrap']: bootswatch = 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css' elif theme != 'lux': bootswatch = "https://bootswatch.com/4/%s/bootstrap.min.css" % theme else: bootswatch = rng.JSCSS.bootswatch tag.link(rel="stylesheet", type="text/css", href=bootswatch, id='bootswatch') tag.link(href=rng.JSCSS.font_awesome, rel="stylesheet") # constructing this way to avoid loading un needed js and css # css for asciinema if self.asciinema == True: tag.comment('css for asciinema') tag.link(rel="stylesheet", type="text/css", href=rng.JSCSS.asciinema_css) # css and js for highlight.js if self.code == True: tag.comment('css and js for highlight.js') tag.link(rel="stylesheet", href=rng.JSCSS.highlightjs_css) tag.script(src=rng.JSCSS.highlightjs_js) tag.script( raw(""" hljs.initHighlightingOnLoad(); """)) # script for progress bar if self.pbar == True: tag.comment('js for progress bar') tag.script(src=rng.JSCSS.progressbar_js) tag.script(raw(rng.JSCustom.progress_bar)) # search highlight color control tag.comment('search highlight color control') # tag.style('span.highlight{background: %s;}' % # highlight_color) tag.style( raw(""" mark {background: %s;} mark.current {background: orangered;} """ % highlight_color)) if custom_css != '': tag.comment('Custom CSS starts here') tag.style(raw(custom_css)) # Navbar on top with 2 margin to seperate from first jumbotron. add class mb-2 with tag.nav( _class= "navbar navbar-expand-lg navbar-dark bg-%s sticky-top" % rng.HelperFunctions.color_to_tag(navbar_bg)): tag.a(self.brand, _class="navbar-brand", href="#") # sets the report title on the navbar tag.span(self.report_name, _class="navbar-text text-secondary") # theme previewer if self.theme_preview: tag.comment('Theme previewer') raw(rng.CustomHTML.themes_preview) # Button for responsive navbar with tag.button(_class="navbar-toggler", type="button", data_toggle="collapse", data_target="#navbarid", aria_controls="navbarColor01", aria_expanded="false", aria_label="Toggle navigation"): tag.span(_class="navbar-toggler-icon") # Search box and button on navbar # make sure to include the word context to div/p tags to make it searchable with tag.div(_class= "navbar-collapse collapse justify-content-md-end", id="navbarid"): # ul class to house the navbar navigation items with tag.ul(_class="navbar-nav"): with tag.li(_class="nav-item"): # add dropdown menu to house h1 tags from sections with tag.div(_class="dropdown"): tag.button( 'sections', _class= "btn btn-secondary btn-block dropdown-toggle", type="button", id="dropdownMenuButton", data_toggle="dropdown", aria_haspopup="true", aria_expanded="false") with tag.ul( _class= "dropdown-menu dropdown-menu-right", aria_labelledby="dropdownMenuButton", id="ddmenu", style= "max-height: 300px; height: auto; overflow: scroll" ): # input box for filtering dropdown tag.input(_class="form-control-sm", id="ddfilter", type="text", placeholder="Filter..") # highlight box form starts here # input for search box if not self.search == False: tag.input(_class="form-control mr-sm-2", type="search", placeholder="Search", data_toggle="tooltip", data_placement="bottom", title="Regex capable. Case sensitive.") # Show search hit count tag.span( "0", id="searchcount", style= "color:%s; font-size: initial; padding-right: 8; align-self: center;" % highlight_color) raw(""" <button data-search="next" class="btn btn-sm btn-secondary">↓</button> <button data-search="prev" class="btn btn-sm btn-secondary">↑</button> """ # <button data-search="clear" class="btn btn-sm btn-secondary">✖</button> ) if self.theme_preview: # theme preview jquery tag.comment('theme preview jquery') tag.script(raw(rng.JSCustom.themes_preview)) return str(report_head)
def hide_all_button(): """Creates a Hide All button for every show/hide div block created""" tags.button("Hide All", onclick="hideAll(" + __get_js_array(__get_all_names()) + ")")