feat: implement auto-injection of insertr.js with site-specific configuration
• Add /insertr.js endpoint to serve JavaScript library from API server • Implement demo gate auto-injection for sites without existing gates • Add dynamic site ID injection using per-demo configuration files • Fix CORS middleware to support localhost origins on any port • Update demo commands to use individual insertr.yaml configs • Resolve content persistence issues by matching site IDs between injection and enhancement • Enable complete edit/save workflow for demo sites with proper namespace isolation
This commit is contained in:
@@ -209,17 +209,17 @@ func (i *Injector) AddContentAttributes(node *html.Node, contentID string, conte
|
||||
i.addClass(node, "insertr")
|
||||
}
|
||||
|
||||
// InjectEditorAssets adds editor JavaScript to HTML document
|
||||
// InjectEditorAssets adds editor JavaScript to HTML document and injects demo gate if needed
|
||||
func (i *Injector) InjectEditorAssets(doc *html.Node, isDevelopment bool, libraryScript string) {
|
||||
// TODO: Implement script injection strategy when we have CDN hosting
|
||||
// For now, script injection is disabled since HTML files should include their own script tags
|
||||
// Future options:
|
||||
// 1. Inject CDN script tag: <script src="https://cdn.jsdelivr.net/npm/@insertr/lib@1.0.0/dist/insertr.js"></script>
|
||||
// 2. Inject local script tag for development: <script src="/insertr/insertr.js"></script>
|
||||
// 3. Continue with inline injection for certain use cases
|
||||
// Inject demo gate if no gates exist and add script for functionality
|
||||
if isDevelopment {
|
||||
i.InjectDemoGateIfNeeded(doc)
|
||||
i.InjectEditorScript(doc)
|
||||
}
|
||||
|
||||
// Currently disabled to avoid duplicate scripts
|
||||
return
|
||||
// TODO: Implement CDN script injection for production
|
||||
// Production options:
|
||||
// 1. Inject CDN script tag: <script src="https://cdn.jsdelivr.net/npm/@insertr/lib@1.0.0/dist/insertr.js"></script>
|
||||
}
|
||||
|
||||
// findHeadElement finds the <head> element in the document
|
||||
@@ -310,3 +310,196 @@ type ElementWithID struct {
|
||||
Element *Element
|
||||
ContentID string
|
||||
}
|
||||
|
||||
// InjectDemoGateIfNeeded injects a demo gate element if no .insertr-gate elements exist
|
||||
func (i *Injector) InjectDemoGateIfNeeded(doc *html.Node) {
|
||||
// Check if any .insertr-gate elements already exist
|
||||
if i.hasInsertrGate(doc) {
|
||||
return
|
||||
}
|
||||
|
||||
// Find the body element
|
||||
bodyNode := i.findBodyElement(doc)
|
||||
if bodyNode == nil {
|
||||
log.Printf("Warning: Could not find body element to inject demo gate")
|
||||
return
|
||||
}
|
||||
|
||||
// Create demo gate HTML structure
|
||||
gateHTML := `<div class="insertr-demo-gate" style="position: fixed; top: 20px; right: 20px; z-index: 9999; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
|
||||
<button class="insertr-gate insertr-demo-gate-btn" style="background: #4f46e5; color: white; border: none; padding: 10px 16px; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer; box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3); transition: all 0.2s ease; display: flex; align-items: center; gap: 8px; user-select: none;" onmouseover="this.style.background='#4338ca'; this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 16px rgba(79, 70, 229, 0.4)'" onmouseout="this.style.background='#4f46e5'; this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 12px rgba(79, 70, 229, 0.3)'">
|
||||
<span style="font-size: 16px;">✏️</span>
|
||||
<span>Edit Site</span>
|
||||
</button>
|
||||
</div>`
|
||||
|
||||
// Parse the gate HTML and inject it into the body
|
||||
gateDoc, err := html.Parse(strings.NewReader(gateHTML))
|
||||
if err != nil {
|
||||
log.Printf("Error parsing demo gate HTML: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Extract and inject the gate element
|
||||
if gateDiv := i.extractElementByClass(gateDoc, "insertr-demo-gate"); gateDiv != nil {
|
||||
if gateDiv.Parent != nil {
|
||||
gateDiv.Parent.RemoveChild(gateDiv)
|
||||
}
|
||||
bodyNode.AppendChild(gateDiv)
|
||||
log.Printf("✅ Demo gate injected: Edit button added to top-right corner")
|
||||
}
|
||||
}
|
||||
|
||||
// InjectEditorScript injects the insertr.js library and initialization script
|
||||
func (i *Injector) InjectEditorScript(doc *html.Node) {
|
||||
// Find the head element for the script tag
|
||||
headNode := i.findHeadElement(doc)
|
||||
if headNode == nil {
|
||||
log.Printf("Warning: Could not find head element to inject editor script")
|
||||
return
|
||||
}
|
||||
|
||||
// Create script element that loads insertr.js from our server
|
||||
scriptHTML := fmt.Sprintf(`<script src="http://localhost:8080/insertr.js"></script>
|
||||
<script type="text/javascript">
|
||||
// Initialize insertr for demo sites
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
if (typeof window.Insertr !== 'undefined') {
|
||||
console.log('✅ Insertr library loaded successfully');
|
||||
|
||||
// The library has auto-initialization, but we can force initialization
|
||||
// with our demo configuration
|
||||
window.Insertr.init({
|
||||
siteId: '%s',
|
||||
apiEndpoint: 'http://localhost:8080/api/content',
|
||||
mockAuth: true, // Use mock authentication for demos
|
||||
debug: true
|
||||
});
|
||||
|
||||
console.log('✅ Insertr initialized for demo site with config:', {
|
||||
siteId: '%s',
|
||||
apiEndpoint: 'http://localhost:8080/api/content',
|
||||
mockAuth: true
|
||||
});
|
||||
} else {
|
||||
console.error('❌ Insertr library failed to load');
|
||||
|
||||
// Fallback for demo gates if library fails
|
||||
const gates = document.querySelectorAll('.insertr-gate');
|
||||
gates.forEach(gate => {
|
||||
gate.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
alert('🚧 Insertr library not loaded\\n\\nPlease run "just build-lib" to build the library first.');
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>`, i.siteID, i.siteID)
|
||||
|
||||
// Parse and inject the script
|
||||
scriptDoc, err := html.Parse(strings.NewReader(scriptHTML))
|
||||
if err != nil {
|
||||
log.Printf("Error parsing editor script HTML: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Extract and inject all script elements
|
||||
if err := i.injectAllScriptElements(scriptDoc, headNode); err != nil {
|
||||
log.Printf("Error injecting script elements: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("✅ Insertr.js library and initialization script injected")
|
||||
}
|
||||
|
||||
// injectAllScriptElements finds and injects all script elements from parsed HTML
|
||||
func (i *Injector) injectAllScriptElements(doc *html.Node, targetNode *html.Node) error {
|
||||
scripts := i.findAllScriptElements(doc)
|
||||
|
||||
for _, script := range scripts {
|
||||
// Remove from original parent
|
||||
if script.Parent != nil {
|
||||
script.Parent.RemoveChild(script)
|
||||
}
|
||||
// Add to target node
|
||||
targetNode.AppendChild(script)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// findAllScriptElements recursively finds all script elements
|
||||
func (i *Injector) findAllScriptElements(node *html.Node) []*html.Node {
|
||||
var scripts []*html.Node
|
||||
|
||||
if node.Type == html.ElementNode && node.Data == "script" {
|
||||
scripts = append(scripts, node)
|
||||
}
|
||||
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
childScripts := i.findAllScriptElements(child)
|
||||
scripts = append(scripts, childScripts...)
|
||||
}
|
||||
|
||||
return scripts
|
||||
}
|
||||
|
||||
// hasInsertrGate checks if document has .insertr-gate elements
|
||||
func (i *Injector) hasInsertrGate(node *html.Node) bool {
|
||||
if node.Type == html.ElementNode {
|
||||
for _, attr := range node.Attr {
|
||||
if attr.Key == "class" && strings.Contains(attr.Val, "insertr-gate") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
if i.hasInsertrGate(child) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// findBodyElement finds the <body> element
|
||||
func (i *Injector) findBodyElement(node *html.Node) *html.Node {
|
||||
if node.Type == html.ElementNode && node.Data == "body" {
|
||||
return node
|
||||
}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
if result := i.findBodyElement(child); result != nil {
|
||||
return result
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractElementByClass finds element with specific class
|
||||
func (i *Injector) extractElementByClass(node *html.Node, className string) *html.Node {
|
||||
if node.Type == html.ElementNode {
|
||||
for _, attr := range node.Attr {
|
||||
if attr.Key == "class" && strings.Contains(attr.Val, className) {
|
||||
return node
|
||||
}
|
||||
}
|
||||
}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
if result := i.extractElementByClass(child, className); result != nil {
|
||||
return result
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractElementByTag finds element with specific tag
|
||||
func (i *Injector) extractElementByTag(node *html.Node, tagName string) *html.Node {
|
||||
if node.Type == html.ElementNode && node.Data == tagName {
|
||||
return node
|
||||
}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
if result := i.extractElementByTag(child, tagName); result != nil {
|
||||
return result
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user