Skip to content

Home Information - Your home, your data, organized.

Python

Feature/78 Attribute values as clickable hyperlinks (#252)

Thiago Trautwein Santosaf75e9442f52
diff --git a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
index c89b7e72..4e59f057 100644
--- a/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
+++ b/src/hi/apps/attribute/templates/attribute/components/regular_attribute_card.html
@@ -83,6 +83,17 @@ Individual attribute attribute card with value editing and actions
{% icon "chevron-down" size="sm" %}
</button>
{% endif %}
+
+ {% if attribute_form.instance.pk and attribute_form.instance.is_editable %}
+ {% if attribute_form.instance.value_type.name == 'TEXT' %}
+ <button type="button"
+ class="btn btn-sm btn-outline-secondary"
+ title="Edit value"
+ onclick="Hi.attr.enterAttributeEditMode(this)">
+ {% icon "edit" size="sm" %}
+ </button>
+ {% endif %}
+ {% endif %}
{% if attribute_form.instance.pk and not attribute_form.suppress_history %}
<a href="{% attr_history_url attr_item_context attribute_form.instance.pk %}"
@@ -148,13 +159,13 @@ Individual attribute attribute card with value editing and actions
{% elif attribute_form.instance.value_type.is_secret %}
{% include "attribute/components/value_types/attribute_value_secret.html" %}
{% else %}
- <!-- TEXT and other types use textarea -->
+ <!-- TEXT and other fallback types use text read/edit component -->
<div class="{{ DIVID.ATTR_V2_TEXT_VALUE_CLASS }}">
{% include "attribute/components/value_types/attribute_value_text.html" %}
</div>
{% endif %}
{% else %}
- <!-- New attribute - always use textarea (TEXT behavior) -->
+ <!-- New attribute uses text read/edit component (starts in edit mode) -->
<div class="{{ DIVID.ATTR_V2_TEXT_VALUE_CLASS }}">
{% include "attribute/components/value_types/attribute_value_text.html" %}
</div>
diff --git a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_text.html b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_text.html
index 37104b54..6aef7f43 100644
--- a/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_text.html
+++ b/src/hi/apps/attribute/templates/attribute/components/value_types/attribute_value_text.html
@@ -1,33 +1,68 @@
{% load common_tags %}
+{% load attribute_extras %}
{% comment %}
Text Attribute Value Component
-Renders textarea with special handling (hidden input + display textarea) for text attributes
-This component handles the auto-sizing and expand/collapse functionality
+Renders TEXT attributes in a single read/edit pattern:
+1) Read mode with inline linkification (safe for plain text too)
+2) Edit mode using textarea plus cancel action
+
+New/unsaved TEXT forms start directly in edit mode.
{% endcomment %}
-<!-- Hidden field pattern for data integrity -->
{% with value_text=attribute_form.value.value|default_if_none:'' %}
{% with line_count=value_text|linecount %}
{% with display_rows=line_count|min_value:4 %}
{% with overflows=line_count|add:"-4" %}
<div class="{{ DIVID.ATTR_V2_TEXT_VALUE_WRAPPER_CLASS }}"
- data-overflow="{% if overflows > 0 %}true{% else %}false{% endif %}"
+ data-overflow="false"
data-line-count="{{ line_count }}">
-
- <!-- Real form field - contains actual data, never manipulated during editing -->
- <input type="hidden"
+
+ <!-- Real form field - source of truth for submission -->
+ <input type="hidden"
name="{{ attribute_form.value.html_name }}"
id="hidden-{{ attribute_form.value.id_for_label }}"
- value="{{ attribute_form.value.value|default_if_none:'' }}">
-
- <!-- Display field - for UI only (no name = not submitted) -->
- <textarea rows="{{ display_rows }}"
- id="{{ attribute_form.value.id_for_label }}"
- class="form-control {{ DIVID.ATTR_V2_TEXTAREA_CLASS }} {{ DIVID.ATTR_V2_DISPLAY_FIELD_CLASS }}"
- data-overflow="{% if overflows > 0 %}true{% else %}false{% endif %}"
- data-hidden-field="hidden-{{ attribute_form.value.id_for_label }}"
- {% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %}
- data-original-value="{{ attribute_form.value.value|default_if_none:'' }}">{{ attribute_form.value.value|default_if_none:'' }}</textarea>
+ value="{{ value_text }}">
+
+ <!-- Read mode with inline links -->
+ <div class="{{ DIVID.ATTR_V2_TEXT_READ_MODE_CLASS }}" data-read-expanded="false"
+ {% if not attribute_form.instance.pk %}style="display: none;"{% endif %}>
+ <div class="{{ DIVID.ATTR_V2_TEXT_READ_CONTENT_CLASS }}{% if overflows > 0 %} is-collapsed{% endif %}"
+ {% if attribute_form.instance.is_editable %}onclick="Hi.attr.handleTextReadContentClick(event)" style="cursor: text;"{% endif %}>
+ {% if value_text %}
+ {{ value_text|attribute_text_linkify }}
+ {% else %}
+ &nbsp;
+ {% endif %}
+ </div>
+
+ {% if overflows > 0 %}
+ <div class="{{ DIVID.ATTR_V2_EXPAND_CONTROLS_CLASS }}" style="display: block;">
+ <button type="button" class="btn btn-sm btn-link" onclick="Hi.attr.toggleTextReadExpandedView(this)">
+ <span class="{{ DIVID.ATTR_V2_SHOW_MORE_TEXT_CLASS }}">Show more...</span>
+ <span class="{{ DIVID.ATTR_V2_SHOW_LESS_TEXT_CLASS }}" style="display: none;">Show less</span>
+ </button>
+ </div>
+ {% endif %}
+ </div>
+
+ {% if not attribute_form.instance.pk or attribute_form.instance.is_editable %}
+ <!-- Edit mode -->
+ <div class="{{ DIVID.ATTR_V2_TEXT_EDIT_MODE_CLASS }}"
+ {% if attribute_form.instance.pk %}style="display: none;"{% endif %}>
+ <textarea rows="{{ display_rows }}"
+ id="{{ attribute_form.value.id_for_label }}"
+ class="form-control {{ DIVID.ATTR_V2_TEXTAREA_CLASS }} {{ DIVID.ATTR_V2_DISPLAY_FIELD_CLASS }} {{ DIVID.ATTR_V2_TEXT_EDIT_FIELD_CLASS }}"
+ data-hidden-field="hidden-{{ attribute_form.value.id_for_label }}"
+ data-original-value="{{ value_text }}"
+ data-read-edit-field="true">{{ value_text }}</textarea>
+ <div class="{{ DIVID.ATTR_V2_TEXT_EDIT_ACTIONS_CLASS }}">
+ <button type="button"
+ class="btn btn-sm attr-v2-text-cancel-btn"
+ onclick="Hi.attr.cancelTextEditMode(this)">Cancel</button>
+ </div>
+ </div>
+ {% endif %}
+
{% if attribute_form.value.errors %}
<div class="attr-v2-field-errors">
{% for error in attribute_form.value.errors %}
@@ -35,14 +70,6 @@ This component handles the auto-sizing and expand/collapse functionality
{% endfor %}
</div>
{% endif %}
- {% if overflows > 0 %}
- <div class="{{ DIVID.ATTR_V2_EXPAND_CONTROLS_CLASS }}" style="display: block;">
- <button type="button" class="btn btn-sm btn-link" onclick="Hi.attr.toggleExpandedView(this)">
- <span class="{{ DIVID.ATTR_V2_SHOW_MORE_TEXT_CLASS }}">Show more...</span>
- <span class="{{ DIVID.ATTR_V2_SHOW_LESS_TEXT_CLASS }}" style="display: none;">Show less</span>
- </button>
- </div>
- {% endif %}
</div>
{% endwith %}
{% endwith %}
diff --git a/src/hi/apps/attribute/templatetags/attribute_extras.py b/src/hi/apps/attribute/templatetags/attribute_extras.py
index c7f72d84..50f74305 100644
--- a/src/hi/apps/attribute/templatetags/attribute_extras.py
+++ b/src/hi/apps/attribute/templatetags/attribute_extras.py
@@ -1,6 +1,48 @@
+import re
+
from django import template
+from django.core.exceptions import ValidationError
+from django.core.validators import URLValidator
+from django.utils.html import escape, format_html
+from django.utils.safestring import mark_safe
register = template.Library()
+_url_validator = URLValidator()
+_URL_IN_TEXT_PATTERN = re.compile(r'https?://[^\s<>"\']+')
+_TRAILING_PUNCTUATION = '.,;:!?)]}'
+
+
+def _is_valid_url(value):
+ """Return True when value passes Django URL validation."""
+ try:
+ _url_validator(value)
+ except ValidationError:
+ return False
+ return True
+
+
+def _split_url_and_trailing_punctuation(candidate):
+ """Split common trailing punctuation from URL candidates."""
+ trailing = []
+ trimmed = candidate
+
+ while trimmed and trimmed[-1] in _TRAILING_PUNCTUATION:
+ trailing.append(trimmed[-1])
+ trimmed = trimmed[:-1]
+
+ return trimmed, ''.join(reversed(trailing))
+
+
+def _iter_valid_url_segments(text):
+ """Yield (start, end, valid_url, trailing_punctuation) for each valid URL."""
+ for match in _URL_IN_TEXT_PATTERN.finditer(text):
+ raw_candidate = match.group(0)
+ url_candidate, trailing = _split_url_and_trailing_punctuation(raw_candidate)
+
+ if not url_candidate or not _is_valid_url(url_candidate):
+ continue
+
+ yield (match.start(), match.end(), url_candidate, trailing)
@register.filter
@@ -199,3 +241,78 @@ def attr_restore_all_url(attr_item_context):
attr_item_context.owner_id_param_name: attr_item_context.owner_id,
}
return reverse(url_name, kwargs=params)
+
+
+def attribute_url(value):
+ """
+ Return a validated URL string when value is a URL, otherwise return empty string.
+
+ This is intended for best-effort display-time detection without persisting
+ any derived value in the database.
+ """
+ if value is None:
+ return ""
+
+ url_candidate = str(value).strip()
+ if not url_candidate:
+ return ""
+
+ if not _is_valid_url(url_candidate):
+ return ""
+
+ return url_candidate
+
+
+def attribute_text_has_url(value):
+ """Return True when text contains at least one valid URL candidate."""
+ if value is None:
+ return False
+
+ text_value = str(value)
+ if not text_value:
+ return False
+
+ return any(True for _ in _iter_valid_url_segments(text_value))
+
+
+def attribute_text_linkify(value):
+ """
+ Render text with inline clickable links while safely escaping non-URL text.
+
+ Newlines are converted to <br> for read-mode display.
+ """
+ if value is None:
+ return ""
+
+ text_value = str(value)
+ if text_value == "":
+ return ""
+
+ rendered_parts = []
+ current_index = 0
+
+ for start, end, valid_url, trailing in _iter_valid_url_segments(text_value):
+ if start > current_index:
+ rendered_parts.append(escape(text_value[current_index:start]))
+
+ rendered_parts.append(
+ format_html(
+ '<a href="{}" target="_blank" rel="noopener noreferrer">{}</a>',
+ valid_url,
+ valid_url,
+ )
+ )
+
+ if trailing:
+ rendered_parts.append(escape(trailing))
+
+ current_index = end
+
+ if current_index < len(text_value):
+ rendered_parts.append(escape(text_value[current_index:]))
+
+ html = ''.join(str(part) for part in rendered_parts).replace('\n', '<br>')
+ return mark_safe(html)
diff --git a/src/hi/apps/attribute/tests/test_templatetags.py b/src/hi/apps/attribute/tests/test_templatetags.py
index 7962f78b..7f7f5a1f 100644
--- a/src/hi/apps/attribute/tests/test_templatetags.py
+++ b/src/hi/apps/attribute/tests/test_templatetags.py
@@ -11,7 +11,8 @@ from django.test import TestCase
from hi.apps.attribute.templatetags.attribute_extras import (
attribute_preview, file_title_field_name, history_target_id,
- history_toggle_id, attr_history_url, attr_restore_url
+ history_toggle_id, attr_history_url, attr_restore_url, attribute_url,
+ attribute_text_has_url, attribute_text_linkify,
)
from hi.apps.attribute.edit_context import AttributeItemEditContext
@@ -148,6 +149,107 @@ class TestAttributeContextFilters(TestCase):
self.assertEqual(result, "history-extra-123-456")
+class TestAttributeUrlFilter(TestCase):
+ """Test display-time URL detection used for attribute value rendering."""
+
+ def test_attribute_url_returns_valid_url(self):
+ self.assertEqual(
+ attribute_url("https://example.com/path?q=1"),
+ "https://example.com/path?q=1"
+ )
+
+ def test_attribute_url_trims_whitespace(self):
+ self.assertEqual(
+ attribute_url(" https://example.com "),
+ "https://example.com"
+ )
+
+ def test_attribute_url_rejects_invalid_values(self):
+ self.assertEqual(attribute_url("not a url"), "")
+ self.assertEqual(attribute_url(""), "")
+ self.assertEqual(attribute_url(None), "")
+
+
+class TestAttributeTextUrlFilters(TestCase):
+ """Test URL detection and inline linkification for text attributes."""
+
+ def test_attribute_text_has_url_detects_embedded_urls(self):
+ text = "Primary docs: https://example.com/docs and backup: https://backup.example.com"
+ self.assertTrue(attribute_text_has_url(text))
+
+ def test_attribute_text_has_url_rejects_non_url_text(self):
+ self.assertFalse(attribute_text_has_url("example.com without scheme"))
+ self.assertFalse(attribute_text_has_url(""))
+ self.assertFalse(attribute_text_has_url(None))
+
+ def test_attribute_text_has_url_detects_url_with_wrapping_punctuation(self):
+ self.assertTrue(attribute_text_has_url("Open this (https://example.com/docs)."))
+
+ def test_attribute_text_has_url_ignores_invalid_http_candidates(self):
+ self.assertFalse(attribute_text_has_url("Broken candidate: https://bad"))
+
+ def test_attribute_text_linkify_renders_multiple_links_inline(self):
+ rendered = attribute_text_linkify(
+ "See https://example.com and https://example.org/path?q=1 for details"
+ )
+
+ self.assertIn('<a href="https://example.com" target="_blank" rel="noopener noreferrer">https://example.com</a>', rendered)
+ self.assertIn('<a href="https://example.org/path?q=1" target="_blank" rel="noopener noreferrer">https://example.org/path?q=1</a>', rendered)
+
+ def test_attribute_text_linkify_preserves_newlines_with_br(self):
+ rendered = attribute_text_linkify("Line 1\nhttps://example.com\nLine 3")
+ self.assertIn('Line 1<br>', rendered)
+ self.assertIn('</a><br>Line 3', rendered)
+
+ def test_attribute_text_linkify_escapes_non_url_html(self):
+ rendered = attribute_text_linkify('<script>alert(1)</script> https://example.com')
+ self.assertIn('&lt;script&gt;alert(1)&lt;/script&gt;', rendered)
+ self.assertNotIn('<script>', rendered)
+
+ def test_attribute_text_linkify_keeps_trailing_punctuation_outside_link(self):
+ rendered = attribute_text_linkify('Read this (https://example.com/docs).')
+ self.assertIn('<a href="https://example.com/docs" target="_blank" rel="noopener noreferrer">https://example.com/docs</a>).', rendered)
+
+ def test_attribute_text_linkify_keeps_multiple_trailing_punctuation_outside_link(self):
+ rendered = attribute_text_linkify('Open https://example.com/path), right now!')
+ self.assertIn(
+ '<a href="https://example.com/path" target="_blank" rel="noopener noreferrer">https://example.com/path</a>),',
+ rendered,
+ )
+
+ def test_attribute_text_linkify_does_not_link_invalid_candidates(self):
+ rendered = attribute_text_linkify('Broken: https://bad and valid: https://example.com')
+ self.assertIn('Broken: https://bad', rendered)
+ self.assertIn(
+ '<a href="https://example.com" target="_blank" rel="noopener noreferrer">https://example.com</a>',
+ rendered,
+ )
+
+ def test_attribute_text_linkify_filter_renders_anchor_in_template_output(self):
+ template_str = """
+ {% load attribute_extras %}
+ {{ value|attribute_text_linkify }}
+ """
+ template = Template(template_str)
+
+ rendered = template.render(Context({'value': 'See https://example.com'}))
+ self.assertIn('<a href="https://example.com" target="_blank" rel="noopener noreferrer">', rendered)
+ self.assertNotIn('&lt;a href=', rendered)
+
+ def test_attribute_text_has_url_filter_works_in_template_condition(self):
+ template_str = """
+ {% load attribute_extras %}
+ {% if value|attribute_text_has_url %}HAS_URL{% else %}NO_URL{% endif %}
+ """
+ template = Template(template_str)
+
+ rendered_with_url = template.render(Context({'value': 'Link: https://example.com'}))
+ self.assertIn('HAS_URL', rendered_with_url)
+
+ rendered_without_url = template.render(Context({'value': 'No link here'}))
+ self.assertIn('NO_URL', rendered_without_url)
+
+
class TestAttributeUrlTags(TestCase):
"""Test template tags that generate URLs - URL construction logic."""
@@ -222,75 +324,6 @@ class TestAttributeUrlTags(TestCase):
with self.assertRaises(NoReverseMatch):
attr_restore_url(self.context, self.attribute_id, self.history_id)
-
-
-class TestTemplateIntegration(TestCase):
- """Test template filters and tags integrated with Django template system."""
-
- def setUp(self):
- self.mock_owner = MockOwner(id=123, name="Test Owner")
- self.context = AttributeItemEditContext(self.mock_owner, "entity")
-
- def test_attribute_preview_filter_in_template(self):
- """Test attribute_preview filter works in actual template rendering."""
- template_str = """
- {% load attribute_extras %}
- Preview: {{ value|attribute_preview:30 }}
- """
-
- template = Template(template_str)
-
- # Test with long multiline value
- long_value = "This is a very long first line that will be truncated\nSecond line\nThird line"
- context = Context({'value': long_value})
-
- rendered = template.render(context).strip()
- self.assertIn("Preview:", rendered)
- self.assertIn("...", rendered)
- self.assertIn("chars", rendered)
- self.assertIn("lines", rendered)
-
- def test_context_filters_in_template(self):
- """Test AttributeItemEditContext filters work in template rendering."""
- template_str = """
- {% load attribute_extras %}
- Field: {{ attr_item_context|file_title_field_name:attribute_id }}
- Target: {{ attr_item_context|history_target_id:attribute_id }}
- Toggle: {{ attr_item_context|history_toggle_id:attribute_id }}
- """
-
- template = Template(template_str)
- context = Context({
- 'attr_item_context': self.context,
- 'attribute_id': 456
- })
-
- rendered = template.render(context)
- self.assertIn("Field: file_title_123_456", rendered)
- self.assertIn("Target: hi-entity-attr-history-123-456", rendered)
- self.assertIn("Toggle: history-extra-123-456", rendered)
-
- @patch('django.urls.reverse')
- def test_url_tags_in_template(self, mock_reverse):
- """Test URL tags work in actual template rendering."""
- mock_reverse.side_effect = lambda name, kwargs: f"/{name.replace('_', '/')}/{kwargs.get('entity_id', 0)}/{kwargs.get('attribute_id', 0)}/"
-
- template_str = """
- {% load attribute_extras %}
- History: {% attr_history_url attr_item_context attribute_id %}
- Restore: {% attr_restore_url attr_item_context attribute_id history_id %}
- """
-
- template = Template(template_str)
- context = Context({
- 'attr_item_context': self.context,
- 'attribute_id': 456,
- 'history_id': 789
- })
-
- rendered = template.render(context)
- self.assertIn("History:", rendered)
- self.assertIn("Restore:", rendered)
def test_template_syntax_error_handling(self):
"""Test template tags handle syntax errors appropriately."""
@@ -334,4 +367,21 @@ class TestTemplateIntegration(TestCase):
# This should raise an AttributeError which Django templates handle
with self.assertRaises(AttributeError):
template_error.render(context_error)
+
+ def test_attribute_url_filter_in_template(self):
+ """Test attribute_url filter renders links only for valid URLs."""
+ template_str = """
+ {% load attribute_extras %}
+ {% with detected=value|attribute_url %}
+ {% if detected %}<a href="{{ detected }}">{{ detected }}</a>{% else %}NO_LINK{% endif %}
+ {% endwith %}
+ """
+
+ template = Template(template_str)
+
+ rendered_valid = template.render(Context({'value': 'https://example.com'}))
+ self.assertIn('href="https://example.com"', rendered_valid)
+
+ rendered_invalid = template.render(Context({'value': 'abc'}))
+ self.assertIn('NO_LINK', rendered_invalid)
diff --git a/src/hi/constants.py b/src/hi/constants.py
index a396a9f0..f8a558a6 100644
--- a/src/hi/constants.py
+++ b/src/hi/constants.py
@@ -121,6 +121,11 @@ DIVID = {
'ATTR_V2_TEXT_VALUE_CLASS': 'attr-v2-text-value',
'ATTR_V2_SECRET_CHECKBOX_CLASS': 'attr-v2-secret-checkbox',
'ATTR_V2_INLINE_HISTORY_CLASS': 'attr-v2-inline-history',
+ 'ATTR_V2_TEXT_READ_MODE_CLASS': 'attr-v2-text-read-mode',
+ 'ATTR_V2_TEXT_READ_CONTENT_CLASS': 'attr-v2-text-read-content',
+ 'ATTR_V2_TEXT_EDIT_MODE_CLASS': 'attr-v2-text-edit-mode',
+ 'ATTR_V2_TEXT_EDIT_FIELD_CLASS': 'attr-v2-text-edit-field',
+ 'ATTR_V2_TEXT_EDIT_ACTIONS_CLASS': 'attr-v2-text-edit-actions',
'ATTR_V2_DISPLAY_FIELD_CLASS': 'display-field',
'ATTR_V2_SHOW_MORE_TEXT_CLASS': 'show-more-text',
'ATTR_V2_SHOW_LESS_TEXT_CLASS': 'show-less-text',
diff --git a/src/hi/static/css/attribute.css b/src/hi/static/css/attribute.css
index c93bb43f..f042602a 100644
--- a/src/hi/static/css/attribute.css
+++ b/src/hi/static/css/attribute.css
@@ -272,6 +272,66 @@
background: rgba(0, 0, 0, 0.02);
}
+/* URL-aware read/edit text mode */
+.attr-v2-text-read-content {
+ position: relative;
+ border: 1px solid var(--line-color);
+ border-radius: 0.375rem;
+ padding: 0.75rem;
+ background-color: var(--white, #ffffff);
+ line-height: 1.4;
+ word-break: break-word;
+}
+
+.attr-v2-text-read-content a {
+ word-break: break-all;
+}
+
+.attr-v2-text-read-content.is-collapsed {
+ max-height: calc((1.4em * 4) + 1.5rem);
+ overflow: hidden;
+}
+
+.attr-v2-text-read-content.is-collapsed::after {
+ content: '';
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ height: 1.75rem;
+ background: linear-gradient(to bottom, rgba(255, 255, 255, 0), var(--white, #ffffff));
+ pointer-events: none;
+}
+
+.attr-v2-text-edit-mode {
+ margin-top: 0.5rem;
+}
+
+.attr-v2-text-edit-actions {
+ margin-top: 0.25rem;
+ display: flex;
+ justify-content: flex-end;
+}
+
+.attr-v2-text-cancel-btn {
+ border: 0;
+ background: transparent;
+ color: var(--primary-color, #177072);
+}
+
+.attr-v2-text-cancel-btn:hover {
+ border: 0;
+ color: var(--primary-color-dark, #11595b);
+ background-color: rgba(23, 112, 114, 0.08);
+}
+
+.attr-v2-text-cancel-btn:focus {
+ border: 0;
+ color: var(--primary-color, #177072);
+ background-color: rgba(23, 112, 114, 0.08);
+ box-shadow: 0 0 0 0.2rem rgba(23, 112, 114, 0.25);
+}
+
/* Truncated textarea styling - indicate it's clickable */
.attr-v2-textarea.truncated[readonly] {
cursor: pointer;
diff --git a/src/hi/static/js/attr-dirty-tracking.js b/src/hi/static/js/attr-dirty-tracking.js
index 9de37ba7..114033c6 100644
--- a/src/hi/static/js/attr-dirty-tracking.js
+++ b/src/hi/static/js/attr-dirty-tracking.js
@@ -367,7 +367,8 @@
const form = this.container.querySelector(this.config.formSelector);
if (!form) return;
- const displayFields = form.querySelectorAll(Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR);
+ const textFieldSelector = `${Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR}, ${Hi.ATTR_V2_TEXT_EDIT_FIELD_SELECTOR}`;
+ const displayFields = form.querySelectorAll(textFieldSelector);
displayFields.forEach(displayField => {
const hiddenFieldId = displayField.getAttribute('data-hidden-field');
const hiddenField = hiddenFieldId ? document.getElementById(hiddenFieldId) : null;
diff --git a/src/hi/static/js/attr.js b/src/hi/static/js/attr.js
index a36de7d7..73cb2ede 100644
--- a/src/hi/static/js/attr.js
+++ b/src/hi/static/js/attr.js
@@ -115,7 +115,27 @@
toggleExpandedView: function(button) {
return _toggleExpandedView(button);
},
-
+
+ enterAttributeEditMode: function(button) {
+ return _enterAttributeEditMode(button);
+ },
+
+ toggleTextReadExpandedView: function(button) {
+ return _toggleTextReadExpandedView(button);
+ },
+
+ enterTextEditMode: function(button) {
+ return _enterTextEditMode(button);
+ },
+
+ cancelTextEditMode: function(button) {
+ return _cancelTextEditMode(button);
+ },
+
+ handleTextReadContentClick: function(event) {
+ return _handleTextReadContentClick(event);
+ },
+
reorderAttributeCard: function(button, direction) {
return _reorderAttributeCard(button, direction);
},
@@ -1186,6 +1206,180 @@
displayField.off('input.overflow');
}
}
+
+ function _toggleTextReadExpandedView(button) {
+ const $button = $(button);
+ const readMode = $button.closest(Hi.ATTR_V2_TEXT_READ_MODE_SELECTOR);
+ const readContent = readMode.find(Hi.ATTR_V2_TEXT_READ_CONTENT_SELECTOR).first();
+
+ if (readContent.length === 0) {
+ return;
+ }
+
+ const showMoreText = $button.find(Hi.ATTR_V2_SHOW_MORE_TEXT_SELECTOR);
+ const showLessText = $button.find(Hi.ATTR_V2_SHOW_LESS_TEXT_SELECTOR);
+ const isCollapsed = readContent.hasClass('is-collapsed');
+
+ if (isCollapsed) {
+ readContent.removeClass('is-collapsed');
+ readMode.attr('data-read-expanded', 'true');
+ showMoreText.hide();
+ showLessText.show();
+ } else {
+ readContent.addClass('is-collapsed');
+ readMode.attr('data-read-expanded', 'false');
+ showMoreText.show();
+ showLessText.hide();
+ }
+ }
+
+ function _enterAttributeEditMode(button) {
+ const $button = $(button);
+ const $card = $button.closest(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);
+ if ($card.length === 0) {
+ return;
+ }
+
+ const isSecret = $card.data('is-secret') === true || $card.data('is-secret') === 'true';
+ if (isSecret) {
+ const secretInput = $card.find(Hi.ATTR_V2_SECRET_INPUT_SELECTOR).first();
+ if (secretInput.length === 0 || secretInput.prop('disabled')) {
+ return;
+ }
+
+ const toggleButton = $card.find('.attr-v2-secret-toggle').first();
+ if (toggleButton.length > 0 && secretInput.attr('type') === 'password') {
+ _toggleSecretField(toggleButton[0]);
+ }
+
+ secretInput.focus();
+ return;
+ }
+
+ const textWrapper = $card.find(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR).first();
+ if (textWrapper.length > 0) {
+ _enterTextEditMode(button);
+ return;
+ }
+
+ const editableField = $card.find(
+ '.attr-v2-boolean-checkbox:not([disabled]), ' +
+ 'select[name$="-value"]:not([disabled]), ' +
+ 'input[name$="-value"]:not([type="hidden"]):not([disabled]), ' +
+ 'textarea[name$="-value"]:not([disabled])'
+ ).first();
+
+ if (editableField.length > 0) {
+ editableField.trigger('focus');
+ }
+
+ return;
+ }
+
+ function _handleTextReadContentClick(event) {
+ // Don't enter edit mode if clicking a link
+ if (event.target.closest('a')) {
+ return;
+ }
+ // Don't enter edit mode if user is selecting text
+ const selection = window.getSelection();
+ if (selection && !selection.isCollapsed) {
+ return;
+ }
+ _enterTextEditMode(event.currentTarget);
+ }
+
+ function _enterTextEditMode(button) {
+ const $button = $(button);
+ let wrapper = $button.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);
+ if (wrapper.length === 0) {
+ const card = $button.closest(Hi.ATTR_V2_ATTRIBUTE_CARD_SELECTOR);
+ wrapper = card.find(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR).first();
+ }
+
+ if (wrapper.length === 0) {
+ return;
+ }
+
+ const readMode = wrapper.find(Hi.ATTR_V2_TEXT_READ_MODE_SELECTOR).first();
+ const editMode = wrapper.find(Hi.ATTR_V2_TEXT_EDIT_MODE_SELECTOR).first();
+ const editField = editMode.find(Hi.ATTR_V2_TEXT_EDIT_FIELD_SELECTOR).first();
+
+ if (editMode.length === 0 || editField.length === 0) {
+ return;
+ }
+
+ if (editMode.is(':visible')) {
+ const currentRawField = editField[0];
+ if (currentRawField) {
+ currentRawField.focus();
+ }
+ return;
+ }
+
+ const hiddenFieldId = editField.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
+ const hiddenField = hiddenFieldId ? wrapper.find(`#${hiddenFieldId}`) : null;
+
+ if (hiddenField && hiddenField.length > 0) {
+ editField.val(hiddenField.val() || '');
+ }
+
+ readMode.hide();
+ editMode.show();
+
+ if (window.autosize) {
+ if (!editField[0]._autosize) {
+ autosize(editField);
+ }
+ autosize.update(editField);
+ }
+
+ const rawField = editField[0];
+ if (rawField) {
+ rawField.focus();
+ const textLength = rawField.value.length;
+ rawField.setSelectionRange(textLength, textLength);
+ }
+ }
+
+ function _cancelTextEditMode(button) {
+ const $button = $(button);
+ const wrapper = $button.closest(Hi.ATTR_V2_TEXT_VALUE_WRAPPER_SELECTOR);
+ const readMode = wrapper.find(Hi.ATTR_V2_TEXT_READ_MODE_SELECTOR).first();
+ const editMode = wrapper.find(Hi.ATTR_V2_TEXT_EDIT_MODE_SELECTOR).first();
+ const editField = editMode.find(Hi.ATTR_V2_TEXT_EDIT_FIELD_SELECTOR).first();
+
+ if (editField.length === 0) {
+ return;
+ }
+
+ const originalValue = editField.attr(Hi.DATA_ORIGINAL_VALUE_ATTR) || '';
+ const hiddenFieldId = editField.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
+ const hiddenField = hiddenFieldId ? wrapper.find(`#${hiddenFieldId}`) : null;
+
+ editField.val(originalValue);
+
+ if (hiddenField && hiddenField.length > 0) {
+ hiddenField.val(originalValue);
+ }
+
+ const container = $button.closest(Hi.ATTR_V2_CONTAINER_SELECTOR);
+ if (container.length > 0 && window.Hi && window.Hi.attr && window.Hi.attr.dirtyTracking) {
+ const containerId = container.attr('id');
+ if (containerId) {
+ const instance = window.Hi.attr.dirtyTracking.getInstance(containerId);
+ if (instance) {
+ instance.handleFieldChange(editField[0]);
+ if (hiddenField && hiddenField.length > 0) {
+ instance.handleFieldChange(hiddenField[0]);
+ }
+ }
+ }
+ }
+
+ editMode.hide();
+ readMode.show();
+ }
function _reorderAttributeCard(button, direction) {
const card = button.closest(`[${Hi.DATA_ATTRIBUTE_ID_ATTR}]`);
@@ -1269,7 +1463,7 @@
}
function _restoreTextarea($card, defaultValue) {
- const $textarea = $card.find(Hi.ATTR_V2_TEXTAREA_SELECTOR);
+ const $textarea = $card.find(Hi.ATTR_V2_TEXTAREA_SELECTOR).first();
if (!$textarea.length) {
console.error('Textarea not found for text attribute');
@@ -1277,6 +1471,12 @@
}
$textarea.val(defaultValue).trigger('input');
+
+ const hiddenFieldId = $textarea.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
+ const $hiddenField = hiddenFieldId ? $card.find(`#${hiddenFieldId}`) : null;
+ if ($hiddenField && $hiddenField.length > 0) {
+ $hiddenField.val(defaultValue);
+ }
}
function _restoreSelect($card, defaultValue) {
@@ -1304,7 +1504,9 @@
// Sync textarea values to hidden fields before form submission
function _syncTextareaValuesToHiddenFields($container) {
// Process all display fields within this container
- $container.find(Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR).each(function() {
+ const textFieldSelector = `${Hi.ATTR_V2_DISPLAY_FIELD_SELECTOR}, ${Hi.ATTR_V2_TEXT_EDIT_FIELD_SELECTOR}`;
+
+ $container.find(textFieldSelector).each(function() {
const displayField = $(this);
const hiddenFieldId = displayField.attr(Hi.DATA_HIDDEN_FIELD_ATTR);
const hiddenField = hiddenFieldId ? $container.find('#' + hiddenFieldId) : null;
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index fc8ba769..57cd01ee 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -108,6 +108,10 @@
ATTR_V2_AUTO_DISMISS_SELECTOR: '.attr-v2-auto-dismiss',
ATTR_V2_UPDATE_BTN_SELECTOR: '.attr-v2-update-btn',
ATTR_V2_DISPLAY_FIELD_SELECTOR: '.display-field',
+ ATTR_V2_TEXT_READ_MODE_SELECTOR: '.attr-v2-text-read-mode',
+ ATTR_V2_TEXT_READ_CONTENT_SELECTOR: '.attr-v2-text-read-content',
+ ATTR_V2_TEXT_EDIT_MODE_SELECTOR: '.attr-v2-text-edit-mode',
+ ATTR_V2_TEXT_EDIT_FIELD_SELECTOR: '.attr-v2-text-edit-field',
ATTR_V2_SHOW_MORE_TEXT_SELECTOR: '.show-more-text',
ATTR_V2_SHOW_LESS_TEXT_SELECTOR: '.show-less-text',