Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for intelligent recognition of LaTeX and custom internal hosts config #44

Merged
merged 5 commits into from
Jan 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ jobs:
mkdir temp
cp -r vendor temp/
cp composer.json temp/
cp MarkdownParse.php temp/
php -d phar.readonly=0 vendor/bin/phar-composer build temp vendor.phar

- name: Package Files
Expand All @@ -37,7 +38,6 @@ jobs:
mkdir MarkdownParse
mv vendor.phar MarkdownParse/
cp LICENSE.md MarkdownParse/
cp MarkdownParse.php MarkdownParse/
cp Plugin.php MarkdownParse/
cp README.md MarkdownParse/
zip -r MarkdownParse.zip MarkdownParse
Expand Down
93 changes: 81 additions & 12 deletions MarkdownParse.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@

namespace TypechoPlugin\MarkdownParse;

if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
} elseif (file_exists(__DIR__ . 'vendor.phar')) {
require_once 'phar://' . __DIR__ . '/vendor.phar/vendor/autoload.php';
}
require_once __DIR__ . '/vendor/autoload.php';

use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\Autolink\AutolinkExtension;
Expand Down Expand Up @@ -38,6 +34,9 @@ class MarkdownParse
// Flag to determine if LaTex support is needed
private bool $isNeedLaTex = false;

// The internal hosts, supports regular expressions ("/(^|\.)example\.com$/"), multiple values can be separated by commas.
private string $internalHosts = '';

// Singleton instance of MarkdownParse
private static ?MarkdownParse $instance = null;

Expand Down Expand Up @@ -74,11 +73,66 @@ public static function getInstance(): MarkdownParse
*/
public function parse(string $text, array $config = []): string
{
list($text, $config) = $this->preParse($text, $config);

$environment = new Environment(array_merge($this->getConfig(), $config));

$this->addCommonMarkExtensions($environment);

return (new MarkdownConverter($environment))->convert($text)->getContent();
$htmlContent = (new MarkdownConverter($environment))->convert($text)->getContent();

list($htmlContent, $config) = $this->postParse($htmlContent, $config);

return $htmlContent;
}

/**
* Placeholder function for actions to be performed before parsing
*
* @param string $text The input text
* @param array $config Optional configuration for the parsing process
* @return array Result of actions before parsing
*/
public function preParse(string $text, array $config = []): array
{
// Remove Table of Contents config if it is not enabled
if (!$this->isTocEnable) {
$config['table_of_contents']['placeholder'] = '';
}

// Set internal hosts for external link config
if (!empty($this->internalHosts)) {
$config['external_link']['internal_hosts'] = explode(',', $this->internalHosts);
}

// Check if LaTeX is needed by searching for $$ or $ in the text
if (!$this->isNeedLaTex) {
$this->isNeedLaTex = (bool) preg_match('/\${1,2}[^`]*?\${1,2}/m', $text);
}

// Replace double $$ at the beginning and end of the text with <div> tags
$count = 0;
$text = preg_replace('/(^\${2,})(.*)(\${2,}$)/ms', '<div>$1$2$3</div>', $text, -1, $count);
$this->isNeedLaTex = $this->isNeedLaTex || $count > 0;

return [$text, $config];
}

/**
* Placeholder function for actions to be performed after parsing
*
* @param string $htmlContent The parsed HTML content
* @param array $config Optional configuration for the parsing process
* @return array Result of actions after parsing
*/
public function postParse(string $htmlContent, array $config = []): array
{
// If LaTeX is needed, remove <div> tags added during preParse
if ($this->isNeedLaTex) {
$htmlContent = str_replace(['<div>$$', '$$</div>'], '$$', $htmlContent);
}

return [$htmlContent, $config];
}

/**
Expand All @@ -96,7 +150,7 @@ public function getConfig(): array
'placeholder' => '[TOC]',
],
'external_link' => [
'internal_hosts' => ['foo.example.com', 'bar.example.com', '/(^|\.)google\.com$/'],
'internal_hosts' => [],
'open_in_new_window' => true,
],
'default_attributes' => [
Expand All @@ -113,11 +167,6 @@ public function getConfig(): array
]
];

// Remove Table of Contents config if it is not enabled
if (!$this->isTocEnable) {
$defaultConfig['table_of_contents']['placeholder'] = '';
}

return $defaultConfig;
}

Expand Down Expand Up @@ -203,4 +252,24 @@ public function setIsNeedLaTex(bool $isNeedLaTex): void
{
$this->isNeedLaTex = $isNeedLaTex;
}

/**
* Get the internal hosts value
*
* @return string The internal hosts value
*/
public function getInternalHosts(): string
{
return $this->internalHosts;
}

/**
* Set the internal hosts value
*
* @param string $internalHosts The internal hosts value
*/
public function setInternalHosts(string $internalHosts): void
{
$this->internalHosts = $internalHosts;
}
}
15 changes: 9 additions & 6 deletions Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace TypechoPlugin\MarkdownParse;

require_once 'phar://' . __DIR__ . '/vendor.phar/MarkdownParse.php';

use Typecho\Plugin\PluginInterface;
use Typecho\Widget\Helper\Form;
use Widget\Options;
Expand Down Expand Up @@ -60,6 +62,9 @@ public static function config(Form $form)
$elementCDNSource = new Form\Element\Radio('cdn_source', array_combine(array_keys(self::CDN_SOURCE_MERMAID), array_map('_t', array_keys(self::CDN_SOURCE_MERMAID))), self::CDN_SOURCE_DEFAULT);
$form->addInput($elementCDNSource);

$elementInternalHosts = new Form\Element\Text('internal_hosts', null, parse_url(Options::alloc()->siteUrl(), PHP_URL_HOST), _t('设置内部链接'), _t('默认为本站点地址,支持正则表达式("/(^|\.)example\.com$/"),多个可用英文逗号分隔。外部链接解析策略:默认在新窗口中打开,并加上 "noopener noreferrer" 属性'));
$form->addInput($elementInternalHosts);

$elementHelper = new Form\Element\Radio('show_help_info', [], self::RADIO_VALUE_DISABLE, _t('<a href="https://www.chengxiaobai.cn/php/markdown-parser-library.html/">点击查看更新信息</a>'), _t('<a href="https://www.chengxiaobai.cn/record/markdown-concise-grammar-manual.html/">点击查看语法手册</a>'));
$form->addInput($elementHelper);
}
Expand All @@ -71,9 +76,10 @@ public static function personalConfig(Form $form)

public static function parse($text)
{
$markdownParser = ParsedownExtension::getInstance();
$markdownParser = MarkdownParse::getInstance();

$markdownParser->setIsTocEnable((bool)Options::alloc()->plugin('MarkdownParse')->is_available_toc);
$markdownParser->setInternalHosts((string)Options::alloc()->plugin('MarkdownParse')->internal_hosts);

return $markdownParser->parse($text);
}
Expand All @@ -83,12 +89,9 @@ public static function resourceLink()
$configMermaid = (int)Options::alloc()->plugin('MarkdownParse')->is_available_mermaid;
$configLaTex = (int)Options::alloc()->plugin('MarkdownParse')->is_available_mathjax;
$configCDN = (string)Options::alloc()->plugin('MarkdownParse')->cdn_source;
$markdownParser = ParsedownExtension::getInstance();
$markdownParser = MarkdownParse::getInstance();
$isAvailableMermaid = $configMermaid === self::RADIO_VALUE_FORCE || ($markdownParser->getIsNeedMermaid() && $configMermaid === self::RADIO_VALUE_AUTO);

// @Todo performance for latex
// $isAvailableMathjax = $configLaTex === self::RADIO_VALUE_FORCE || ($markdownParser->getIsNeedLaTex() && $configLaTex === self::RADIO_VALUE_AUTO);
$isAvailableMathjax = $configLaTex === self::RADIO_VALUE_FORCE || $configLaTex === self::RADIO_VALUE_AUTO;
$isAvailableMathjax = $configLaTex === self::RADIO_VALUE_FORCE || ($markdownParser->getIsNeedLaTex() && $configLaTex === self::RADIO_VALUE_AUTO);

$resourceContent = '';

Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"require": {
"php": "^8.0",
"league/commonmark": "^2.4",
"wnx/commonmark-mark-extension": "^1.2",
"simonvomeyser/commonmark-ext-lazy-image": "^2.0",
Expand Down
6 changes: 4 additions & 2 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions tests/test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

require_once 'phar://' . __DIR__ . '/../vendor.phar/MarkdownParse.php';

use TypechoPlugin\MarkdownParse\MarkdownParse;

$markdownParser = MarkdownParse::getInstance();

$markdownParser->setIsTocEnable(true);

echo $markdownParser->parse('Hello World!');