Skip to content

Commit 63813a3

Browse files
committed
Initial commit
0 parents  commit 63813a3

25 files changed

+775
-0
lines changed

Diff for: .editorconfig

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
root = true
2+
3+
[*]
4+
charset = utf-8
5+
end_of_line = lf
6+
insert_final_newline = true
7+
indent_style = space
8+
indent_size = 4
9+
trim_trailing_whitespace = true
10+
11+
[*.md]
12+
trim_trailing_whitespace = false
13+
14+
[*.{yml,yaml}]
15+
indent_size = 2

Diff for: .gitattributes

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
* text=auto
2+
3+
/.github export-ignore
4+
/tests export-ignore
5+
.editorconfig export-ignore
6+
.gitattributes export-ignore
7+
.gitignore export-ignore

Diff for: .gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
vendor/
2+
.phpunit.result.cache
3+
composer.lock

Diff for: LICENSE.md

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c)
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

Diff for: README.md

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Unfenced
2+
3+
Unleash your fenced code.
4+
5+
An extension for [`league/commonmark`](https://github.com/thephpleague/commonmark/).
6+
7+
## Installation
8+
9+
After installing the package, you will need to register the extension.
10+
11+
### Using `graham-campbell/markdown`
12+
13+
In your `config/markdown.php` file, add the extension somewhere after the `CommonMarkCoreExtension`:
14+
15+
```diff
16+
return [
17+
// ...
18+
'extensions' => [
19+
League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension::class,
20+
League\CommonMark\Extension\GithubFlavoredMarkdownExtension::class,
21+
+ Laravel\Unfenced\UnfencedExtension::class,
22+
],
23+
];
24+
```
25+
26+
### Manually
27+
28+
```php
29+
use Laravel\Unfenced\UnfencedExtension;
30+
use League\CommonMark\Environment\Environment;
31+
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
32+
use League\CommonMark\MarkdownConverter;
33+
34+
$environment = new Environment();
35+
$environment->addExtension(new CommonMarkCoreExtension());
36+
$environment->addExtension(new UnfencedExtension());
37+
38+
$converter = new MarkdownConverter($environment);
39+
echo $converter->convert('...');
40+
```
41+
42+
## Usage
43+
44+
Features are enabled via the "info" string of the code fence.
45+
46+
Note that this extension does not include any CSS.
47+
48+
### Adding file names
49+
50+
To display a file name above your code, add the `filename` attribute:
51+
52+
```php filename=src/Hello.php
53+
// ...
54+
```
55+
56+
### Adding tabs
57+
58+
Adjacent code fences can be grouped into a tabbed view by specifying the `tab` attribute:
59+
60+
```vue tab=Vue
61+
// ...
62+
```
63+
64+
```javascript tab=React
65+
// ...
66+
```
67+
68+
You may also include the `filename` attribute, which is especially helpful when providing code samples where the file name differs depending on the language.
69+
70+
The extension will inject JavaScript into your page when tabs are used. The JavaScript enables the following features:
71+
72+
* It will apply an `active` class to the active tab button and tab content. You may use CSS to highlight the active tab, and hide the inactive tab content.
73+
* If multiple tabbed sections are found, and they contain identical tab names, they will be synchronized. I.e, clicking the "React" tab in one section, will switch to that tab in all sections.
74+
* The active tab is saved to the browsers local storage so that is can persist between pages and even visits.

Diff for: composer.json

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"name": "laravel/unfenced",
3+
"type": "library",
4+
"license": "MIT",
5+
"autoload": {
6+
"psr-4": {
7+
"Laravel\\Unfenced\\": "src/",
8+
"Tests\\": "tests/"
9+
}
10+
},
11+
"authors": [
12+
{
13+
"name": "Jess Archer",
14+
"email": "[email protected]"
15+
}
16+
],
17+
"require": {
18+
"league/commonmark": "^2.3"
19+
},
20+
"require-dev": {
21+
"phpunit/phpunit": "^9.5"
22+
}
23+
}

Diff for: js/tabbed-code.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
function setTab(tab, group, save) {
2+
save = typeof save === 'undefined' ? true : save
3+
4+
document
5+
.querySelectorAll(`.tabbed-code[data-group="${group}"] .tabbed-code-nav-button`)
6+
.forEach(el => el.classList.remove('active'))
7+
document
8+
.querySelectorAll(`.tabbed-code[data-group="${group}"] .code-container`)
9+
.forEach(el => el.classList.remove('active'))
10+
document
11+
.querySelectorAll(`.tabbed-code[data-group="${group}"] [data-tab="${tab}"]`)
12+
.forEach(el => el.classList.add('active'))
13+
14+
if (save) {
15+
saveTab(tab, group)
16+
}
17+
}
18+
19+
function getTabs() {
20+
try {
21+
return JSON.parse(localStorage.tabs)
22+
} catch {
23+
return {}
24+
}
25+
}
26+
27+
function saveTab(tab, group) {
28+
localStorage.tabs = JSON.stringify({
29+
...getTabs(),
30+
[group]: tab,
31+
})
32+
}
33+
34+
function restoreTabs() {
35+
Object.entries(getTabs()).forEach(([group, tab]) => setTab(tab, group, false))
36+
}
37+
38+
restoreTabs()

Diff for: phpunit.xml

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
4+
colors="true"
5+
>
6+
<testsuites>
7+
<testsuite name="Tests">
8+
<directory suffix="Test.php">./tests</directory>
9+
</testsuite>
10+
</testsuites>
11+
<coverage processUncoveredFiles="true">
12+
<include>
13+
<directory suffix=".php">./src</directory>
14+
</include>
15+
</coverage>
16+
</phpunit>

Diff for: src/Node/FencedCodeContainer.php

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
namespace Laravel\Unfenced\Node;
4+
5+
use Laravel\Unfenced\Parser\FencedCodeAttributeParser;
6+
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
7+
use League\CommonMark\Node\Block\AbstractBlock;
8+
9+
class FencedCodeContainer extends AbstractBlock
10+
{
11+
public array $attributes;
12+
13+
public function __construct(FencedCode $fencedCode)
14+
{
15+
$this->attributes = $this->parseAttributes($fencedCode);
16+
17+
$this->appendChild($fencedCode);
18+
}
19+
20+
public function filename(): ?string
21+
{
22+
return $this->attributes['filename'] ?? null;
23+
}
24+
25+
public function hasFilename(): bool
26+
{
27+
return isset($this->attributes['filename']);
28+
}
29+
30+
public function tab(): ?string
31+
{
32+
return $this->attributes['tab'] ?? null;
33+
}
34+
35+
public function hasTab(): bool
36+
{
37+
return isset($this->attributes['tab']);
38+
}
39+
40+
protected function parseAttributes(FencedCode $fencedCode)
41+
{
42+
return (new FencedCodeAttributeParser())->parse($fencedCode);
43+
}
44+
}

Diff for: src/Node/TabbedCode.php

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
namespace Laravel\Unfenced\Node;
4+
5+
use League\CommonMark\Node\Block\AbstractBlock;
6+
7+
class TabbedCode extends AbstractBlock
8+
{
9+
public readonly string $group;
10+
11+
/**
12+
* @param array<FencedCodeContainer> $children
13+
*/
14+
public function __construct(array $children)
15+
{
16+
$this->group = $this->generateTabHash($children);
17+
18+
$this->replaceChildren($children);
19+
}
20+
21+
/**
22+
* @param array<FencedCodeContainer> $children
23+
*/
24+
protected function generateTabHash(array $children)
25+
{
26+
return md5(implode('', array_map(fn (FencedCodeContainer $child) => $child->tab(), $children)));
27+
}
28+
}

Diff for: src/Node/TabbedCodeScript.php

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
namespace Laravel\Unfenced\Node;
4+
5+
use League\CommonMark\Node\Node;
6+
7+
class TabbedCodeScript extends Node
8+
{
9+
}

Diff for: src/Parser/FencedCodeAttributeParser.php

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
3+
namespace Laravel\Unfenced\Parser;
4+
5+
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
6+
7+
class FencedCodeAttributeParser
8+
{
9+
/**
10+
* @return array<string, string|bool>
11+
*/
12+
public function parse(FencedCode $node): array
13+
{
14+
$info = $node->getInfo();
15+
16+
if ($info === null) {
17+
return [];
18+
}
19+
20+
preg_match('/^(\w+\b(?!=))(?:\s(.*))?/', $info, $matches);
21+
22+
$language = $matches[1] ?? null;
23+
$attributes = $matches[2] ?? null;
24+
25+
if ($attributes === null) {
26+
return [];
27+
}
28+
29+
return $this->parseAttributes($attributes);
30+
}
31+
32+
/**
33+
* @return array<string, string|bool>
34+
*/
35+
protected function parseAttributes(string $attributes): array
36+
{
37+
preg_match_all(
38+
'/([^=\s]+)(?:=(?:["\']?((?:.(?!["\']?\s+(?:\S+)=|\s*\/?[>"\']))+.)["\']?))?/',
39+
$attributes,
40+
$matches,
41+
PREG_UNMATCHED_AS_NULL
42+
);
43+
44+
$result = [];
45+
46+
foreach ($matches[1] as $i => $key) {
47+
$result[$key] = $matches[2][$i] ?? true;
48+
}
49+
50+
return $result;
51+
}
52+
}

Diff for: src/Renderer/FencedCodeContainerRenderer.php

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
namespace Laravel\Unfenced\Renderer;
4+
5+
use Laravel\Unfenced\Node\FencedCodeContainer;
6+
use League\CommonMark\Node\Node;
7+
use League\CommonMark\Renderer\ChildNodeRendererInterface;
8+
use League\CommonMark\Renderer\NodeRendererInterface;
9+
use League\CommonMark\Util\HtmlElement;
10+
11+
class FencedCodeContainerRenderer implements NodeRendererInterface
12+
{
13+
public function render(Node $node, ChildNodeRendererInterface $childRenderer)
14+
{
15+
assert($node instanceof FencedCodeContainer);
16+
17+
$separator = $childRenderer->getInnerSeparator();
18+
19+
return new HtmlElement(
20+
'div',
21+
array_filter([
22+
'class' => 'code-container',
23+
'data-tab' => $node->tab(),
24+
]),
25+
[
26+
$separator,
27+
$this->renderFilename($node, $separator),
28+
$node->hasFilename() ? $separator : null,
29+
$childRenderer->renderNodes($node->children()),
30+
$separator,
31+
]
32+
);
33+
}
34+
35+
protected function renderFilename(FencedCodeContainer $node)
36+
{
37+
if (! $node->hasFilename()) {
38+
return null;
39+
}
40+
41+
return new HtmlElement(
42+
'div',
43+
['class' => 'code-container-filename'],
44+
[
45+
$node->filename()
46+
],
47+
);
48+
}
49+
}

0 commit comments

Comments
 (0)