Skip to content

Commit

Permalink
Add new html to markdown converter for strikethrough support (#1275)
Browse files Browse the repository at this point in the history
  • Loading branch information
BentiGorlich authored Dec 10, 2024
1 parent 8cbb51c commit a007680
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Service/ActivityPub/MarkdownConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function convert(string $value): string
{
$converter = new HtmlConverter(['strip_tags' => true]);
$converter->getEnvironment()->addConverter(new TableConverter());
$converter->getEnvironment()->addConverter(new StrikethroughConverter());
$value = stripslashes($converter->convert($value));

preg_match_all('/\[([^]]*)\] *\(([^)]*)\)/i', $value, $matches, PREG_SET_ORDER);
Expand Down
48 changes: 48 additions & 0 deletions src/Service/ActivityPub/StrikethroughConverter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace App\Service\ActivityPub;

use League\HTMLToMarkdown\Configuration;
use League\HTMLToMarkdown\ConfigurationAwareInterface;
use League\HTMLToMarkdown\Converter\ConverterInterface;
use League\HTMLToMarkdown\ElementInterface;

/**
* Inspired by https://github.com/thephpleague/html-to-markdown/blob/master/src/Converter/EmphasisConverter.php.
*/
class StrikethroughConverter implements ConverterInterface, ConfigurationAwareInterface
{
protected Configuration $config;

public function getSupportedTags(): array
{
return ['del', 'strike'];
}

public function setConfig(Configuration $config): void
{
$this->config = $config;
}

public function convert(ElementInterface $element): string
{
$value = $element->getValue();
if (!trim($value)) {
return $value;
}

$prefix = ltrim($value) !== $value ? ' ' : '';
$suffix = rtrim($value) !== $value ? ' ' : '';

/* If this node is immediately preceded or followed by one of the same type don't emit
* the start or end $style, respectively. This prevents <del>foo</del><del>bar</del> from
* being converted to ~~foo~~~~bar~~ which is incorrect. We want ~~foobar~~ instead.
*/
$preStyle = \in_array($element->getPreviousSibling()?->getTagName(), $this->getSupportedTags()) ? '' : '~~';
$postStyle = \in_array($element->getNextSibling()?->getTagName(), $this->getSupportedTags()) ? '' : '~~';

return $prefix.$preStyle.trim($value).$postStyle.$suffix;
}
}

0 comments on commit a007680

Please sign in to comment.