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

Feat: table of contents on converter #266

Merged
merged 2 commits into from
Dec 19, 2023
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ Styling the output is entirely up to you.
{!! tiptap_converter()->asText($post->content) !!}
```

#### Table of Contents

If you are using the `heading` tool in your editor you can also generate a table of contents from the headings in the content. This is done by passing the content to the `asHTML()` method and setting the `toc` option to `true`. You can also pass a `maxDepth` option to limit the depth of headings to include in the table of contents.

```blade
<!-- this will generate links for all headings up to h3 -->
{!! tiptap_converter()->asHTML($post->content, toc: true, maxDepth: 3) !!}

<!-- this will generate a table of contents with headings up to h3 -->
{!! tiptap_converter()->asToc($post->content, maxDepth: 3) !!}
```

## Config

The plugin will work without publishing the config, but should you need to change any of the default settings you can publish the config file with the following Artisan command:
Expand Down
19 changes: 19 additions & 0 deletions resources/views/table-of-contents.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<ul>
@foreach ($headings as $heading)
@if (array_key_exists($loop->index + 1, $headings) && $headings[$loop->index + 1]['level'] === $heading['level'])
<li>
<a href="#{{ $heading['id'] }}">{{ $heading['text'] }}</a>
</li>
@else
@endif
<li>
@if ($heading[$loop->index + 1] && $heading[$loop->index + 1]['level'] > $heading['level'])
<ul>
@endif
<a href="#{{ $heading['id'] }}">{{ $heading['text'] }}</a>
@if ($heading[$loop->index + 1] && $heading[$loop->index + 1]['level'] > $heading['level'])
<ul>
@endif
</li>
@endforeach
</ul>
2 changes: 1 addition & 1 deletion src/Extensions/Extensions/ClassExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function addGlobalAttributes(): array
return InlineStyle::getAttribute($DOMNode, 'class') ?? false;
},
'renderHTML' => function ($attributes) {
if (! $attributes->class) {
if (! property_exists($attributes, 'class')) {
return null;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Extensions/Extensions/IdExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ public function addGlobalAttributes(): array
'id' => [
'default' => null,
'parseHTML' => function ($DOMNode) {
return InlineStyle::getAttribute($DOMNode, 'id') ?? false;
return InlineStyle::getAttribute($DOMNode, 'id');
},
'renderHTML' => function ($attributes) {
if (! $attributes->id) {
if (! property_exists($attributes, 'id')) {
return null;
}

Expand Down
117 changes: 112 additions & 5 deletions src/TiptapConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use FilamentTiptapEditor\Extensions\Extensions;
use FilamentTiptapEditor\Extensions\Marks;
use FilamentTiptapEditor\Extensions\Nodes;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Tiptap\Editor;
use Tiptap\Extensions\StarterKit;
use Tiptap\Marks\Highlight;
Expand All @@ -24,6 +26,8 @@ class TiptapConverter

protected ?array $blocks = null;

protected bool $tableOfContents = false;

public function getEditor(): Editor
{
return $this->editor ??= new Editor([
Expand Down Expand Up @@ -88,20 +92,123 @@ public function getExtensions(): array
];
}

public function asHTML(string | array $content): string
public function asHTML(string | array $content, bool $toc = false, int $maxDepth = 3): string
{
return $this->getEditor()->setContent($content)->getHTML();
$editor = $this->getEditor()->setContent($content);

if ($toc) {
$this->parseHeadings($editor, $maxDepth);
}

return $editor->getHTML();
}

public function asJSON(string | array $content, bool $decoded = false): string | array
public function asJSON(string | array $content, bool $decoded = false, bool $toc = false, int $maxDepth = 3): string | array
{
$content = $this->getEditor()->setContent($content)->getJSON();
$editor = $this->getEditor()->setContent($content);

if ($toc) {
$this->parseHeadings($editor, $maxDepth);
}

return $decoded ? json_decode($content, true) : $content;
return $decoded ? json_decode($editor->getJSON(), true) : $editor->getJSON();
}

public function asText(string | array $content): string
{
return $this->getEditor()->setContent($content)->getText();
}

public function asTOC(string | array $content, int $maxDepth = 3): string
{
if (is_string($content)) {
$content = $this->asJSON($content, decoded: true);
}

$headings = $this->parseTocHeadings($content['content'], $maxDepth);

return $this->generateNestedTOC($headings, $headings[0]['level']);
}

public function parseHeadings(Editor $editor, int $maxDepth = 3): Editor
{
$editor->descendants(function (&$node) use ($maxDepth) {
if ($node->type !== 'heading') {
return;
}

if ($node->attrs->level > $maxDepth) {
return;
}

if (! property_exists($node->attrs, 'id') || $node->attrs->id === null) {
$node->attrs->id = str(collect($node->content)->map(function ($node) {
return $node->text;
})->implode(' '))->kebab()->toString();
}

array_unshift($node->content, (object) [
"type" => "text",
"text" => "#",
"marks" => [
[
"type" => "link",
"attrs" => [
"href" => "#" . $node->attrs->id,
]
]
]
]);
});

return $editor;
}

public function parseTocHeadings(array $content, int $maxDepth = 3): array
{
$headings = [];

foreach ($content as $node) {
if ($node['type'] === 'heading') {
if ($node['attrs']['level'] <= $maxDepth) {
$text = collect($node['content'])->map(function ($node) {
return $node['text'];
})->implode(' ');

if (!isset($node['attrs']['id'])) {
$node['attrs']['id'] = str($text)->kebab()->toString();
}

$headings[] = [
'level' => $node['attrs']['level'],
'id' => $node['attrs']['id'],
'text' => $text,
];
}
} elseif (array_key_exists('content', $content)) {
$this->parseTocHeadings($content, $maxDepth);
}
}

return $headings;
}

public function generateNestedTOC(array $headings, int $parentLevel = 0): string
{
$result = '<ul>';
$prev = $parentLevel;

foreach ($headings as $item) {
$prev <= $item['level'] ?: $result .= str_repeat('</ul>', $prev - $item['level']);
$prev >= $item['level'] ?: $result .= '<ul>';

$result .= '<li><a href="#' . $item['id'] . '">' . $item['text'] . '</a></li>';

$prev = $item['level'];
}

$result .= '</ul>';

return $result;
}
}
8 changes: 8 additions & 0 deletions src/TiptapFaker.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ public function heading(int | string | null $level = 2): static
return $this;
}

public function headingWithLink(int | string | null $level = 2): static
{
$heading = $this->faker->words(rand(2, 3), true) . '<a href="#">' . $this->faker->words(rand(2, 3), true) . '</a>' . $this->faker->words(rand(2, 3), true);
$this->output .= '<h' . $level . '>' . Str::title($heading) . '</h' . $level . '>';

return $this;
}

public function emptyParagraph(): static
{
$this->output .= '<p></p>';
Expand Down