diff --git a/README.md b/README.md index c6de1eaa..5c7367b9 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,8 @@ The MageForge Inspector lets you inspect Magento blocks, templates, and performa **Features:** - Template paths, block classes, and module names +- 1-click **Open in IDE** (PhpStorm, VS Code, Cursor, Zed, Sublime Text, or custom URL) with browser-saved Docker/DDEV host path mapping +- 1-click **Override & Open** directly into any editable `app/design/frontend` theme, including automatic cache cleaning - PHP render times and cache status (lifetime, tags) - Web Vitals: LCP, CLS, INP per element - Accessibility checks: ARIA roles, contrast ratios, alt text diff --git a/src/Block/Inspector.php b/src/Block/Inspector.php index f2ef3306..96822186 100644 --- a/src/Block/Inspector.php +++ b/src/Block/Inspector.php @@ -4,12 +4,19 @@ namespace OpenForgeProject\MageForge\Block; +use Magento\Framework\App\Area; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\App\State; +use Magento\Framework\Component\ComponentRegistrar; +use Magento\Framework\Component\ComponentRegistrarInterface; +use Magento\Framework\View\DesignInterface; use Magento\Framework\View\Element\Template; use Magento\Framework\View\Element\Template\Context; use OpenForgeProject\MageForge\Model\Config\Inspector as InspectorConfig; +use OpenForgeProject\MageForge\Model\ThemeList; use OpenForgeProject\MageForge\Service\DeveloperAccessChecker; +use OpenForgeProject\MageForge\Service\Inspector\OverrideTokenManager; /** * Block for MageForge Inspector @@ -23,6 +30,11 @@ class Inspector extends Template * @param State $state * @param ScopeConfigInterface $scopeConfig * @param DeveloperAccessChecker $developerAccessChecker + * @param OverrideTokenManager $overrideTokenManager + * @param ThemeList $themeList + * @param ComponentRegistrarInterface $componentRegistrar + * @param DirectoryList $directoryList + * @param DesignInterface $design * @param array $data * @phpstan-param array $data */ @@ -31,6 +43,11 @@ public function __construct( private readonly State $state, private readonly ScopeConfigInterface $scopeConfig, private readonly DeveloperAccessChecker $developerAccessChecker, + private readonly OverrideTokenManager $overrideTokenManager, + private readonly ThemeList $themeList, + private readonly ComponentRegistrarInterface $componentRegistrar, + private readonly DirectoryList $directoryList, + private readonly DesignInterface $design, array $data = [], ) { parent::__construct($context, $data); @@ -188,6 +205,106 @@ public function getInspectorShortcut(): string return is_string($value) && $value !== '' ? $value : InspectorConfig::DEFAULT_INSPECTOR_SHORTCUT; } + /** + * Get URL for the 1-click template override endpoint + * + * @return string + */ + public function getOverrideUrl(): string + { + return $this->getUrl('mageforge/inspector/override'); + } + + /** + * Get HMAC security token for 1-click template override requests + * + * @return string + */ + public function getOverrideToken(): string + { + return $this->overrideTokenManager->generate(); + } + + /** + * Get normalized Magento root path on the server + * + * @return string + */ + public function getMagentoRoot(): string + { + return rtrim(str_replace('\\', '/', $this->directoryList->getRoot()), '/'); + } + + /** + * Get currently active frontend theme code + * + * @return string + */ + public function getActiveThemeCode(): string + { + return $this->design->getDesignTheme()->getCode(); + } + + /** + * Get registered frontend themes as JSON metadata for the target theme selector + * + * Editable themes (outside vendor/, e.g. app/design/frontend/...) are sorted first. + * + * @return string + */ + public function getFrontendThemesJson(): string + { + $root = $this->getMagentoRoot(); + $editable = []; + $readOnly = []; + + foreach ($this->themeList->getAllThemes() as $theme) { + if ($theme->getArea() !== Area::AREA_FRONTEND) { + continue; + } + + $code = $theme->getCode(); + if ($code === '') { + continue; + } + + $fullPath = $theme->getFullPath(); + $themePath = is_string($fullPath) && $fullPath !== '' + ? $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $fullPath) + : null; + $relativePath = ''; + if (is_string($themePath) && $themePath !== '') { + $normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/'); + $relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/') + ? substr($normalizedPath, strlen($root) + 1) + : $normalizedPath; + } + + $isEditable = $relativePath !== '' && !str_starts_with($relativePath, 'vendor/'); + $entry = [ + 'code' => $code, + 'path' => $relativePath, + 'editable' => $isEditable, + ]; + + if ($isEditable) { + $editable[$code] = $entry; + } else { + $readOnly[$code] = $entry; + } + } + + ksort($editable); + ksort($readOnly); + + $encoded = json_encode( + array_values([...$editable, ...$readOnly]), + JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, + ); + + return $encoded !== false ? $encoded : '[]'; + } + /** * Render block HTML * diff --git a/src/Console/Command/System/CheckCommand.php b/src/Console/Command/System/CheckCommand.php index a027ad13..ff15da32 100644 --- a/src/Console/Command/System/CheckCommand.php +++ b/src/Console/Command/System/CheckCommand.php @@ -659,7 +659,7 @@ private function getImportantPhpExtensions(): array */ private function getPhpMemoryLimit(): string { - return (string) ini_get('memory_limit'); + return ini_get('memory_limit') ?: ''; } /** @@ -810,7 +810,7 @@ private function getSystemEnvironmentValue(string $name): ?string { // Use ini_get for certain system variables as a safer alternative if (in_array($name, ['memory_limit', 'max_execution_time'], true)) { - $value = (string) ini_get($name); + $value = ini_get($name) ?: ''; if ($value !== '') { return $value; } diff --git a/src/Controller/Inspector/Override.php b/src/Controller/Inspector/Override.php new file mode 100644 index 00000000..4929f3db --- /dev/null +++ b/src/Controller/Inspector/Override.php @@ -0,0 +1,208 @@ +createJsonResponse(403, [ + 'success' => false, + 'message' => 'Invalid or missing security token.', + ])); + } + + /** + * Require POST, XHR header, and a valid installation HMAC token + * + * @param RequestInterface $request + * @return bool|null + */ + public function validateForCsrf(RequestInterface $request): ?bool + { + return $this->isAuthorizedRequest($request); + } + + /** + * Execute the 1-click template override action + * + * @return Json + */ + public function execute(): Json + { + if (!$this->isInspectorAvailable()) { + return $this->createJsonResponse(403, [ + 'success' => false, + 'message' => 'MageForge Inspector is not available.', + ]); + } + + if (!$this->isAuthorizedRequest($this->request)) { + return $this->createJsonResponse(403, [ + 'success' => false, + 'message' => 'Invalid or missing security token.', + ]); + } + + [$template, $theme] = $this->extractPayload(); + + try { + $result = $this->templateOverrider->override($template, $theme); + + return $this->createJsonResponse(200, [ + 'success' => true, + 'created' => $result->created, + 'targetPath' => $result->targetPath, + 'sourcePath' => $result->sourcePath, + 'themeCode' => $result->themeCode, + 'templateId' => $result->templateId, + ]); + } catch (InvalidArgumentException $e) { + return $this->createJsonResponse(400, [ + 'success' => false, + 'message' => $e->getMessage(), + ]); + } catch (Throwable $e) { + return $this->createJsonResponse(500, [ + 'success' => false, + 'message' => $e->getMessage(), + ]); + } + } + + /** + * Check developer mode, Inspector config flag, and allowed IP + * + * @return bool + */ + private function isInspectorAvailable(): bool + { + if ($this->state->getMode() !== State::MODE_DEVELOPER) { + return false; + } + + if (!$this->scopeConfig->isSetFlag(InspectorConfig::XML_PATH_ENABLED, InspectorConfig::SCOPE_STORE)) { + return false; + } + + return $this->developerAccessChecker->isDevAllowed(); + } + + /** + * Verify HTTP method, AJAX header, and HMAC token header + * + * @param RequestInterface $request + * @return bool + */ + private function isAuthorizedRequest(RequestInterface $request): bool + { + if (!$request instanceof HttpRequest || !$request->isPost() || !$request->isXmlHttpRequest()) { + return false; + } + + $token = $request->getHeader(self::SIGNATURE_HEADER); + if (!is_string($token)) { + return false; + } + + return $this->tokenManager->isValid(trim($token)); + } + + /** + * Extract template and theme fields from JSON body or request params + * + * @return array{0: string, 1: string} + */ + private function extractPayload(): array + { + if ($this->request instanceof HttpRequest) { + $rawContent = $this->request->getContent(); + if ($rawContent !== '') { + $decoded = json_decode($rawContent, true); + if (is_array($decoded)) { + $template = isset($decoded['template']) && is_string($decoded['template']) + ? $decoded['template'] + : ''; + $theme = isset($decoded['theme']) && is_string($decoded['theme']) ? $decoded['theme'] : ''; + + return [$template, $theme]; + } + } + } + + $templateParam = $this->request->getParam('template'); + $themeParam = $this->request->getParam('theme'); + + return [ + is_string($templateParam) ? $templateParam : '', + is_string($themeParam) ? $themeParam : '', + ]; + } + + /** + * Build a JSON result with status code and payload + * + * @param int $statusCode + * @param array $payload + * @phpstan-param array $payload + * @return Json + */ + private function createJsonResponse(int $statusCode, array $payload): Json + { + $result = $this->jsonFactory->create(); + $result->setHttpResponseCode($statusCode); + $result->setData($payload); + + return $result; + } +} diff --git a/src/Model/TemplateOverrideResult.php b/src/Model/TemplateOverrideResult.php new file mode 100644 index 00000000..555a0c82 --- /dev/null +++ b/src/Model/TemplateOverrideResult.php @@ -0,0 +1,27 @@ +encryptor->hash(self::PAYLOAD_PURPOSE); + } + + /** + * Verify a provided token in constant time + * + * @param string $token + * @return bool + */ + public function isValid(#[SensitiveParameter] string $token): bool + { + if ($token === '') { + return false; + } + + $expected = $this->generate(); + if ($expected === '') { + return false; + } + + return Security::compareStrings($expected, $token); + } +} diff --git a/src/Service/TemplateOverride/BrowserTemplateOverrider.php b/src/Service/TemplateOverride/BrowserTemplateOverrider.php new file mode 100644 index 00000000..ab87c768 --- /dev/null +++ b/src/Service/TemplateOverride/BrowserTemplateOverrider.php @@ -0,0 +1,236 @@ +findFrontendTheme($themeCode); + if ($theme === null) { + throw new InvalidArgumentException(sprintf("Frontend theme '%s' was not found.", $themeCode)); + } + + $this->assertEditableTheme($theme); + + $reference = $this->templatePathParser->parse($templateInput); + if ($reference->isDirectory()) { + throw new InvalidArgumentException('Only single template files can be overridden from the Inspector.'); + } + + $templatePath = $reference->getTemplatePath(); + $fallbackDirs = $this->fallbackResolver->getFallbackDirs($reference, $theme); + if ($fallbackDirs === []) { + throw new RuntimeException(sprintf('No fallback directories found for %s.', $reference->getTemplateId())); + } + + $targetDir = $this->fallbackResolver->getThemeTargetDir($fallbackDirs, $theme); + if ($targetDir === null) { + throw new RuntimeException(sprintf( + "Could not determine the override directory inside theme '%s'.", + $theme->getCode(), + )); + } + + $sourceFile = $this->fallbackResolver->findFirstExistingFile($fallbackDirs, $templatePath); + if ($sourceFile === null) { + throw new RuntimeException(sprintf( + 'Template %s was not found in any fallback location.', + $reference->getTemplateId(), + )); + } + + $targetFile = $targetDir . '/' . $templatePath; + if ($sourceFile === $targetFile) { + return new TemplateOverrideResult( + created: false, + targetPath: $this->toRelativePath($targetFile), + sourcePath: $this->toRelativePath($sourceFile), + themeCode: $theme->getCode(), + templateId: $reference->getTemplateId(), + ); + } + + $sourceModuleName = $this->resolveSourceModuleName($sourceFile, $fallbackDirs, $reference); + $this->templateCopier->copy($sourceFile, $targetFile, $sourceModuleName); + + $resolved = $this->fallbackResolver->findFirstExistingFile($fallbackDirs, $templatePath); + if ($resolved !== $targetFile) { + throw new RuntimeException(sprintf( + 'The file was copied, but Magento resolves the template to %s instead of the new override.', + $resolved === null ? 'nothing' : $this->toRelativePath($resolved), + )); + } + + foreach (self::CACHE_TYPES as $cacheType) { + $this->cacheTypeList->cleanType($cacheType); + } + + return new TemplateOverrideResult( + created: true, + targetPath: $this->toRelativePath($targetFile), + sourcePath: $this->toRelativePath($sourceFile), + themeCode: $theme->getCode(), + templateId: $reference->getTemplateId(), + ); + } + + /** + * Find a registered frontend theme by code + * + * @param string $themeCode + * @return ThemeInterface|null + */ + private function findFrontendTheme(string $themeCode): ?ThemeInterface + { + foreach ($this->themeList->getAllThemes() as $theme) { + if ($theme->getArea() === Area::AREA_FRONTEND && $theme->getCode() === $themeCode) { + return $theme; + } + } + + return null; + } + + /** + * Ensure the theme is located outside vendor/ so Composer packages are never modified + * + * @param ThemeInterface $theme + * @return void + * @throws InvalidArgumentException + */ + private function assertEditableTheme(ThemeInterface $theme): void + { + $themePath = $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $theme->getFullPath()); + if ($themePath === null || $themePath === '') { + throw new InvalidArgumentException(sprintf( + "Could not resolve filesystem path for theme '%s'.", + $theme->getCode(), + )); + } + + $relativePath = $this->toRelativePath($themePath); + if (str_starts_with($relativePath, 'vendor/')) { + throw new InvalidArgumentException(sprintf( + "Theme '%s' is located in vendor/ and is read-only. Select a custom theme in app/design/frontend.", + $theme->getCode(), + )); + } + } + + /** + * Determine the module name the source file belongs to, falling back to the reference + * + * @param string $sourceFile + * @param string[] $fallbackDirs + * @param TemplateReference $reference + * @return string + */ + private function resolveSourceModuleName( + string $sourceFile, + array $fallbackDirs, + TemplateReference $reference, + ): string { + $normalizedSource = str_replace('\\', '/', $sourceFile); + + foreach ($fallbackDirs as $dir) { + $dirWithTrailingSlash = rtrim(str_replace('\\', '/', $dir), '/') . '/'; + if (!str_starts_with($normalizedSource, $dirWithTrailingSlash)) { + continue; + } + + $relativePath = substr($normalizedSource, strlen($dirWithTrailingSlash)); + if (!str_contains($relativePath, '/')) { + continue; + } + + $firstSegment = explode('/', $relativePath)[0]; + if (str_contains($firstSegment, '_')) { + return $firstSegment; + } + } + + return $reference->getModuleName(); + } + + /** + * Convert an absolute path to a path relative to the Magento root + * + * @param string $absolutePath + * @return string + */ + private function toRelativePath(string $absolutePath): string + { + $root = rtrim(str_replace('\\', '/', $this->directoryList->getRoot()), '/'); + $normalized = str_replace('\\', '/', $absolutePath); + + if ($root !== '' && str_starts_with($normalized, $root . '/')) { + return substr($normalized, strlen($root) + 1); + } + + return $normalized; + } +} diff --git a/src/etc/frontend/routes.xml b/src/etc/frontend/routes.xml new file mode 100644 index 00000000..0cd764b9 --- /dev/null +++ b/src/etc/frontend/routes.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/src/view/frontend/templates/inspector.phtml b/src/view/frontend/templates/inspector.phtml index 532376a5..3de592b1 100644 --- a/src/view/frontend/templates/inspector.phtml +++ b/src/view/frontend/templates/inspector.phtml @@ -81,4 +81,9 @@ $alpineBootstrap = << + data-shortcut="escapeHtmlAttr($block->getInspectorShortcut()) ?>" + data-magento-root="escapeHtmlAttr($block->getMagentoRoot()) ?>" + data-override-url="escapeUrl($block->getOverrideUrl()) ?>" + data-override-token="escapeHtmlAttr($block->getOverrideToken()) ?>" + data-active-theme="escapeHtmlAttr($block->getActiveThemeCode()) ?>" + data-themes="escapeHtmlAttr($block->getFrontendThemesJson()) ?>"> diff --git a/src/view/frontend/web/css/inspector.css b/src/view/frontend/web/css/inspector.css index e0ee77ac..d601f896 100644 --- a/src/view/frontend/web/css/inspector.css +++ b/src/view/frontend/web/css/inspector.css @@ -615,6 +615,288 @@ border-color: rgba(var(--mageforge-color-red-rgb), 0.3) !important; } +/* ============================================================================ + Template IDE & 1-Click Override Controls + ========================================================================== */ + +.mageforge-mb-0 { + margin-bottom: 0 !important; +} + +.mageforge-template-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 6px; +} + +.mageforge-template-title-group { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.mageforge-template-pill { + display: inline-flex; + align-items: center; + padding: 1px 7px; + border-radius: 999px; + font-size: 10px; + font-weight: 600; + line-height: 1.4; + letter-spacing: 0.01em; +} + +.mageforge-template-pill--overridden { + background: rgba(var(--mageforge-color-green-rgb), 0.15); + color: var(--mageforge-color-green); + border: 1px solid rgba(var(--mageforge-color-green-rgb), 0.3); +} + +.mageforge-template-pill--theme { + background: rgba(var(--mageforge-color-amber-rgb), 0.15); + color: var(--mageforge-color-amber); + border: 1px solid rgba(var(--mageforge-color-amber-rgb), 0.3); +} + +.mageforge-template-pill--vendor { + background: rgba(var(--mageforge-color-slate-400-rgb), 0.15); + color: var(--mageforge-color-slate-300); + border: 1px solid rgba(var(--mageforge-color-slate-400-rgb), 0.25); +} + +.mageforge-ide-settings-toggle { + background: var(--mageforge-surface-glass); + border: 1px solid var(--mageforge-border-glass); + color: var(--mageforge-color-slate-300); + border-radius: 5px; + padding: 2px 8px; + font-size: 10px; + font-weight: 600; + font-family: inherit; + cursor: pointer; + transition: all 0.15s ease; + white-space: nowrap; +} + +.mageforge-ide-settings-toggle:hover, +.mageforge-ide-settings-toggle.active { + background: rgba(var(--mageforge-color-blue-rgb), 0.15); + border-color: rgba(var(--mageforge-color-blue-rgb), 0.35); + color: var(--mageforge-color-blue); +} + +.mageforge-template-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-top: 8px; +} + +.mageforge-ide-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + height: 28px; + padding: 0 10px; + border-radius: 6px; + font-family: inherit; + font-size: 11px; + font-weight: 600; + line-height: 1; + cursor: pointer; + transition: all 0.15s ease; + white-space: nowrap; + border: 1px solid transparent; +} + +.mageforge-ide-btn--open { + background: rgba(var(--mageforge-color-blue-rgb), 0.15); + border-color: rgba(var(--mageforge-color-blue-rgb), 0.35); + color: var(--mageforge-color-blue); +} + +.mageforge-ide-btn--open:hover { + background: rgba(var(--mageforge-color-blue-rgb), 0.25); + border-color: rgba(var(--mageforge-color-blue-rgb), 0.55); +} + +.mageforge-ide-btn--override { + background: linear-gradient( + 135deg, + var(--mageforge-color-blue) 0%, + var(--mageforge-color-blue-dark) 100% + ); + color: var(--mageforge-color-white); + box-shadow: 0 2px 6px rgba(var(--mageforge-color-blue-rgb), 0.3); +} + +.mageforge-ide-btn--override:hover:not(:disabled) { + transform: translateY(-1px); + box-shadow: 0 4px 10px rgba(var(--mageforge-color-blue-rgb), 0.4); +} + +.mageforge-ide-btn--override:disabled { + opacity: 0.55; + cursor: not-allowed; + box-shadow: none; +} + +.mageforge-ide-btn--override.is-overridden { + background: rgba(var(--mageforge-color-green-rgb), 0.15); + border-color: rgba(var(--mageforge-color-green-rgb), 0.35); + color: var(--mageforge-color-green); + opacity: 1; +} + +.mageforge-ide-btn--save { + background: var(--mageforge-color-green); + color: var(--mageforge-color-white); +} + +.mageforge-ide-btn--save:hover { + background: var(--mageforge-color-green-dark); +} + +.mageforge-ide-btn--ghost { + background: var(--mageforge-surface-glass); + border-color: var(--mageforge-border-glass); + color: var(--mageforge-color-slate-300); +} + +.mageforge-ide-btn--ghost:hover { + background: var(--mageforge-surface-glass-hover); + color: var(--mageforge-color-slate-100); +} + +.mageforge-ide-select, +.mageforge-ide-input { + height: 28px; + padding: 0 8px; + border-radius: 6px; + background: var(--mageforge-surface-glass); + border: 1px solid var(--mageforge-border-glass); + color: var(--mageforge-color-slate-100); + font-family: inherit; + font-size: 11px; + outline: none; + transition: border-color 0.15s ease; +} + +.mageforge-ide-select { + cursor: pointer; + background-color: var(--mageforge-color-slate-900); +} + +.mageforge-inspector[data-theme="light"] .mageforge-ide-select { + background-color: var(--mageforge-color-white); +} + +@media (prefers-color-scheme: light) { + .mageforge-inspector[data-theme="auto"] .mageforge-ide-select { + background-color: var(--mageforge-color-white); + } +} + +.mageforge-theme-select { + flex: 1 1 130px; + min-width: 120px; + max-width: 210px; +} + +.mageforge-ide-input { + width: 100%; + font-family: var(--mageforge-font-mono); + cursor: text; + user-select: text; + -webkit-user-select: text; +} + +.mageforge-ide-select:focus, +.mageforge-ide-input:focus { + border-color: var(--mageforge-color-blue); +} + +.mageforge-ide-status { + margin-top: 8px; + padding: 6px 10px; + border-radius: 6px; + font-size: 11px; + line-height: 1.4; +} + +.mageforge-ide-status--success { + background: rgba(var(--mageforge-color-green-rgb), 0.12); + border: 1px solid rgba(var(--mageforge-color-green-rgb), 0.3); + color: var(--mageforge-color-green); +} + +.mageforge-ide-status--warning { + background: rgba(var(--mageforge-color-amber-rgb), 0.12); + border: 1px solid rgba(var(--mageforge-color-amber-rgb), 0.35); + color: var(--mageforge-color-amber); +} + +.mageforge-ide-status--error { + background: rgba(var(--mageforge-color-red-rgb), 0.12); + border: 1px solid rgba(var(--mageforge-color-red-rgb), 0.35); + color: var(--mageforge-color-red-light); +} + +.mageforge-inspector[data-theme="light"] .mageforge-ide-status--error { + color: var(--mageforge-color-red); +} + +@media (prefers-color-scheme: light) { + .mageforge-inspector[data-theme="auto"] .mageforge-ide-status--error { + color: var(--mageforge-color-red); + } +} + +.mageforge-ide-settings-panel { + margin-top: 10px; + padding: 10px 12px; + border-radius: 8px; + background: var(--mageforge-surface-glass); + border: 1px solid var(--mageforge-border-color); + cursor: default; +} + +.mageforge-ide-field { + margin-bottom: 8px; +} + +.mageforge-ide-field .mageforge-ide-select { + width: 100%; +} + +.mageforge-ide-label { + display: block; + font-size: 10px; + font-weight: 600; + color: var(--mageforge-color-slate-300); + margin-bottom: 4px; +} + +.mageforge-ide-hint { + margin-top: 4px; + font-size: 10px; + line-height: 1.35; + color: var(--mageforge-color-slate-400); + word-break: break-all; +} + +.mageforge-ide-settings-actions { + display: flex; + justify-content: flex-end; + gap: 6px; + margin-top: 10px; +} + /* ============================================================================ Alerts & Notifications ========================================================================== */ diff --git a/src/view/frontend/web/js/inspector.js b/src/view/frontend/web/js/inspector.js index 2da85d1a..570f129a 100644 --- a/src/view/frontend/web/js/inspector.js +++ b/src/view/frontend/web/js/inspector.js @@ -14,6 +14,7 @@ import { accessibilityMethods } from "./inspector/accessibility.js"; import { performanceMethods } from "./inspector/performance.js"; import { vitalsMethods } from "./inspector/vitals.js"; import { draggableMethods } from "./inspector/draggable.js"; +import { ideMethods } from "./inspector/ide.js"; import { blockDataMap } from "./inspector/blockData.js"; // Extracted into a named function so it can be called either from the @@ -89,6 +90,7 @@ function _registerMageforgeInspector() { this.clickHandler = (e) => this.handleClick(e); this.setupKeyboardShortcuts(); + this.initIdeIntegration(); this.createHighlightBox(); this.createInfoBadge(); this.initWebVitalsTracking(); @@ -285,6 +287,7 @@ function _registerMageforgeInspector() { ...performanceMethods, ...vitalsMethods, ...draggableMethods, + ...ideMethods, })); } diff --git a/src/view/frontend/web/js/inspector/draggable.js b/src/view/frontend/web/js/inspector/draggable.js index 44107499..1c8963fa 100644 --- a/src/view/frontend/web/js/inspector/draggable.js +++ b/src/view/frontend/web/js/inspector/draggable.js @@ -43,6 +43,11 @@ export const draggableMethods = { // Ignore clicks on close button or content internal interactive elements if ( e.target.closest("button") || + e.target.closest("select") || + e.target.closest("input") || + e.target.closest("label") || + e.target.closest("a") || + e.target.closest(".mageforge-ide-settings-panel") || e.target.closest(".mageforge-info-value") ) { return; diff --git a/src/view/frontend/web/js/inspector/ide.js b/src/view/frontend/web/js/inspector/ide.js new file mode 100644 index 00000000..cf49aca9 --- /dev/null +++ b/src/view/frontend/web/js/inspector/ide.js @@ -0,0 +1,921 @@ +/** + * MageForge Inspector - 1-Click Template Override & Open in IDE + */ + +import { blockDataMap } from "./blockData.js"; + +const IDE_STORAGE_KEY = "mageforge_inspector_ide_settings"; +const THEME_STORAGE_KEY = "mageforge_inspector_target_theme"; + +const IDE_PRESETS = { + phpstorm: { + label: "PhpStorm", + buildUrl: (file, line) => + `phpstorm://open?file=${encodeURIComponent(file)}&line=${line}`, + }, + vscode: { + label: "VS Code", + buildUrl: (file, line) => + `vscode://file/${encodeURI(file.replace(/^\/+/, ""))}:${line}`, + }, + cursor: { + label: "Cursor", + buildUrl: (file, line) => + `cursor://file/${encodeURI(file.replace(/^\/+/, ""))}:${line}`, + }, + zed: { + label: "Zed", + buildUrl: (file, line) => + `zed://file/${encodeURI(file.replace(/^\/+/, ""))}:${line}`, + }, + sublime: { + label: "Sublime Text", + buildUrl: (file, line) => + `subl://open?url=${encodeURIComponent("file://" + (file.startsWith("/") ? file : "/" + file))}&line=${line}`, + }, + custom: { + label: "Custom URL", + buildUrl: (file, line, customPattern, relativeFile) => + (customPattern || "phpstorm://open?file={file}&line={line}") + .replaceAll("{file}", encodeURIComponent(file)) + .replaceAll("{relativeFile}", encodeURIComponent(relativeFile || "")) + .replaceAll("{line}", String(line)), + }, +}; + +const CONTAINER_PATH_PREFIXES = [ + "/var/www", + "/srv/", + "/app/", + "/opt/", + "/workspace", +]; + +export const ideMethods = { + /** + * Initialize IDE configuration and theme list from root data-* attributes + */ + initIdeIntegration() { + this.magentoRoot = ( + this.$el?.getAttribute("data-magento-root") || "" + ).replace(/\/+$/, ""); + this.overrideUrl = this.$el?.getAttribute("data-override-url") || ""; + this.overrideToken = this.$el?.getAttribute("data-override-token") || ""; + this.activeThemeCode = this.$el?.getAttribute("data-active-theme") || ""; + this.frontendThemes = this.parseFrontendThemes( + this.$el?.getAttribute("data-themes") || "[]", + ); + + this.ideSettings = this.loadIdeSettings(); + this.selectedOverrideTheme = this.resolveInitialTargetTheme(); + this.ideSettingsOpen = false; + this.ideStatusMessage = null; + this.pendingIdeOpenPath = null; + this.isOverridingTemplate = false; + }, + + /** + * Parse JSON theme metadata safely + */ + parseFrontendThemes(rawJson) { + try { + const parsed = JSON.parse(rawJson); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } + }, + + /** + * Load persisted IDE preferences from localStorage + */ + loadIdeSettings() { + const defaults = { + editor: "phpstorm", + hostRoot: "", + customUrlPattern: "phpstorm://open?file={file}&line={line}", + }; + + try { + const stored = window.localStorage.getItem(IDE_STORAGE_KEY); + if (!stored) return defaults; + + const parsed = JSON.parse(stored); + if (!parsed || typeof parsed !== "object") return defaults; + + return { + editor: IDE_PRESETS[parsed.editor] ? parsed.editor : defaults.editor, + hostRoot: + typeof parsed.hostRoot === "string" + ? parsed.hostRoot.trim().replace(/[\\/]+$/, "") + : "", + customUrlPattern: + typeof parsed.customUrlPattern === "string" && + parsed.customUrlPattern.trim() !== "" + ? parsed.customUrlPattern.trim() + : defaults.customUrlPattern, + }; + } catch { + return defaults; + } + }, + + /** + * Save IDE preferences to localStorage + */ + saveIdeSettings(settings) { + this.ideSettings = { + editor: IDE_PRESETS[settings.editor] ? settings.editor : "phpstorm", + hostRoot: (settings.hostRoot || "").trim().replace(/[\\/]+$/, ""), + customUrlPattern: + (settings.customUrlPattern || "").trim() || + "phpstorm://open?file={file}&line={line}", + }; + + try { + window.localStorage.setItem( + IDE_STORAGE_KEY, + JSON.stringify(this.ideSettings), + ); + } catch { + // Ignore storage quota / private mode failures; keep in-memory state + } + }, + + /** + * Pick initial target theme: saved preference -> active theme (if editable) -> first editable theme + */ + resolveInitialTargetTheme() { + const editableThemes = this.frontendThemes.filter((t) => t.editable); + if (editableThemes.length === 0) { + return ""; + } + + try { + const savedTheme = window.sessionStorage.getItem(THEME_STORAGE_KEY); + if ( + savedTheme && + editableThemes.some((theme) => theme.code === savedTheme) + ) { + return savedTheme; + } + } catch { + // Ignore sessionStorage errors + } + + if ( + this.activeThemeCode && + editableThemes.some((theme) => theme.code === this.activeThemeCode) + ) { + return this.activeThemeCode; + } + + return editableThemes[0].code; + }, + + /** + * Persist chosen target theme for the current browser session + */ + setSelectedOverrideTheme(themeCode) { + this.selectedOverrideTheme = themeCode; + try { + window.sessionStorage.setItem(THEME_STORAGE_KEY, themeCode); + } catch { + // Ignore sessionStorage errors + } + }, + + /** + * Detect whether the PHP server root looks like a Docker/DDEV/Warden container path + */ + isServerContainerPath() { + if (!this.magentoRoot) return false; + const normalized = this.magentoRoot.replace(/\\/g, "/"); + return CONTAINER_PATH_PREFIXES.some( + (prefix) => + normalized === prefix.replace(/\/$/, "") || + normalized.startsWith(prefix), + ); + }, + + /** + * Resolve full host filesystem path for a Magento-relative file path + */ + resolveHostFilePath(relativePath) { + const cleanRel = (relativePath || "") + .replace(/\\/g, "/") + .replace(/^\/+/, ""); + const baseRoot = (this.ideSettings.hostRoot || this.magentoRoot || "") + .replace(/\\/g, "/") + .replace(/\/+$/, ""); + + if (!baseRoot) { + return cleanRel; + } + + return `${baseRoot}/${cleanRel}`; + }, + + /** + * Build editor protocol URL for a Magento-relative file path + */ + buildIdeUrl(relativePath, line = 1) { + const preset = IDE_PRESETS[this.ideSettings.editor] || IDE_PRESETS.phpstorm; + const fullPath = this.resolveHostFilePath(relativePath); + + return preset.buildUrl( + fullPath, + line, + this.ideSettings.customUrlPattern, + relativePath, + ); + }, + + /** + * Trigger OS protocol handler via synthetic anchor click so active page state/WebSockets stay intact + */ + openTemplateInIde(relativePath, element) { + if (!relativePath) return; + + // Guard against opening an unmapped container path (e.g. /var/www/html) on the host OS + if (!this.ideSettings.hostRoot && this.isServerContainerPath()) { + this.ideSettingsOpen = true; + this.pendingIdeOpenPath = relativePath; + this.ideStatusMessage = { + type: "warning", + text: `Container path (${this.magentoRoot}) detected. Enter your host Magento root path below once to open files in your IDE.`, + }; + this.refreshCurrentBadge(element); + return; + } + + const url = this.buildIdeUrl(relativePath, 1); + const link = document.createElement("a"); + link.href = url; + link.rel = "noopener noreferrer"; + link.style.display = "none"; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + }, + + /** + * Check whether the given template path already resides inside a theme entry + */ + isTemplateInTheme(templatePath, themeEntry) { + if (!templatePath || !themeEntry || !themeEntry.path) { + return false; + } + const normalizedTemplate = templatePath.replace(/\\/g, "/"); + const normalizedThemePath = themeEntry.path + .replace(/\\/g, "/") + .replace(/\/+$/, ""); + + return normalizedTemplate.startsWith(`${normalizedThemePath}/`); + }, + + /** + * Execute 1-click template override via backend controller and open resulting file in IDE + */ + async triggerTemplateOverride(data, element) { + if (!this.canTriggerOverride(data, element)) { + return; + } + + this.isOverridingTemplate = true; + this.ideStatusMessage = null; + this.refreshCurrentBadge(element); + + try { + const payload = await this.sendOverrideRequest(data.template); + this.handleOverrideResponse(payload, element); + } catch (error) { + this.ideStatusMessage = { + type: "error", + text: error?.message || "Network error while creating override.", + }; + } finally { + this.isOverridingTemplate = false; + this.refreshCurrentBadge(element); + } + }, + + /** + * Validate preconditions before sending an override request + */ + canTriggerOverride(data, element) { + if ( + this.isOverridingTemplate || + !data?.template || + !this.selectedOverrideTheme + ) { + return false; + } + + if (!this.overrideUrl || !this.overrideToken) { + this.ideStatusMessage = { + type: "error", + text: "Override endpoint is not configured.", + }; + this.refreshCurrentBadge(element); + return false; + } + + return true; + }, + + /** + * Send POST request to the MageForge Inspector override endpoint + */ + async sendOverrideRequest(template) { + const response = await window.fetch(this.overrideUrl, { + method: "POST", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "X-Requested-With": "XMLHttpRequest", + "X-MageForge-Token": this.overrideToken, + }, + body: JSON.stringify({ + template, + theme: this.selectedOverrideTheme, + }), + }); + + const payload = await response.json().catch(() => null); + if (!response.ok || payload?.success !== true) { + throw new Error( + payload?.message || + `Override request failed (HTTP ${response.status}).`, + ); + } + + return payload; + }, + + /** + * Update local DOM metadata and open the overridden template in IDE + */ + handleOverrideResponse(payload, element) { + this.applyOverridePathToElement(element, payload.targetPath); + + const editorLabel = IDE_PRESETS[this.ideSettings.editor]?.label || "IDE"; + const actionLabel = payload.created + ? `Override created in ${payload.themeCode}` + : `Already overridden in ${payload.themeCode}`; + + this.ideStatusMessage = { + type: "success", + text: `${actionLabel} — opening in ${editorLabel}…`, + }; + + this.openTemplateInIde(payload.targetPath, element); + }, + + /** + * Update in-memory WeakMap and DOM attribute so the new override path is reflected immediately + */ + applyOverridePathToElement(element, newTargetPath) { + if (!element || !newTargetPath) return; + + const cached = blockDataMap.get(element); + if (cached) { + cached.template = newTargetPath; + cached.override = "1"; + cached.isOverride = true; + } + + const block = this.findBlockForElement(element); + const blockRoot = + block?.elements?.[0] || + (element.hasAttribute("data-mageforge-block") + ? element + : element.closest("[data-mageforge-block]")); + + if (blockRoot) { + try { + const raw = blockRoot.getAttribute("data-mageforge-block"); + if (raw) { + const parsed = JSON.parse(raw); + parsed.template = newTargetPath; + parsed.override = "1"; + blockRoot.setAttribute( + "data-mageforge-block", + JSON.stringify(parsed), + ); + } + } catch { + // Ignore malformed attribute JSON + } + } + }, + + /** + * Rebuild the active badge and focus Host Path input if settings were opened for container setup + */ + refreshCurrentBadge(element) { + const target = element || this.selectedElement || this.hoveredElement; + if (!target) return; + + this.buildBadgeContent(target); + + if (this.ideSettingsOpen && this.pendingIdeOpenPath && this.infoBadge) { + const hostInput = this.infoBadge.querySelector( + ".mageforge-ide-host-input", + ); + if (hostInput) { + hostInput.focus(); + } + } + }, + + /** + * Build the complete Template section with Open in IDE, 1-Click Override, Theme Switcher, and IDE Settings + */ + createTemplateSection(data, element) { + const container = document.createElement("div"); + container.className = "mageforge-info-section mageforge-template-section"; + + const editableThemes = this.frontendThemes.filter((t) => t.editable); + const selectedThemeObj = + editableThemes.find((t) => t.code === this.selectedOverrideTheme) || null; + const inSelectedTheme = this.isTemplateInTheme( + data.template, + selectedThemeObj, + ); + const editorLabel = + IDE_PRESETS[this.ideSettings?.editor]?.label || "PhpStorm"; + + container.appendChild( + this.createTemplateHeaderRow( + data, + element, + selectedThemeObj, + inSelectedTheme, + editorLabel, + ), + ); + container.appendChild(this.createCopyableValueSpan(data.template)); + container.appendChild( + this.createTemplateActionsBar( + data, + element, + editableThemes, + inSelectedTheme, + editorLabel, + ), + ); + + if (this.ideStatusMessage?.text) { + const statusBox = document.createElement("div"); + statusBox.className = `mageforge-ide-status mageforge-ide-status--${this.ideStatusMessage.type}`; + statusBox.textContent = this.ideStatusMessage.text; + container.appendChild(statusBox); + } + + if (this.ideSettingsOpen) { + container.appendChild(this.createIdeSettingsPanel(element)); + } + + return container; + }, + + /** + * Build Template section header row with title, status pill, and IDE settings toggle + */ + createTemplateHeaderRow( + data, + element, + selectedThemeObj, + inSelectedTheme, + editorLabel, + ) { + const headerRow = document.createElement("div"); + headerRow.className = "mageforge-template-header"; + + const titleGroup = document.createElement("div"); + titleGroup.className = "mageforge-template-title-group"; + + const titleSpan = document.createElement("span"); + titleSpan.className = + "mageforge-info-title mageforge-text-blue mageforge-mb-0"; + titleSpan.textContent = "Template"; + titleGroup.appendChild(titleSpan); + titleGroup.appendChild( + this.createTemplateStatusPill(data, selectedThemeObj, inSelectedTheme), + ); + + const settingsBtn = document.createElement("button"); + settingsBtn.type = "button"; + settingsBtn.className = + "mageforge-ide-settings-toggle" + (this.ideSettingsOpen ? " active" : ""); + settingsBtn.title = "Configure IDE & Host Path (saved in browser)"; + settingsBtn.textContent = `⚙ ${editorLabel}`; + settingsBtn.onclick = (e) => { + e.preventDefault(); + e.stopPropagation(); + this.ideSettingsOpen = !this.ideSettingsOpen; + if (!this.ideSettingsOpen) { + this.pendingIdeOpenPath = null; + } + this.refreshCurrentBadge(element); + }; + + headerRow.appendChild(titleGroup); + headerRow.appendChild(settingsBtn); + + return headerRow; + }, + + /** + * Build status pill indicating whether the template is a module default or theme override + */ + createTemplateStatusPill(data, selectedThemeObj, inSelectedTheme) { + const statusPill = document.createElement("span"); + const isThemeOverride = + data.isOverride || Boolean(data.template?.startsWith("app/design/")); + + if (inSelectedTheme && selectedThemeObj) { + statusPill.className = + "mageforge-template-pill mageforge-template-pill--overridden"; + statusPill.textContent = `Overridden (${selectedThemeObj.code})`; + } else if (isThemeOverride) { + statusPill.className = + "mageforge-template-pill mageforge-template-pill--theme"; + statusPill.textContent = "Theme Override"; + } else { + statusPill.className = + "mageforge-template-pill mageforge-template-pill--vendor"; + statusPill.textContent = "Module Default"; + } + + return statusPill; + }, + + /** + * Build action bar with Open in IDE button, target theme dropdown, and Override & Open button + */ + createTemplateActionsBar( + data, + element, + editableThemes, + inSelectedTheme, + editorLabel, + ) { + const actionsBar = document.createElement("div"); + actionsBar.className = "mageforge-template-actions"; + actionsBar.onclick = (e) => e.stopPropagation(); + + const openBtn = document.createElement("button"); + openBtn.type = "button"; + openBtn.className = "mageforge-ide-btn mageforge-ide-btn--open"; + openBtn.textContent = `↗ Open in ${editorLabel}`; + openBtn.title = `Open ${this.resolveHostFilePath(data.template)} in ${editorLabel}`; + openBtn.onclick = (e) => { + e.preventDefault(); + e.stopPropagation(); + this.ideStatusMessage = null; + this.openTemplateInIde(data.template, element); + }; + actionsBar.appendChild(openBtn); + + if (this.frontendThemes.length > 0) { + actionsBar.appendChild( + this.createTargetThemeSelect(editableThemes, element), + ); + } + + actionsBar.appendChild( + this.createOverrideActionButton( + data, + element, + editableThemes, + inSelectedTheme, + editorLabel, + ), + ); + + return actionsBar; + }, + + /** + * Build dropdown selector for choosing the target override theme + */ + createTargetThemeSelect(editableThemes, element) { + const themeSelect = document.createElement("select"); + themeSelect.className = "mageforge-ide-select mageforge-theme-select"; + themeSelect.title = "Target theme for 1-Click Override"; + themeSelect.setAttribute("aria-label", "Target theme for override"); + + if (editableThemes.length === 0) { + const placeholderOpt = document.createElement("option"); + placeholderOpt.value = ""; + placeholderOpt.textContent = "No app/design theme"; + themeSelect.appendChild(placeholderOpt); + } + + this.frontendThemes.forEach((theme) => { + themeSelect.appendChild(this.createThemeOptionElement(theme)); + }); + + themeSelect.onchange = (e) => { + e.stopPropagation(); + this.setSelectedOverrideTheme(e.target.value); + this.ideStatusMessage = null; + this.refreshCurrentBadge(element); + }; + + return themeSelect; + }, + + /** + * Build a single