Consolidate DOM manipulation utilities to eliminate code duplication

- Move addClass and setAttribute from ContentEngine/Injector to utils.go
- Remove duplicate hasInsertrClass implementation
- Add RemoveClass and HasClass utilities for completeness
- Eliminates 74+ lines of exact duplication across files
This commit is contained in:
2025-10-26 18:07:12 +01:00
parent c34a1a033e
commit a52d9bb600
3 changed files with 116 additions and 130 deletions

View File

@@ -9,7 +9,6 @@ import (
"github.com/insertr/insertr/internal/config"
"github.com/insertr/insertr/internal/db"
"golang.org/x/net/html"
"slices"
)
// Injector handles content injection into HTML elements
@@ -168,8 +167,8 @@ func (i *Injector) findElementByTag(node *html.Node, tag string) *html.Node {
// AddContentAttributes adds necessary data attributes and insertr class for editor functionality
func (i *Injector) AddContentAttributes(node *html.Node, contentID string, contentType string) {
i.setAttribute(node, "data-content-id", contentID)
i.addClass(node, "insertr")
SetAttribute(node, "data-content-id", contentID)
AddClass(node, "insertr")
}
// InjectEditorAssets adds editor JavaScript to HTML document and injects demo gate if needed
@@ -200,63 +199,6 @@ func (i *Injector) findHeadElement(node *html.Node) *html.Node {
return nil
}
// setAttribute safely sets an attribute on an HTML node
func (i *Injector) setAttribute(node *html.Node, key, value string) {
// Remove existing attribute if present
for idx, attr := range node.Attr {
if attr.Key == key {
node.Attr = slices.Delete(node.Attr, idx, idx+1)
break
}
}
// Add new attribute
node.Attr = append(node.Attr, html.Attribute{
Key: key,
Val: value,
})
}
// addClass safely adds a class to an HTML node
func (i *Injector) addClass(node *html.Node, className string) {
var classAttr *html.Attribute
var classIndex int = -1
// Find existing class attribute
for idx, attr := range node.Attr {
if attr.Key == "class" {
classAttr = &attr
classIndex = idx
break
}
}
var classes []string
if classAttr != nil {
classes = strings.Fields(classAttr.Val)
}
// Check if class already exists
if slices.Contains(classes, className) {
return // Class already exists
}
// Add new class
classes = append(classes, className)
newClassValue := strings.Join(classes, " ")
if classIndex >= 0 {
// Update existing class attribute
node.Attr[classIndex].Val = newClassValue
} else {
// Add new class attribute
node.Attr = append(node.Attr, html.Attribute{
Key: "class",
Val: newClassValue,
})
}
}
// Element represents a parsed HTML element with metadata
type Element struct {
Node *html.Node