Skip to content

Commit

Permalink
Preserve the correct last href in Blocks -> Markdown conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
adamziel committed Jan 2, 2025
1 parent 86ab57d commit 6be33e3
Showing 1 changed file with 16 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ private function block_to_markdown($block) {
$attributes['alt'] = $processor->get_attribute('alt');
}
}
$escaped_url = $attributes['url'] ?? '';
// @TODO: Figure out the correct markdown escaping for these things
$escaped_url = str_replace(' ', '%20', $escaped_url);
$escaped_url = str_replace(')', '%29', $escaped_url);

$escaped_url = self::escape_url(
$attributes['url'] ?? ''
);

$escaped_alt = $attributes['alt'] ?? '';
$escaped_alt = str_replace(['[', ']'], '', $escaped_alt);
Expand Down Expand Up @@ -261,6 +261,7 @@ private function html_to_markdown($html, $parents = []) {
$processor = WP_Data_Liberation_HTML_Processor::create_fragment($html);
$markdown = '';

$last_href = null;
while ($processor->next_token()) {
if ($processor->get_token_type() === '#text') {
$markdown .= $processor->get_modifiable_text();
Expand All @@ -269,7 +270,6 @@ private function html_to_markdown($html, $parents = []) {
continue;
}

$last_href = null;
$tag_name = $processor->get_tag();
$sign = $processor->is_tag_closer() ? '-' : (
$processor->expects_closer() ? '+' : ''
Expand Down Expand Up @@ -303,12 +303,15 @@ private function html_to_markdown($html, $parents = []) {
break;

case '+A':
$last_href = $processor->get_attribute('href') ?? '';
$last_href = self::escape_url(
$processor->get_attribute('href') ?? ''
);
$markdown .= '[';
break;

case '-A':
$markdown .= "]($last_href)";
$last_href = null;
break;

case 'BR':
Expand All @@ -326,6 +329,13 @@ private function html_to_markdown($html, $parents = []) {
return $markdown;
}

// @TODO: Figure out the correct markdown escaping for URLs
static private function escape_url($url) {
$escaped_url = str_replace(' ', '%20', $url);
$escaped_url = str_replace(')', '%29', $escaped_url);
return $escaped_url;
}

private function has_parent($parent) {
return in_array($parent, $this->parents, true);
}
Expand Down

0 comments on commit 6be33e3

Please sign in to comment.