Skip to content

Commit

Permalink
Add html repr
Browse files Browse the repository at this point in the history
  • Loading branch information
edeno committed Jun 28, 2023
1 parent 2f9ec56 commit 2fd1d84
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/hdmf/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,78 @@ def __repr__(self):
template += " {}: {}\n".format(k, v)
return template

def _repr_html_(self):
CSS_STYLE = """
<style>
.nwb-fields { font-family: "Segoe UI", Roboto, sans-serif; }
.nwb-fields .field-key { font-weight: bold; }
.nwb-fields .field-value { color: #00788E; }
.nwb-fields details > summary { cursor: pointer; }
.nwb-fields details > summary:hover { color: #0A6EAA; }
</style>
"""

JS_SCRIPT = """
<script>
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(function() {
console.log('Copied to clipboard: ' + text);
}, function(err) {
console.error('Could not copy text: ', err);
});
}
document.addEventListener('DOMContentLoaded', function() {
let fieldKeys = document.querySelectorAll('.nwb-fields .field-key');
fieldKeys.forEach(function(fieldKey) {
fieldKey.addEventListener('click', function() {
let accessCode = fieldKey.getAttribute('title').replace('Access code: ', '');
copyToClipboard(accessCode);
});
});
});
</script>
"""
html_repr = CSS_STYLE
html_repr += JS_SCRIPT
html_repr += "<div class='nwb-wrap'>"
html_repr += (
"<div class='nwb-header'><div class='xr-obj-type'>NWB File</div></div>"
)
html_repr += self.generate_html_repr(self.fields)
html_repr += "</div>"
return html_repr

def _generate_html_repr(self, fields, level=0, access_code=".fields"):
html_repr = ""

if isinstance(fields, dict):
for key, value in fields.items():
current_access_code = f"{access_code}['{key}']"
if (
isinstance(value, dict)
or isinstance(value, list)
or hasattr(value, "fields")
):
html_repr += f'<details><summary style="margin-left: {level * 20}px;" class="nwb-fields field-key" title="{current_access_code}">{key}</summary>'
if hasattr(value, "fields"):
value = value.fields
current_access_code = current_access_code + ".fields"
html_repr += self.generate_html_repr(
value, level + 1, current_access_code
)
html_repr += "</details>"
else:
html_repr += f'<div style="margin-left: {level * 20}px;" class="nwb-fields"><span class="field-key" title="{current_access_code}">{key}:</span> <span class="field-value">{value}</span></div>'
elif isinstance(fields, list):
for index, item in enumerate(fields):
current_access_code = f"{access_code}[{index}]"
html_repr += f'<div style="margin-left: {level * 20}px;" class="nwb-fields"><span class="field-value" title="{current_access_code}">{str(item)}</span></div>'
else:
pass

return html_repr

@staticmethod
def __smart_str(v, num_indent):
"""
Expand Down

0 comments on commit 2fd1d84

Please sign in to comment.