Primo Committ

This commit is contained in:
paoloar77
2024-05-07 12:17:25 +02:00
commit e73d0e5113
7204 changed files with 884387 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents\Node;
use League\CommonMark\Block\Element\ListBlock;
use League\CommonMark\Extension\TableOfContents\TableOfContents as DeprecatedTableOfContents;
final class TableOfContents extends ListBlock
{
}
\class_exists(DeprecatedTableOfContents::class);

View File

@@ -0,0 +1,33 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents\Node;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Cursor;
final class TableOfContentsPlaceholder extends AbstractBlock
{
public function canContain(AbstractBlock $block): bool
{
return false;
}
public function isCode(): bool
{
return false;
}
public function matchesNextLine(Cursor $cursor): bool
{
return false;
}
}

View File

@@ -0,0 +1,70 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents\Normalizer;
use League\CommonMark\Block\Element\ListBlock;
use League\CommonMark\Block\Element\ListItem;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
final class AsIsNormalizerStrategy implements NormalizerStrategyInterface
{
/** @var ListBlock */
private $parentListBlock;
/** @var int */
private $parentLevel = 1;
/** @var ListItem|null */
private $lastListItem;
public function __construct(TableOfContents $toc)
{
$this->parentListBlock = $toc;
}
public function addItem(int $level, ListItem $listItemToAdd): void
{
while ($level > $this->parentLevel) {
// Descend downwards, creating new ListBlocks if needed, until we reach the correct depth
if ($this->lastListItem === null) {
$this->lastListItem = new ListItem($this->parentListBlock->getListData());
$this->parentListBlock->appendChild($this->lastListItem);
}
$newListBlock = new ListBlock($this->parentListBlock->getListData());
$newListBlock->setStartLine($listItemToAdd->getStartLine());
$newListBlock->setEndLine($listItemToAdd->getEndLine());
$this->lastListItem->appendChild($newListBlock);
$this->parentListBlock = $newListBlock;
$this->lastListItem = null;
$this->parentLevel++;
}
while ($level < $this->parentLevel) {
// Search upwards for the previous parent list block
while (true) {
$this->parentListBlock = $this->parentListBlock->parent();
if ($this->parentListBlock instanceof ListBlock) {
break;
}
}
$this->parentLevel--;
}
$this->parentListBlock->appendChild($listItemToAdd);
$this->lastListItem = $listItemToAdd;
}
}
// Trigger autoload without causing a deprecated error
\class_exists(TableOfContents::class);

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents\Normalizer;
use League\CommonMark\Block\Element\ListItem;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
final class FlatNormalizerStrategy implements NormalizerStrategyInterface
{
/** @var TableOfContents */
private $toc;
public function __construct(TableOfContents $toc)
{
$this->toc = $toc;
}
public function addItem(int $level, ListItem $listItemToAdd): void
{
$this->toc->appendChild($listItemToAdd);
}
}
// Trigger autoload without causing a deprecated error
\class_exists(TableOfContents::class);

View File

@@ -0,0 +1,19 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents\Normalizer;
use League\CommonMark\Block\Element\ListItem;
interface NormalizerStrategyInterface
{
public function addItem(int $level, ListItem $listItemToAdd): void;
}

View File

@@ -0,0 +1,67 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents\Normalizer;
use League\CommonMark\Block\Element\ListBlock;
use League\CommonMark\Block\Element\ListItem;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
final class RelativeNormalizerStrategy implements NormalizerStrategyInterface
{
/** @var TableOfContents */
private $toc;
/** @var array<int, ListItem> */
private $listItemStack = [];
public function __construct(TableOfContents $toc)
{
$this->toc = $toc;
}
public function addItem(int $level, ListItem $listItemToAdd): void
{
\end($this->listItemStack);
$previousLevel = \key($this->listItemStack);
// Pop the stack if we're too deep
while ($previousLevel !== null && $level < $previousLevel) {
array_pop($this->listItemStack);
\end($this->listItemStack);
$previousLevel = \key($this->listItemStack);
}
/** @var ListItem|false $lastListItem */
$lastListItem = \current($this->listItemStack);
// Need to go one level deeper? Add that level
if ($lastListItem !== false && $level > $previousLevel) {
$targetListBlock = new ListBlock($lastListItem->getListData());
$targetListBlock->setStartLine($listItemToAdd->getStartLine());
$targetListBlock->setEndLine($listItemToAdd->getEndLine());
$lastListItem->appendChild($targetListBlock);
// Otherwise we're at the right level
// If there's no stack we're adding this item directly to the TOC element
} elseif ($lastListItem === false) {
$targetListBlock = $this->toc;
// Otherwise add it to the last list item
} else {
$targetListBlock = $lastListItem->parent();
}
$targetListBlock->appendChild($listItemToAdd);
$this->listItemStack[$level] = $listItemToAdd;
}
}
// Trigger autoload without causing a deprecated error
\class_exists(TableOfContents::class);

View File

@@ -0,0 +1,30 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents;
use League\CommonMark\Block\Element\ListBlock;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents as NewTableOfContents;
if (!class_exists(NewTableOfContents::class)) {
@trigger_error(sprintf('TableOfContents has moved to a new namespace; use %s instead', NewTableOfContents::class), \E_USER_DEPRECATED);
}
\class_alias(NewTableOfContents::class, TableOfContents::class);
if (false) {
/**
* @deprecated This class has moved to the Node sub-namespace; use that instead
*/
final class TableOfContents extends ListBlock
{
}
}

View File

@@ -0,0 +1,127 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents;
use League\CommonMark\Block\Element\Document;
use League\CommonMark\Block\Element\Heading;
use League\CommonMark\Event\DocumentParsedEvent;
use League\CommonMark\Exception\InvalidOptionException;
use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder;
use League\CommonMark\Util\ConfigurationAwareInterface;
use League\CommonMark\Util\ConfigurationInterface;
final class TableOfContentsBuilder implements ConfigurationAwareInterface
{
/**
* @deprecated Use TableOfContentsGenerator::STYLE_BULLET instead
*/
public const STYLE_BULLET = TableOfContentsGenerator::STYLE_BULLET;
/**
* @deprecated Use TableOfContentsGenerator::STYLE_ORDERED instead
*/
public const STYLE_ORDERED = TableOfContentsGenerator::STYLE_ORDERED;
/**
* @deprecated Use TableOfContentsGenerator::NORMALIZE_DISABLED instead
*/
public const NORMALIZE_DISABLED = TableOfContentsGenerator::NORMALIZE_DISABLED;
/**
* @deprecated Use TableOfContentsGenerator::NORMALIZE_RELATIVE instead
*/
public const NORMALIZE_RELATIVE = TableOfContentsGenerator::NORMALIZE_RELATIVE;
/**
* @deprecated Use TableOfContentsGenerator::NORMALIZE_FLAT instead
*/
public const NORMALIZE_FLAT = TableOfContentsGenerator::NORMALIZE_FLAT;
public const POSITION_TOP = 'top';
public const POSITION_BEFORE_HEADINGS = 'before-headings';
public const POSITION_PLACEHOLDER = 'placeholder';
/** @var ConfigurationInterface */
private $config;
public function onDocumentParsed(DocumentParsedEvent $event): void
{
$document = $event->getDocument();
$generator = new TableOfContentsGenerator(
$this->config->get('table_of_contents/style', TableOfContentsGenerator::STYLE_BULLET),
$this->config->get('table_of_contents/normalize', TableOfContentsGenerator::NORMALIZE_RELATIVE),
(int) $this->config->get('table_of_contents/min_heading_level', 1),
(int) $this->config->get('table_of_contents/max_heading_level', 6)
);
$toc = $generator->generate($document);
if ($toc === null) {
// No linkable headers exist, so no TOC could be generated
return;
}
// Add custom CSS class(es), if defined
$class = $this->config->get('table_of_contents/html_class', 'table-of-contents');
if (!empty($class)) {
$toc->data['attributes']['class'] = $class;
}
// Add the TOC to the Document
$position = $this->config->get('table_of_contents/position', self::POSITION_TOP);
if ($position === self::POSITION_TOP) {
$document->prependChild($toc);
} elseif ($position === self::POSITION_BEFORE_HEADINGS) {
$this->insertBeforeFirstLinkedHeading($document, $toc);
} elseif ($position === self::POSITION_PLACEHOLDER) {
$this->replacePlaceholders($document, $toc);
} else {
throw new InvalidOptionException(\sprintf('Invalid config option "%s" for "table_of_contents/position"', $position));
}
}
private function insertBeforeFirstLinkedHeading(Document $document, TableOfContents $toc): void
{
$walker = $document->walker();
while ($event = $walker->next()) {
if ($event->isEntering() && ($node = $event->getNode()) instanceof HeadingPermalink && ($parent = $node->parent()) instanceof Heading) {
$parent->insertBefore($toc);
return;
}
}
}
private function replacePlaceholders(Document $document, TableOfContents $toc): void
{
$walker = $document->walker();
while ($event = $walker->next()) {
// Add the block once we find a placeholder (and we're about to leave it)
if (!$event->getNode() instanceof TableOfContentsPlaceholder) {
continue;
}
if ($event->isEntering()) {
continue;
}
$event->getNode()->replaceWith(clone $toc);
}
}
public function setConfiguration(ConfigurationInterface $config)
{
$this->config = $config;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents;
use League\CommonMark\ConfigurableEnvironmentInterface;
use League\CommonMark\Event\DocumentParsedEvent;
use League\CommonMark\Extension\ExtensionInterface;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder;
final class TableOfContentsExtension implements ExtensionInterface
{
public function register(ConfigurableEnvironmentInterface $environment): void
{
$environment->addEventListener(DocumentParsedEvent::class, [new TableOfContentsBuilder(), 'onDocumentParsed'], -150);
if ($environment->getConfig('table_of_contents/position') === TableOfContentsBuilder::POSITION_PLACEHOLDER) {
$environment->addBlockParser(new TableOfContentsPlaceholderParser(), 200);
// If a placeholder cannot be replaced with a TOC element this renderer will ensure the parser won't error out
$environment->addBlockRenderer(TableOfContentsPlaceholder::class, new TableOfContentsPlaceholderRenderer());
}
}
}

View File

@@ -0,0 +1,172 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents;
use League\CommonMark\Block\Element\Document;
use League\CommonMark\Block\Element\Heading;
use League\CommonMark\Block\Element\ListBlock;
use League\CommonMark\Block\Element\ListData;
use League\CommonMark\Block\Element\ListItem;
use League\CommonMark\Block\Element\Paragraph;
use League\CommonMark\Exception\InvalidOptionException;
use League\CommonMark\Extension\HeadingPermalink\HeadingPermalink;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
use League\CommonMark\Extension\TableOfContents\Normalizer\AsIsNormalizerStrategy;
use League\CommonMark\Extension\TableOfContents\Normalizer\FlatNormalizerStrategy;
use League\CommonMark\Extension\TableOfContents\Normalizer\NormalizerStrategyInterface;
use League\CommonMark\Extension\TableOfContents\Normalizer\RelativeNormalizerStrategy;
use League\CommonMark\Inline\Element\AbstractStringContainer;
use League\CommonMark\Inline\Element\Link;
final class TableOfContentsGenerator implements TableOfContentsGeneratorInterface
{
public const STYLE_BULLET = ListBlock::TYPE_BULLET;
public const STYLE_ORDERED = ListBlock::TYPE_ORDERED;
public const NORMALIZE_DISABLED = 'as-is';
public const NORMALIZE_RELATIVE = 'relative';
public const NORMALIZE_FLAT = 'flat';
/** @var string */
private $style;
/** @var string */
private $normalizationStrategy;
/** @var int */
private $minHeadingLevel;
/** @var int */
private $maxHeadingLevel;
public function __construct(string $style, string $normalizationStrategy, int $minHeadingLevel, int $maxHeadingLevel)
{
$this->style = $style;
$this->normalizationStrategy = $normalizationStrategy;
$this->minHeadingLevel = $minHeadingLevel;
$this->maxHeadingLevel = $maxHeadingLevel;
}
public function generate(Document $document): ?TableOfContents
{
$toc = $this->createToc($document);
$normalizer = $this->getNormalizer($toc);
$firstHeading = null;
foreach ($this->getHeadingLinks($document) as $headingLink) {
$heading = $headingLink->parent();
// Make sure this is actually tied to a heading
if (!$heading instanceof Heading) {
continue;
}
// Skip any headings outside the configured min/max levels
if ($heading->getLevel() < $this->minHeadingLevel || $heading->getLevel() > $this->maxHeadingLevel) {
continue;
}
// Keep track of the first heading we see - we might need this later
$firstHeading = $firstHeading ?? $heading;
// Keep track of the start and end lines
$toc->setStartLine($firstHeading->getStartLine());
$toc->setEndLine($heading->getEndLine());
// Create the new link
$link = new Link('#' . $headingLink->getSlug(), self::getHeadingText($heading));
$paragraph = new Paragraph();
$paragraph->setStartLine($heading->getStartLine());
$paragraph->setEndLine($heading->getEndLine());
$paragraph->appendChild($link);
$listItem = new ListItem($toc->getListData());
$listItem->setStartLine($heading->getStartLine());
$listItem->setEndLine($heading->getEndLine());
$listItem->appendChild($paragraph);
// Add it to the correct place
$normalizer->addItem($heading->getLevel(), $listItem);
}
// Don't add the TOC if no headings were present
if (!$toc->hasChildren() || $firstHeading === null) {
return null;
}
return $toc;
}
private function createToc(Document $document): TableOfContents
{
$listData = new ListData();
if ($this->style === self::STYLE_BULLET) {
$listData->type = ListBlock::TYPE_BULLET;
} elseif ($this->style === self::STYLE_ORDERED) {
$listData->type = ListBlock::TYPE_ORDERED;
} else {
throw new InvalidOptionException(\sprintf('Invalid table of contents list style "%s"', $this->style));
}
$toc = new TableOfContents($listData);
$toc->setStartLine($document->getStartLine());
$toc->setEndLine($document->getEndLine());
return $toc;
}
/**
* @param Document $document
*
* @return iterable<HeadingPermalink>
*/
private function getHeadingLinks(Document $document)
{
$walker = $document->walker();
while ($event = $walker->next()) {
if ($event->isEntering() && ($node = $event->getNode()) instanceof HeadingPermalink) {
yield $node;
}
}
}
private function getNormalizer(TableOfContents $toc): NormalizerStrategyInterface
{
switch ($this->normalizationStrategy) {
case self::NORMALIZE_DISABLED:
return new AsIsNormalizerStrategy($toc);
case self::NORMALIZE_RELATIVE:
return new RelativeNormalizerStrategy($toc);
case self::NORMALIZE_FLAT:
return new FlatNormalizerStrategy($toc);
default:
throw new InvalidOptionException(\sprintf('Invalid table of contents normalization strategy "%s"', $this->normalizationStrategy));
}
}
/**
* @return string
*/
private static function getHeadingText(Heading $heading)
{
$text = '';
$walker = $heading->walker();
while ($event = $walker->next()) {
if ($event->isEntering() && ($child = $event->getNode()) instanceof AbstractStringContainer) {
$text .= $child->getContent();
}
}
return $text;
}
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents;
use League\CommonMark\Block\Element\Document;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContents;
interface TableOfContentsGeneratorInterface
{
public function generate(Document $document): ?TableOfContents;
}
// Trigger autoload without causing a deprecated error
\class_exists(TableOfContents::class);

View File

@@ -0,0 +1,47 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents;
use League\CommonMark\Block\Parser\BlockParserInterface;
use League\CommonMark\ContextInterface;
use League\CommonMark\Cursor;
use League\CommonMark\Extension\TableOfContents\Node\TableOfContentsPlaceholder;
use League\CommonMark\Util\ConfigurationAwareInterface;
use League\CommonMark\Util\ConfigurationInterface;
final class TableOfContentsPlaceholderParser implements BlockParserInterface, ConfigurationAwareInterface
{
/** @var ConfigurationInterface */
private $config;
public function parse(ContextInterface $context, Cursor $cursor): bool
{
$placeholder = $this->config->get('table_of_contents/placeholder');
if ($placeholder === null) {
return false;
}
// The placeholder must be the only thing on the line
if ($cursor->match('/^' . \preg_quote($placeholder, '/') . '$/') === null) {
return false;
}
$context->addBlock(new TableOfContentsPlaceholder());
return true;
}
public function setConfiguration(ConfigurationInterface $configuration)
{
$this->config = $configuration;
}
}

View File

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of the league/commonmark package.
*
* (c) Colin O'Dell <colinodell@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\CommonMark\Extension\TableOfContents;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
final class TableOfContentsPlaceholderRenderer implements BlockRendererInterface
{
public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false)
{
return '<!-- table of contents -->';
}
}