BookStack/app/Entities/Tools/Markdown/CustomListItemRenderer.php

44 lines
1.3 KiB
PHP
Raw Normal View History

<?php
namespace BookStack\Entities\Tools\Markdown;
2023-02-07 04:00:44 +08:00
use League\CommonMark\Extension\CommonMark\Node\Block\ListItem;
use League\CommonMark\Extension\CommonMark\Renderer\Block\ListItemRenderer;
use League\CommonMark\Extension\TaskList\TaskListItemMarker;
2023-02-07 04:00:44 +08:00
use League\CommonMark\Node\Block\Paragraph;
use League\CommonMark\Node\Node;
use League\CommonMark\Renderer\ChildNodeRendererInterface;
use League\CommonMark\Renderer\NodeRendererInterface;
use League\CommonMark\Util\HtmlElement;
2023-02-07 04:00:44 +08:00
class CustomListItemRenderer implements NodeRendererInterface
{
2023-02-07 04:00:44 +08:00
protected ListItemRenderer $baseRenderer;
public function __construct()
{
$this->baseRenderer = new ListItemRenderer();
}
/**
* @return HtmlElement|string|null
*/
2023-02-07 04:00:44 +08:00
public function render(Node $node, ChildNodeRendererInterface $childRenderer)
{
2023-02-07 04:00:44 +08:00
$listItem = $this->baseRenderer->render($node, $childRenderer);
2023-02-07 04:00:44 +08:00
if ($node instanceof ListItem && $this->startsTaskListItem($node) && $listItem instanceof HtmlElement) {
$listItem->setAttribute('class', 'task-list-item');
}
return $listItem;
}
private function startsTaskListItem(ListItem $block): bool
{
$firstChild = $block->firstChild();
return $firstChild instanceof Paragraph && $firstChild->firstChild() instanceof TaskListItemMarker;
}
2021-08-25 04:23:55 +08:00
}