Fix: Empty lines in code blocks
This commit is contained in:
parent
f16bdfb89a
commit
824f4335fb
|
@ -3,6 +3,7 @@
|
|||
namespace App\Services\Markdown;
|
||||
|
||||
use App\Services\Markdown\Renderers\LinkRenderer;
|
||||
use DOMDocument;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use League\CommonMark\Environment\Environment;
|
||||
|
@ -58,6 +59,7 @@ public function render(): string
|
|||
|
||||
// Perform final adjustments like inserting non-breaking spaces
|
||||
$result = $this->insertNonBreakingSpaces($converted->getContent());
|
||||
$result = $this->removeEmptyCodeLines($result);
|
||||
|
||||
// Cache::put($cacheKey, $result, now()->addMonth());
|
||||
|
||||
|
@ -122,4 +124,32 @@ protected function insertNonBreakingSpaces(string $html): string
|
|||
// Perform the replacements and return the modified HTML
|
||||
return preg_replace($patterns, $replacements, $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* For some reason, to date (04-2024), HighlightCodeExtension appends empty
|
||||
* lines at the end of a code block. We need to get rid of them.
|
||||
*/
|
||||
protected function removeEmptyCodeLines(string $html): string
|
||||
{
|
||||
$body = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
|
||||
|
||||
libxml_use_internal_errors(true);
|
||||
|
||||
$dom = new DOMDocument('1.0', 'UTF-8');
|
||||
|
||||
$dom->loadHtml($body);
|
||||
|
||||
libxml_clear_errors();
|
||||
|
||||
$xpath = new \DOMXPath($dom);
|
||||
$spans = $xpath->query('//pre/code/span[@class="line" and not(node())]');
|
||||
|
||||
foreach ($spans as $span) {
|
||||
if ($span->isSameNode($span->parentNode->lastChild)) {
|
||||
$span->parentNode->removeChild($span);
|
||||
}
|
||||
}
|
||||
|
||||
return $dom->saveHTML();
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user