From 2feefaeb5ed2e6af3c1770a53ebc98426b316c74 Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Wed, 25 Oct 2023 19:39:36 +0200 Subject: [PATCH] Create basic dashboard syntax highlighter --- .../src/Http/DashboardController.php | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/packages/realtime-compiler/src/Http/DashboardController.php b/packages/realtime-compiler/src/Http/DashboardController.php index 260ece7f6da..2ae5de486da 100644 --- a/packages/realtime-compiler/src/Http/DashboardController.php +++ b/packages/realtime-compiler/src/Http/DashboardController.php @@ -28,10 +28,14 @@ use Hyde\Framework\Actions\CreatesNewMarkdownPostFile; use Symfony\Component\HttpKernel\Exception\HttpException; +use function e; +use function str; use function time; use function trim; use function round; +use function rtrim; use function strlen; +use function substr; use function basename; use function in_array; use function json_decode; @@ -169,6 +173,52 @@ public static function isMediaFileProbablyMinified(string $contents): bool return substr_count(trim($contents), "\n") < 3 && strlen($contents) > 200; } + /** @internal */ + public static function highlightMediaLibraryCode(string $contents): HtmlString + { + $contents = e($contents); + + if (static::isMediaFileProbablyMinified($contents)) { + return new HtmlString(substr($contents, 0, 800)); + } + + $highlighted = str($contents)->explode("\n")->slice(0, 25)->map(function (string $line): string { + $line = rtrim($line); + + if (str_starts_with($line, '//')) { + return "$line"; + } + + if (str_starts_with($line, '/*') && str_ends_with($line, '*/')) { + // Commented code should not be additionally formatted, though we always want to comment multiline blocks + $quickReturn = true; + + } + + $line = str_replace('/*', "/*", $line); + $line = str_replace('*/', '*/', $line); + + if ($quickReturn ?? false) { + return rtrim($line); + } + + $line = strtr($line, [ + '{' => "{", + '}' => "}", + '(' => "(", + ')' => ")", + ':' => ":", + ';' => ";", + 'return' => "return", + 'function' => "function", + ]); + + return rtrim($line); + })->implode("\n"); + + return new HtmlString($highlighted); + } + public function showTips(): bool { return config('hyde.server.tips', true);