import overlayStyles from './overlay.css';
import { injectStyle } from '../styles';
import { HotReloadFlash, SlotFlash } from '../slots/flash';
export const HERB_LINTER_EVENT = 'herb:dev-tools:linter'
export interface HerbOverlayOptions {
projectPath?: string;
autoInit?: boolean;
devServerClient?: { applyConnectionDot(): void } | null;
onMenuOpen?: () => void;
onReinitialize?: () => void;
isRuntimePanelVisible?: () => boolean;
onRuntimePanelToggle?: (visible: boolean) => void;
onHotReloadingToggle?: (enabled: boolean) => void;
reportedFor?: (template: string) => { count: number, tone: string } | null;
measuredFor?: (template: string) => string | null;
}
export class HerbOverlay {
private showingERB = false;
private showingERBOutlines = false;
private showingERBHoverReveal = false;
private showingTooltips = true;
private showingViewOutlines = false;
private showingPartialOutlines = false;
private showingComponentOutlines = false;
private showingOutlineMetrics = false;
private menuOpen = false;
private projectPath = '';
private preferredEditor = 'auto';
private defaultEditorFromServer = 'vscode';
private currentlyHoveredERBElement: HTMLElement | null = null;
private destroyed = false;
private styleElement: HTMLStyleElement | null = null;
private slotFlash = new SlotFlash();
private hotReloadFlash = new HotReloadFlash();
private flashingUpdates = true;
private flashingHotReload = true;
private showingSlotUpdates = false;
private runningLinter = true;
private hotReloading = true;
private static readonly SETTINGS_KEY = 'herb-dev-tools-settings';
private static readonly EDITOR_OPTIONS = [
{ value: 'auto', label: 'Auto (from server via RAILS_EDITOR or EDITOR)' },
{ value: 'atom', label: 'Atom' },
{ value: 'cursor', label: 'Cursor' },
{ value: 'emacs', label: 'Emacs' },
{ value: 'idea', label: 'IntelliJ IDEA' },
{ value: 'macvim', label: 'MacVim' },
{ value: 'nova', label: 'Nova' },
{ value: 'nvim', label: 'Neovim' },
{ value: 'rubymine', label: 'RubyMine' },
{ value: 'sublime', label: 'Sublime Text' },
{ value: 'textmate', label: 'TextMate' },
{ value: 'vim', label: 'Vim' },
{ value: 'vscode', label: 'Visual Studio Code' },
{ value: 'vscodium', label: 'VSCodium' },
{ value: 'windsurf', label: 'Windsurf' },
{ value: 'zed', label: 'Zed' },
];
constructor(private options: HerbOverlayOptions = {}) {
this.styleElement = injectStyle('overlay', overlayStyles);
if (options.autoInit !== false) {
this.init();
}
}
private syncConnectionDot() {
this.options.devServerClient?.applyConnectionDot();
}
private init() {
this.loadProjectPath();
this.loadDefaultEditor();
this.loadSettings();
this.injectMenu();
this.syncConnectionDot();
this.setupMenuToggle();
this.setupToggleSwitches();
this.setupEditorDropdown();
this.setupTurboListeners();
this.applySettings();
document.addEventListener('click', this.handleDocumentClick);
}
public destroy() {
if (this.destroyed) {
return;
}
this.destroyed = true;
document.removeEventListener('click', this.handleDocumentClick);
document.removeEventListener('turbo:load', this.handleTurboNavigation);
document.removeEventListener('turbo:render', this.handleTurboNavigation);
document.removeEventListener('turbo:visit', this.handleTurboNavigation);
this.slotFlash.stop();
this.hotReloadFlash.stop();
document.querySelector('.herb-floating-menu')?.remove();
this.styleElement?.remove();
this.styleElement = null;
}
private loadProjectPath() {
if (this.options.projectPath) {
this.projectPath = this.options.projectPath;
return;
}
const metaTag = document.querySelector('meta[name="herb-project-path"]') as HTMLMetaElement;
if (metaTag?.content) {
this.projectPath = metaTag.content;
}
}
private loadDefaultEditor() {
const metaTag = document.querySelector('meta[name="herb-default-editor"]') as HTMLMetaElement;
if (metaTag?.content) {
const defaultEditor = metaTag.content.toLowerCase();
const isValidEditor = HerbOverlay.EDITOR_OPTIONS.some(option => option.value === defaultEditor);
if (isValidEditor) {
this.defaultEditorFromServer = defaultEditor;
}
}
}
private loadSettings() {
const savedSettings = localStorage.getItem(HerbOverlay.SETTINGS_KEY);
if (savedSettings) {
try {
const settings = JSON.parse(savedSettings);
this.showingERB = settings.showingERB || false;
this.showingERBOutlines = settings.showingERBOutlines || false;
this.showingERBHoverReveal = settings.showingERBHoverReveal || false;
this.showingTooltips = settings.showingTooltips !== undefined ? settings.showingTooltips : true;
this.showingViewOutlines = settings.showingViewOutlines || false;
this.showingPartialOutlines = settings.showingPartialOutlines || false;
this.showingComponentOutlines = settings.showingComponentOutlines || false;
this.showingOutlineMetrics = settings.showingOutlineMetrics || false;
this.showingSlotUpdates = settings.showingSlotUpdates || false;
this.runningLinter = settings.runningLinter !== undefined ? settings.runningLinter : true;
this.hotReloading = settings.hotReloading !== undefined ? settings.hotReloading : true;
this.flashingHotReload = settings.flashingHotReload !== undefined ? settings.flashingHotReload : true;
this.flashingUpdates = settings.flashingUpdates !== undefined ? settings.flashingUpdates : true;
this.menuOpen = settings.menuOpen || false;
if (settings.preferredEditor) {
this.preferredEditor = settings.preferredEditor;
}
} catch (e) {
console.warn('Failed to load Herb dev tools settings:', e);
}
}
this.flashingUpdates = this.flashingUpdates && this.flashSubTogglesOn;
}
private get flashSubTogglesOn(): boolean {
return this.showingSlotUpdates || (this.options.devServerClient != null && this.flashingHotReload);
}
private saveSettings() {
const settings = {
showingERB: this.showingERB,
showingERBOutlines: this.showingERBOutlines,
showingERBHoverReveal: this.showingERBHoverReveal,
showingTooltips: this.showingTooltips,
showingViewOutlines: this.showingViewOutlines,
showingPartialOutlines: this.showingPartialOutlines,
showingComponentOutlines: this.showingComponentOutlines,
showingOutlineMetrics: this.showingOutlineMetrics,
showingSlotUpdates: this.showingSlotUpdates,
runningLinter: this.runningLinter,
hotReloading: this.hotReloading,
flashingHotReload: this.flashingHotReload,
flashingUpdates: this.flashingUpdates,
menuOpen: this.menuOpen,
preferredEditor: this.preferredEditor
};
localStorage.setItem(HerbOverlay.SETTINGS_KEY, JSON.stringify(settings));
this.updateMenuButtonState();
}
private toggleHotReloading(enabled: boolean) {
this.hotReloading = enabled;
this.saveSettings();
this.options.onHotReloadingToggle?.(enabled);
}
private toggleHotReloadFlashes(show?: boolean) {
this.flashingHotReload = show !== undefined ? show : !this.flashingHotReload;
if (this.flashingUpdates && this.flashingHotReload) this.hotReloadFlash.start();
else this.hotReloadFlash.stop();
this.saveSettings();
}
private toggleFlashUpdates(show?: boolean) {
this.flashingUpdates = show !== undefined ? show : !this.flashingUpdates;
if (this.flashingUpdates && !this.flashSubTogglesOn) {
const toggleSlotUpdatesSwitch = document.getElementById('herbToggleSlotUpdates') as HTMLInputElement | null;
const toggleHotReloadFlashesSwitch = document.getElementById('herbToggleHotReloadFlashes') as HTMLInputElement | null;
this.showingSlotUpdates = true;
if (toggleSlotUpdatesSwitch) toggleSlotUpdatesSwitch.checked = true;
if (this.options.devServerClient != null) {
this.flashingHotReload = true;
if (toggleHotReloadFlashesSwitch) toggleHotReloadFlashesSwitch.checked = true;
}
}
this.toggleSlotUpdates(this.showingSlotUpdates);
this.toggleHotReloadFlashes(this.flashingHotReload);
this.updateNestedToggleVisibility();
this.saveSettings();
}
private syncFlashUpdatesToggle() {
if (this.flashSubTogglesOn) {
return;
}
this.flashingUpdates = false;
const toggleFlashUpdatesSwitch = document.getElementById('herbToggleFlashUpdates') as HTMLInputElement | null;
if (toggleFlashUpdatesSwitch) toggleFlashUpdatesSwitch.checked = false;
this.updateNestedToggleVisibility();
this.saveSettings();
}
private updateMenuButtonState() {
const menuTrigger = document.getElementById('herbMenuTrigger');
if (menuTrigger) {
const hasActiveOptions = this.showingERB || this.showingERBOutlines || this.showingViewOutlines || this.showingPartialOutlines || this.showingComponentOutlines;
if (hasActiveOptions) {
menuTrigger.classList.add('has-active-options');
} else {
menuTrigger.classList.remove('has-active-options');
}
}
}
private runtimePanelToggleHTML() {
if (!this.options.isRuntimePanelVisible) {
return '';
}
return `
`;
}
public syncRuntimePanelToggle() {
const toggle = document.getElementById('herbToggleRuntimePanel') as HTMLInputElement | null;
if (toggle && this.options.isRuntimePanelVisible) {
toggle.checked = this.options.isRuntimePanelVisible();
}
}
private injectMenu() {
const existingMenu = document.querySelector('.herb-floating-menu');
if (existingMenu) {
return;
}
const devServer = this.options.devServerClient != null;
const menuHTML = `
`;
document.body.insertAdjacentHTML('beforeend', menuHTML);
}
private applySettings() {
this.options.onHotReloadingToggle?.(this.hotReloading);
this.toggleViewOutlines(this.showingViewOutlines);
this.togglePartialOutlines(this.showingPartialOutlines);
this.toggleComponentOutlines(this.showingComponentOutlines);
this.toggleERBTags(this.showingERB);
this.toggleERBOutlines(this.showingERBOutlines);
this.toggleSlotUpdates(this.showingSlotUpdates);
this.toggleHotReloadFlashes(this.flashingHotReload);
this.updateNestedToggleVisibility();
const menuTrigger = document.getElementById('herbMenuTrigger');
const menuPanel = document.getElementById('herbMenuPanel');
if (menuTrigger && menuPanel && this.menuOpen) {
menuTrigger.classList.add('active');
menuPanel.classList.add('open');
}
}
private handleMenuTriggerClick = () => {
const menuTrigger = document.getElementById('herbMenuTrigger');
const menuPanel = document.getElementById('herbMenuPanel');
if (!menuTrigger || !menuPanel) {
return;
}
this.menuOpen = !this.menuOpen;
if (this.menuOpen) {
this.options.onMenuOpen?.();
this.syncRuntimePanelToggle();
menuTrigger.classList.add('active');
menuPanel.classList.add('open');
} else {
menuTrigger.classList.remove('active');
menuPanel.classList.remove('open');
}
this.saveSettings();
}
private setupMenuToggle() {
const menuTrigger = document.getElementById('herbMenuTrigger');
const menuPanel = document.getElementById('herbMenuPanel');
if (menuTrigger && menuPanel) {
menuTrigger.removeEventListener('click', this.handleMenuTriggerClick);
menuTrigger.addEventListener('click', this.handleMenuTriggerClick);
}
}
private handleDocumentClick = (event: MouseEvent) => {
if (!this.menuOpen) {
return;
}
const target = event.target as HTMLElement;
const floatingMenu = document.querySelector('.herb-floating-menu');
if (floatingMenu && !floatingMenu.contains(target)) {
this.closeMenu();
}
}
public closeMenu() {
this.menuOpen = false;
document.getElementById('herbMenuTrigger')?.classList.remove('active');
document.getElementById('herbMenuPanel')?.classList.remove('open');
this.saveSettings();
}
private handleTurboNavigation = () => {
this.reinitializeAfterNavigation();
}
private setupTurboListeners() {
document.addEventListener('turbo:load', this.handleTurboNavigation);
document.addEventListener('turbo:render', this.handleTurboNavigation);
document.addEventListener('turbo:visit', this.handleTurboNavigation);
}
private reinitializeAfterNavigation() {
this.injectMenu();
this.syncConnectionDot();
this.setupMenuToggle();
this.setupToggleSwitches();
this.setupEditorDropdown();
this.applySettings();
this.updateMenuButtonState();
this.options.onReinitialize?.();
}
private setupToggleSwitches() {
const toggleHotReloadingSwitch = document.getElementById('herbToggleHotReloading') as HTMLInputElement | null;
if (toggleHotReloadingSwitch) {
toggleHotReloadingSwitch.checked = this.hotReloading;
toggleHotReloadingSwitch.addEventListener('change', () => {
this.toggleHotReloading(toggleHotReloadingSwitch.checked);
});
}
const toggleFlashUpdatesSwitch = document.getElementById('herbToggleFlashUpdates') as HTMLInputElement | null;
if (toggleFlashUpdatesSwitch) {
toggleFlashUpdatesSwitch.checked = this.flashingUpdates;
toggleFlashUpdatesSwitch.addEventListener('change', () => {
this.toggleFlashUpdates(toggleFlashUpdatesSwitch.checked);
});
}
const toggleHotReloadFlashesSwitch = document.getElementById('herbToggleHotReloadFlashes') as HTMLInputElement | null;
if (toggleHotReloadFlashesSwitch) {
toggleHotReloadFlashesSwitch.checked = this.flashingHotReload;
toggleHotReloadFlashesSwitch.addEventListener('change', () => {
this.toggleHotReloadFlashes(toggleHotReloadFlashesSwitch.checked);
this.syncFlashUpdatesToggle();
});
}
const toggleOutlineMetricsSwitch = document.getElementById('herbToggleOutlineMetrics') as HTMLInputElement;
if (toggleOutlineMetricsSwitch) {
toggleOutlineMetricsSwitch.checked = this.showingOutlineMetrics;
toggleOutlineMetricsSwitch.addEventListener('change', () => {
this.toggleOutlineMetrics(toggleOutlineMetricsSwitch.checked);
});
}
const toggleViewOutlinesSwitch = document.getElementById('herbToggleViewOutlines') as HTMLInputElement;
if (toggleViewOutlinesSwitch) {
toggleViewOutlinesSwitch.checked = this.showingViewOutlines;
toggleViewOutlinesSwitch.addEventListener('change', () => {
this.toggleViewOutlines(toggleViewOutlinesSwitch.checked);
});
}
const togglePartialOutlinesSwitch = document.getElementById('herbTogglePartialOutlines') as HTMLInputElement;
if (togglePartialOutlinesSwitch) {
togglePartialOutlinesSwitch.checked = this.showingPartialOutlines;
togglePartialOutlinesSwitch.addEventListener('change', () => {
this.togglePartialOutlines(togglePartialOutlinesSwitch.checked);
});
}
const toggleComponentOutlinesSwitch = document.getElementById('herbToggleComponentOutlines') as HTMLInputElement;
if (toggleComponentOutlinesSwitch) {
toggleComponentOutlinesSwitch.checked = this.showingComponentOutlines;
toggleComponentOutlinesSwitch.addEventListener('change', () => {
this.toggleComponentOutlines(toggleComponentOutlinesSwitch.checked);
});
}
const toggleERBSwitch = document.getElementById('herbToggleERB') as HTMLInputElement;
const toggleERBOutlinesSwitch = document.getElementById('herbToggleERBOutlines') as HTMLInputElement;
if (toggleERBSwitch) {
toggleERBSwitch.checked = this.showingERB;
toggleERBSwitch.addEventListener('change', () => {
if (toggleERBSwitch.checked && toggleERBOutlinesSwitch) {
toggleERBOutlinesSwitch.checked = false;
this.toggleERBOutlines(false);
}
this.toggleERBTags(toggleERBSwitch.checked);
});
}
const toggleLinterSwitch = document.getElementById('herbToggleLinter') as HTMLInputElement;
if (toggleLinterSwitch) {
toggleLinterSwitch.checked = this.runningLinter;
toggleLinterSwitch.addEventListener('change', () => {
this.toggleLinter(toggleLinterSwitch.checked);
});
}
const toggleSlotUpdatesSwitch = document.getElementById('herbToggleSlotUpdates') as HTMLInputElement;
if (toggleSlotUpdatesSwitch) {
toggleSlotUpdatesSwitch.checked = this.showingSlotUpdates;
toggleSlotUpdatesSwitch.addEventListener('change', () => {
this.toggleSlotUpdates(toggleSlotUpdatesSwitch.checked);
this.syncFlashUpdatesToggle();
});
}
const toggleRuntimePanelSwitch = document.getElementById('herbToggleRuntimePanel') as HTMLInputElement;
if (toggleRuntimePanelSwitch) {
this.syncRuntimePanelToggle();
toggleRuntimePanelSwitch.addEventListener('change', () => {
this.options.onRuntimePanelToggle?.(toggleRuntimePanelSwitch.checked);
});
}
if (toggleERBOutlinesSwitch) {
toggleERBOutlinesSwitch.checked = this.showingERBOutlines;
toggleERBOutlinesSwitch.addEventListener('change', () => {
if (toggleERBOutlinesSwitch.checked && toggleERBSwitch) {
toggleERBSwitch.checked = false;
this.toggleERBTags(false);
}
this.toggleERBOutlines(toggleERBOutlinesSwitch.checked);
this.updateNestedToggleVisibility();
});
} else {
console.warn('ERB outlines toggle switch not found');
}
const toggleERBHoverRevealSwitch = document.getElementById('herbToggleERBHoverReveal') as HTMLInputElement;
if (toggleERBHoverRevealSwitch) {
toggleERBHoverRevealSwitch.checked = this.showingERBHoverReveal;
toggleERBHoverRevealSwitch.addEventListener('change', () => {
this.toggleERBHoverReveal(toggleERBHoverRevealSwitch.checked);
});
}
const toggleTooltipsSwitch = document.getElementById('herbToggleTooltips') as HTMLInputElement;
if (toggleTooltipsSwitch) {
toggleTooltipsSwitch.checked = this.showingTooltips;
toggleTooltipsSwitch.addEventListener('change', () => {
this.toggleTooltips(toggleTooltipsSwitch.checked);
});
}
this.updateNestedToggleVisibility();
const disableAllBtn = document.getElementById('herbDisableAll') as HTMLButtonElement;
if (disableAllBtn) {
disableAllBtn.addEventListener('click', () => {
this.disableAll();
});
}
}
private setupEditorDropdown() {
const editorSelect = document.getElementById('herbEditorSelect') as HTMLSelectElement;
if (editorSelect) {
const autoOption = editorSelect.querySelector('option[value="auto"]') as HTMLOptionElement;
if (autoOption) {
const editorLabel = HerbOverlay.EDITOR_OPTIONS.find(opt => opt.value === this.defaultEditorFromServer)?.label || this.defaultEditorFromServer;
const metaTag = document.querySelector('meta[name="herb-default-editor"]') as HTMLMetaElement;
if (metaTag?.content) {
autoOption.textContent = `Auto (from server): ${editorLabel}`;
} else {
autoOption.textContent = `Auto (default): ${editorLabel}`;
}
}
editorSelect.value = this.preferredEditor;
editorSelect.addEventListener('change', () => {
this.preferredEditor = editorSelect.value;
this.saveSettings();
});
}
}
private toggleViewOutlines(show?: boolean) {
this.showingViewOutlines = show !== undefined ? show : !this.showingViewOutlines;
const viewOutlines = document.querySelectorAll('[data-herb-debug-outline-type="view"], [data-herb-debug-outline-type*="view"]');
viewOutlines.forEach((outline) => {
const element = outline as HTMLElement;
if (this.showingViewOutlines) {
element.style.outline = '2px dotted #3b82f6';
element.style.outlineOffset = element.tagName.toLowerCase() === 'html' ? '-2px' : '2px';
element.classList.add('show-outline');
this.createOverlayLabel(element, 'view');
} else {
element.style.outline = 'none';
element.style.outlineOffset = '0';
element.classList.remove('show-outline');
this.removeOverlayLabel(element);
}
});
this.saveSettings();
}
private togglePartialOutlines(show?: boolean) {
this.showingPartialOutlines = show !== undefined ? show : !this.showingPartialOutlines;
const partialOutlines = document.querySelectorAll('[data-herb-debug-outline-type="partial"], [data-herb-debug-outline-type*="partial"]');
partialOutlines.forEach((outline) => {
const element = outline as HTMLElement;
if (this.showingPartialOutlines) {
element.style.outline = '2px dotted #10b981';
element.style.outlineOffset = element.tagName.toLowerCase() === 'html' ? '-2px' : '2px';
element.classList.add('show-outline');
this.createOverlayLabel(element, 'partial');
} else {
element.style.outline = 'none';
element.style.outlineOffset = '0';
element.classList.remove('show-outline');
this.removeOverlayLabel(element);
}
});
this.saveSettings();
}
private toggleComponentOutlines(show?: boolean) {
this.showingComponentOutlines = show !== undefined ? show : !this.showingComponentOutlines;
const componentOutlines = document.querySelectorAll('[data-herb-debug-outline-type="component"], [data-herb-debug-outline-type*="component"]');
componentOutlines.forEach((outline) => {
const element = outline as HTMLElement;
if (this.showingComponentOutlines) {
element.style.outline = '2px dotted #f59e0b';
element.style.outlineOffset = element.tagName.toLowerCase() === 'html' ? '-2px' : '2px';
element.classList.add('show-outline');
this.createOverlayLabel(element, 'component');
} else {
element.style.outline = 'none';
element.style.outlineOffset = '0';
element.classList.remove('show-outline');
this.removeOverlayLabel(element);
}
});
this.saveSettings();
}
private appendMeasurements(label: HTMLElement, relativePath: string) {
label.querySelector('.herb-overlay-label-measured')?.remove();
if (!this.showingOutlineMetrics) {
return;
}
const measured = this.options.measuredFor?.(relativePath) ?? null;
if (measured === null) {
return;
}
const chip = document.createElement('span');
chip.className = 'herb-overlay-label-measured';
chip.textContent = measured;
chip.title = `Measured for ${relativePath}`;
label.appendChild(chip);
}
private toggleOutlineMetrics(show?: boolean) {
this.showingOutlineMetrics = show !== undefined ? show : !this.showingOutlineMetrics;
document.querySelectorAll('.herb-overlay-label').forEach((label) => {
const element = label.parentElement;
const relativePath = element?.getAttribute('data-herb-debug-file-relative-path')
|| element?.getAttribute('data-herb-debug-file-name')
|| '';
this.appendMeasurements(label as HTMLElement, relativePath);
});
this.saveSettings();
}
private createOverlayLabel(element: HTMLElement, type: 'view' | 'partial' | 'component') {
if (element.querySelector(':scope > .herb-overlay-label')) {
return;
}
const shortName = element.getAttribute('data-herb-debug-file-name') || '';
const relativePath = element.getAttribute('data-herb-debug-file-relative-path') || shortName;
const fullPath = element.getAttribute('data-herb-debug-file-full-path') || relativePath;
const label = document.createElement('div');
const name = document.createElement('span');
label.className = 'herb-overlay-label';
label.setAttribute('data-label-setup', 'true');
name.className = 'herb-overlay-label-name';
name.textContent = shortName;
label.appendChild(name);
const reported = this.options.reportedFor?.(relativePath) ?? null;
if (reported !== null) {
const badge = document.createElement('span');
const word = reported.count === 1 ? 'diagnostic' : 'diagnostics';
badge.className = `herb-overlay-label-count herb-overlay-label-count-${reported.tone}`;
badge.textContent = String(reported.count);
badge.title = `${reported.count} ${word} reported for ${relativePath}`;
label.appendChild(badge);
}
this.appendMeasurements(label, relativePath);
label.addEventListener('mouseenter', () => {
name.textContent = relativePath;
document.querySelectorAll('.herb-overlay-label').forEach(otherLabel => {
(otherLabel as HTMLElement).style.zIndex = '1000';
});
label.style.zIndex = '1002';
});
label.addEventListener('mouseleave', () => {
name.textContent = shortName;
label.style.zIndex = '1000';
});
label.addEventListener('click', (e) => {
e.stopPropagation();
this.openFileInEditor(fullPath, 1, 1);
});
const shouldAttachToParent = element.getAttribute('data-herb-debug-attach-to-parent') === 'true';
if (shouldAttachToParent && element.parentElement) {
const parent = element.parentElement;
element.style.outline = 'none';
element.classList.remove('show-outline');
const outlineColor = type === 'component' ? '#f59e0b' : type === 'partial' ? '#10b981' : '#3b82f6';
parent.style.outline = `2px dotted ${outlineColor}`;
parent.style.outlineOffset = parent.tagName.toLowerCase() === 'html' ? '-2px' : '2px';
parent.classList.add('show-outline');
parent.setAttribute('data-herb-debug-attached-outline-type', type);
this.anchorLabel(parent);
label.style.position = 'absolute';
label.style.top = '0';
label.style.left = '0';
parent.appendChild(label);
return;
}
if (element.localName === 'html' || window.getComputedStyle(element).overflowY !== 'visible') {
label.style.top = '0';
}
this.anchorLabel(element);
element.appendChild(label);
}
private anchorLabel(host: HTMLElement) {
if (host === document.documentElement || host === document.body) return;
if (window.getComputedStyle(host).position !== 'static') return;
host.style.position = 'relative';
host.setAttribute('data-herb-debug-anchored', 'true');
}
private releaseLabel(host: HTMLElement) {
if (!host.hasAttribute('data-herb-debug-anchored')) return;
host.style.position = '';
host.removeAttribute('data-herb-debug-anchored');
}
private removeOverlayLabel(element: HTMLElement) {
const shouldAttachToParent = element.getAttribute('data-herb-debug-attach-to-parent') === 'true';
if (shouldAttachToParent && element.parentElement) {
const parent = element.parentElement;
const label = parent.querySelector(':scope > .herb-overlay-label');
if (label) {
label.remove();
}
parent.style.outline = 'none';
parent.style.outlineOffset = '0';
parent.classList.remove('show-outline');
parent.removeAttribute('data-herb-debug-attached-outline-type');
this.releaseLabel(parent);
} else {
const label = element.querySelector(':scope > .herb-overlay-label');
if (label) {
label.remove();
}
this.releaseLabel(element);
}
}
private resetShowingERB() {
const elements = document.querySelectorAll('[data-herb-debug-showing-erb')
elements.forEach(element => {
const originalContent = element.getAttribute('data-herb-debug-original') || "";
element.innerHTML = originalContent;
element.removeAttribute("data-herb-debug-showing-erb")
})
}
private toggleERBTags(show?: boolean) {
this.showingERB = show !== undefined ? show : !this.showingERB;
const erbOutputs = document.querySelectorAll('[data-herb-debug-outline-type*="erb-output"]');
erbOutputs.forEach((element) => {
const erbCode = element.getAttribute('data-herb-debug-erb');
if (this.showingERB && erbCode) {
// this.resetShowingERB()
if (!element.hasAttribute('data-herb-debug-original')) {
element.setAttribute('data-herb-debug-original', element.innerHTML);
}
element.textContent = erbCode;
element.setAttribute("data-herb-debug-showing-erb", "true")
element.style.background = '#f3e8ff';
element.style.color = '#7c3aed';
if (this.showingTooltips) {
this.addTooltipHoverHandler(element);
}
} else {
const originalContent = element.getAttribute('data-herb-debug-original') || "";
if (element && element.hasAttribute("data-herb-debug-showing-erb")) {
element.innerHTML = originalContent;
element.removeAttribute("data-herb-debug-showing-erb")
}
element.style.background = 'transparent';
element.style.color = 'inherit';
this.removeTooltipHoverHandler(element);
this.removeHoverTooltip(element);
}
});
this.saveSettings();
}
private toggleLinter(run?: boolean) {
this.runningLinter = run !== undefined ? run : !this.runningLinter;
this.saveSettings();
document.dispatchEvent(new CustomEvent(HERB_LINTER_EVENT, { detail: { enabled: this.runningLinter } }));
}
get linterEnabled(): boolean {
return this.runningLinter;
}
private toggleSlotUpdates(show?: boolean) {
this.showingSlotUpdates = show !== undefined ? show : !this.showingSlotUpdates;
if (this.flashingUpdates && this.showingSlotUpdates) this.slotFlash.start();
else this.slotFlash.stop();
this.saveSettings();
}
private toggleERBOutlines(show?: boolean) {
this.showingERBOutlines = show !== undefined ? show : !this.showingERBOutlines;
this.clearCurrentHoveredERB();
const erbOutputs = document.querySelectorAll('[data-herb-debug-outline-type*="erb-output"]');
erbOutputs.forEach(element => {
const inserted = element.hasAttribute("data-herb-debug-inserted")
const needsWrapperToggled = (inserted && !element.children[0])
const realElement = (element.children[0] as HTMLElement) || element
if (this.showingERBOutlines) {
realElement.style.outline = '2px dotted #a78bfa';
realElement.style.outlineOffset = '1px';
if (needsWrapperToggled) {
element.style.display = 'inline';
}
if (this.showingTooltips) {
this.addTooltipHoverHandler(element);
}
if (this.showingERBHoverReveal) {
this.addERBHoverReveal(element);
}
} else {
realElement.style.outline = 'none';
realElement.style.outlineOffset = '0';
if (needsWrapperToggled) {
element.style.display = 'contents';
}
this.removeTooltipHoverHandler(element);
this.removeHoverTooltip(element);
this.removeERBHoverReveal(element);
}
});
this.saveSettings();
}
private updateNestedToggleVisibility() {
const nestedToggle = document.getElementById('herbERBHoverRevealNested');
const tooltipsNestedToggle = document.getElementById('herbTooltipsNested');
const slotUpdatesNestedToggle = document.getElementById('herbSlotUpdatesNested');
const hotReloadFlashesNestedToggle = document.getElementById('herbHotReloadFlashesItem');
if (slotUpdatesNestedToggle) {
slotUpdatesNestedToggle.style.display = this.flashingUpdates ? 'block' : 'none';
}
if (hotReloadFlashesNestedToggle) {
hotReloadFlashesNestedToggle.style.display = this.flashingUpdates ? 'block' : 'none';
}
if (nestedToggle) {
nestedToggle.style.display = this.showingERBOutlines ? 'block' : 'none';
}
if (tooltipsNestedToggle) {
tooltipsNestedToggle.style.display = this.showingERBOutlines ? 'block' : 'none';
}
}
private toggleERBHoverReveal(show?: boolean) {
this.showingERBHoverReveal = show !== undefined ? show : !this.showingERBHoverReveal;
if (this.showingERBHoverReveal && this.showingTooltips) {
this.toggleTooltips(false);
const toggleTooltipsSwitch = document.getElementById('herbToggleTooltips') as HTMLInputElement;
if (toggleTooltipsSwitch) {
toggleTooltipsSwitch.checked = false;
}
}
this.clearCurrentHoveredERB();
const erbOutputs = document.querySelectorAll('[data-herb-debug-outline-type*="erb-output"]');
erbOutputs.forEach((el) => {
const element = el as HTMLElement;
this.removeERBHoverReveal(element);
if (this.showingERBHoverReveal && this.showingERBOutlines) {
this.addERBHoverReveal(element);
}
});
this.saveSettings();
}
private clearCurrentHoveredERB() {
if (this.currentlyHoveredERBElement) {
const handlers = (this.currentlyHoveredERBElement as any)._erbHoverHandlers;
if (handlers) {
handlers.hideERBCode();
}
this.currentlyHoveredERBElement = null;
}
}
private handleRevealedERBClick = (event: Event) => {
event.stopPropagation();
event.preventDefault();
const element = event.currentTarget as HTMLElement;
if (!element) return;
const fullPath = element.getAttribute('data-herb-debug-file-full-path');
const line = element.getAttribute('data-herb-debug-line');
const column = element.getAttribute('data-herb-debug-column');
if (fullPath) {
this.openFileInEditor(
fullPath,
line ? parseInt(line) : 1,
column ? parseInt(column) : 1
);
}
}
private addERBHoverReveal(element: HTMLElement) {
const erbCode = element.getAttribute('data-herb-debug-erb');
if (!erbCode) return;
this.removeERBHoverReveal(element);
if (!element.hasAttribute('data-herb-debug-original')) {
element.setAttribute('data-herb-debug-original', element.innerHTML);
}
const showERBCode = () => {
if (!this.showingERBHoverReveal || !this.showingERBOutlines) {
return;
}
if (this.currentlyHoveredERBElement === element) {
return;
}
this.clearCurrentHoveredERB();
this.currentlyHoveredERBElement = element;
element.style.background = '#f3e8ff';
element.style.color = '#7c3aed';
element.style.fontFamily = 'inherit';
element.style.fontSize = 'inherit';
element.style.borderRadius = '3px';
element.style.cursor = 'pointer';
element.textContent = erbCode;
element.addEventListener('click', this.handleRevealedERBClick);
};
const hideERBCode = () => {
if (this.currentlyHoveredERBElement === element) {
this.currentlyHoveredERBElement = null;
}
const originalContent = element.getAttribute('data-herb-debug-original');
if (originalContent) {
element.innerHTML = originalContent;
}
element.style.background = 'transparent';
element.style.color = 'inherit';
element.style.fontFamily = 'inherit';
element.style.fontSize = 'inherit';
element.style.borderRadius = '0';
element.style.cursor = 'default';
element.removeEventListener('click', this.handleRevealedERBClick);
};
(element as any)._erbHoverHandlers = { showERBCode, hideERBCode };
element.addEventListener('mouseenter', showERBCode);
}
private removeERBHoverReveal(element: HTMLElement) {
const handlers = (element as any)._erbHoverHandlers;
if (handlers) {
element.removeEventListener('mouseenter', handlers.showERBCode);
delete (element as any)._erbHoverHandlers;
handlers.hideERBCode();
}
}
private createHoverTooltip(element: HTMLElement, elementForPosition: HTMLElement) {
this.removeHoverTooltip(element);
const relativePath = element.getAttribute('data-herb-debug-file-relative-path') || element.getAttribute('data-herb-debug-file-name') || '';
const fullPath = element.getAttribute('data-herb-debug-file-full-path') || relativePath;
const line = element.getAttribute('data-herb-debug-line') || '';
const column = element.getAttribute('data-herb-debug-column') || '';
const erb = element.getAttribute('data-herb-debug-erb') || '';
if (!relativePath || !erb) return;
const tooltip = document.createElement('div');
tooltip.className = 'herb-tooltip';
tooltip.innerHTML = `
${relativePath}:${line}:${column}
${erb}
`;
let hideTimeout: number | null = null;
const showTooltip = () => {
if (hideTimeout) {
clearTimeout(hideTimeout);
hideTimeout = null;
}
tooltip.classList.add('visible');
};
const hideTooltip = () => {
hideTimeout = window.setTimeout(() => {
tooltip.classList.remove('visible');
}, 100);
};
element.addEventListener('mouseenter', showTooltip);
element.addEventListener('mouseleave', hideTooltip);
tooltip.addEventListener('mouseenter', showTooltip);
tooltip.addEventListener('mouseleave', hideTooltip);
const locationElement = tooltip.querySelector('.herb-location');
const openInEditor = (e: Event) => {
if ((e.target as HTMLElement).closest('.herb-copy-path-btn')) {
return;
}
e.preventDefault();
e.stopPropagation();
this.openFileInEditor(fullPath, parseInt(line), parseInt(column));
};
locationElement?.addEventListener('click', openInEditor);
const copyButton = tooltip.querySelector('.herb-copy-path-btn');
const copyFilePath = (e: Event) => {
e.preventDefault();
e.stopPropagation();
const textToCopy = `${relativePath}:${line}:${column}`;
navigator.clipboard.writeText(textToCopy).then(() => {
copyButton!.textContent = '✅';
setTimeout(() => {
copyButton!.textContent = '📋';
}, 1000);
}).catch((err) => {
console.error('Failed to copy file path:', err);
});
};
copyButton?.addEventListener('click', copyFilePath);
const positionTooltip = () => {
const elementRect = elementForPosition.getBoundingClientRect();
const viewportHeight = window.innerHeight;
const viewportWidth = window.innerWidth;
tooltip.style.position = 'fixed';
tooltip.style.left = '0';
tooltip.style.top = '0';
tooltip.style.transform = 'none';
tooltip.style.bottom = 'auto';
const actualTooltipRect = tooltip.getBoundingClientRect();
const tooltipWidth = actualTooltipRect.width;
const tooltipHeight = actualTooltipRect.height;
let left = elementRect.left + (elementRect.width / 2) - (tooltipWidth / 2);
let top = elementRect.top - tooltipHeight - 8;
if (left < 8) {
left = 8;
} else if (left + tooltipWidth > viewportWidth - 8) {
left = viewportWidth - tooltipWidth - 8;
}
if (top < 8) {
top = elementRect.bottom + 8;
if (top + tooltipHeight > viewportHeight - 8) {
top = Math.max(8, (viewportHeight - tooltipHeight) / 2);
}
}
if (top + tooltipHeight > viewportHeight - 8) {
top = viewportHeight - tooltipHeight - 8;
}
tooltip.style.position = 'fixed';
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
tooltip.style.transform = 'none';
tooltip.style.bottom = 'auto';
};
(element as any)._tooltipHandlers = { showTooltip, hideTooltip, openInEditor, copyFilePath, positionTooltip };
(tooltip as any)._tooltipHandlers = { showTooltip, hideTooltip };
element.appendChild(tooltip);
setTimeout(positionTooltip, 0);
window.addEventListener('scroll', positionTooltip, { passive: true });
window.addEventListener('resize', positionTooltip, { passive: true });
}
private removeHoverTooltip(element: HTMLElement) {
const tooltip = element.querySelector('.herb-tooltip');
if (tooltip) {
const handlers = (element as any)._tooltipHandlers;
const tooltipHandlers = (tooltip as any)._tooltipHandlers;
if (handlers) {
element.removeEventListener('mouseenter', handlers.showTooltip);
element.removeEventListener('mouseleave', handlers.hideTooltip);
const locationElement = tooltip.querySelector('.herb-location');
locationElement?.removeEventListener('click', handlers.openInEditor);
const copyButton = tooltip.querySelector('.herb-copy-path-btn');
copyButton?.removeEventListener('click', handlers.copyFilePath);
if (handlers.positionTooltip) {
window.removeEventListener('scroll', handlers.positionTooltip);
window.removeEventListener('resize', handlers.positionTooltip);
}
delete (element as any)._tooltipHandlers;
}
if (tooltipHandlers) {
tooltip.removeEventListener('mouseenter', tooltipHandlers.showTooltip);
tooltip.removeEventListener('mouseleave', tooltipHandlers.hideTooltip);
delete (tooltip as any)._tooltipHandlers;
}
tooltip.remove();
}
}
private addTooltipHoverHandler(element: HTMLElement) {
this.removeTooltipHoverHandler(element);
const lazyTooltipHandler = () => {
if (!this.showingTooltips || !this.showingERBOutlines) {
return;
}
if (element.querySelector('.herb-tooltip')) {
return;
}
this.createHoverTooltip(element, element);
};
(element as any)._lazyTooltipHandler = lazyTooltipHandler;
element.addEventListener('mouseenter', lazyTooltipHandler);
}
private removeTooltipHoverHandler(element: HTMLElement) {
const handler = (element as any)._lazyTooltipHandler;
if (handler) {
element.removeEventListener('mouseenter', handler);
delete (element as any)._lazyTooltipHandler;
}
}
private getEditorUrl(editor: string, absolutePath: string, line: number, column: number): string {
switch (editor) {
case 'cursor':
return `cursor://file/${absolutePath}:${line}:${column}`;
case 'vscode':
return `vscode://file/${absolutePath}:${line}:${column}`;
case 'vscodium':
return `vscodium://file/${absolutePath}:${line}:${column}`;
case 'zed':
return `zed://file/${absolutePath}:${line}:${column}`;
case 'windsurf':
return `windsurf://file/${absolutePath}:${line}:${column}`;
case 'sublime':
return `subl://open?url=file://${absolutePath}&line=${line}&column=${column}`;
case 'atom':
return `atom://core/open/file?filename=${absolutePath}&line=${line}&column=${column}`;
case 'textmate':
return `txmt://open?url=file://${absolutePath}&line=${line}&column=${column}`;
case 'emacs':
return `emacs://open?url=file://${absolutePath}&line=${line}&column=${column}`;
case 'idea':
return `idea://open?file=${absolutePath}&line=${line}&column=${column}`;
case 'rubymine':
return `x-mine://open?file=${absolutePath}&line=${line}&column=${column}`;
case 'nova':
return `nova://open?path=${absolutePath}&line=${line}&column=${column}`;
case 'macvim':
return `mvim://open?url=file://${absolutePath}&line=${line}&column=${column}`;
case 'vim':
return `vim://open?url=file://${absolutePath}&line=${line}&column=${column}`;
case 'nvim':
return `nvim://open?url=file://${absolutePath}&line=${line}&column=${column}`;
default:
return '';
}
}
public openFileInEditor(file: string, line: number, column: number) {
const absolutePath = file.startsWith('/') ? file : (this.projectPath ? `${this.projectPath}/${file}` : file);
const editorToUse = this.preferredEditor === 'auto' ? this.defaultEditorFromServer : this.preferredEditor;
const url = this.getEditorUrl(editorToUse, absolutePath, line, column);
if (url) {
try {
window.open(url, '_self');
} catch (_error) {
console.log(`Open in editor: ${absolutePath}:${line}:${column}`);
}
} else {
console.log(`Open in editor: ${absolutePath}:${line}:${column}`);
}
}
private toggleTooltips(show?: boolean) {
this.showingTooltips = show !== undefined ? show : !this.showingTooltips;
if (this.showingTooltips && this.showingERBHoverReveal) {
this.toggleERBHoverReveal(false);
const toggleERBHoverRevealSwitch = document.getElementById('herbToggleERBHoverReveal') as HTMLInputElement;
if (toggleERBHoverRevealSwitch) {
toggleERBHoverRevealSwitch.checked = false;
}
}
const erbOutputs = document.querySelectorAll('[data-herb-debug-outline-type*="erb-output"]');
erbOutputs.forEach((element) => {
if (this.showingERBOutlines && this.showingTooltips) {
this.addTooltipHoverHandler(element);
} else {
this.removeTooltipHoverHandler(element);
this.removeHoverTooltip(element);
}
});
this.saveSettings();
}
private disableAll() {
this.clearCurrentHoveredERB();
this.toggleViewOutlines(false);
this.togglePartialOutlines(false);
this.toggleComponentOutlines(false);
this.toggleERBTags(false);
this.toggleERBOutlines(false);
this.toggleERBHoverReveal(false);
this.toggleTooltips(false);
this.toggleOutlineMetrics(false);
this.toggleHotReloading(false);
this.toggleFlashUpdates(false);
this.toggleSlotUpdates(false);
this.toggleHotReloadFlashes(false);
this.toggleLinter(false);
this.options.onRuntimePanelToggle?.(false);
const toggleViewOutlinesSwitch = document.getElementById('herbToggleViewOutlines') as HTMLInputElement;
const togglePartialOutlinesSwitch = document.getElementById('herbTogglePartialOutlines') as HTMLInputElement;
const toggleComponentOutlinesSwitch = document.getElementById('herbToggleComponentOutlines') as HTMLInputElement;
const toggleERBSwitch = document.getElementById('herbToggleERB') as HTMLInputElement;
const toggleERBOutlinesSwitch = document.getElementById('herbToggleERBOutlines') as HTMLInputElement;
const toggleERBHoverRevealSwitch = document.getElementById('herbToggleERBHoverReveal') as HTMLInputElement;
const toggleTooltipsSwitch = document.getElementById('herbToggleTooltips') as HTMLInputElement;
const toggleOutlineMetricsSwitch = document.getElementById('herbToggleOutlineMetrics') as HTMLInputElement;
const toggleHotReloadingSwitch = document.getElementById('herbToggleHotReloading') as HTMLInputElement;
const toggleFlashUpdatesSwitch = document.getElementById('herbToggleFlashUpdates') as HTMLInputElement;
const toggleSlotUpdatesSwitch = document.getElementById('herbToggleSlotUpdates') as HTMLInputElement;
const toggleHotReloadFlashesSwitch = document.getElementById('herbToggleHotReloadFlashes') as HTMLInputElement;
const toggleLinterSwitch = document.getElementById('herbToggleLinter') as HTMLInputElement;
const toggleRuntimePanelSwitch = document.getElementById('herbToggleRuntimePanel') as HTMLInputElement;
if (toggleViewOutlinesSwitch) toggleViewOutlinesSwitch.checked = false;
if (togglePartialOutlinesSwitch) togglePartialOutlinesSwitch.checked = false;
if (toggleComponentOutlinesSwitch) toggleComponentOutlinesSwitch.checked = false;
if (toggleERBSwitch) toggleERBSwitch.checked = false;
if (toggleERBOutlinesSwitch) toggleERBOutlinesSwitch.checked = false;
if (toggleERBHoverRevealSwitch) toggleERBHoverRevealSwitch.checked = false;
if (toggleTooltipsSwitch) toggleTooltipsSwitch.checked = false;
if (toggleOutlineMetricsSwitch) toggleOutlineMetricsSwitch.checked = false;
if (toggleHotReloadingSwitch) toggleHotReloadingSwitch.checked = false;
if (toggleFlashUpdatesSwitch) toggleFlashUpdatesSwitch.checked = false;
if (toggleSlotUpdatesSwitch) toggleSlotUpdatesSwitch.checked = false;
if (toggleHotReloadFlashesSwitch) toggleHotReloadFlashesSwitch.checked = false;
if (toggleLinterSwitch) toggleLinterSwitch.checked = false;
if (toggleRuntimePanelSwitch) toggleRuntimePanelSwitch.checked = false;
}
}