From e99bc13dd1fe7731b4d25e7ac38485f4904fa44a Mon Sep 17 00:00:00 2001 From: Alfonso Bribiesca Date: Thu, 22 Sep 2022 04:32:39 -0500 Subject: [PATCH] fix: add preview capability (#7) --- src/EnhancedMarkdown.php | 43 +++++++++++++++++++++++++++++++++- tests/EnhancedMarkdownTest.php | 6 +++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/EnhancedMarkdown.php b/src/EnhancedMarkdown.php index 8d4639e..9b36205 100644 --- a/src/EnhancedMarkdown.php +++ b/src/EnhancedMarkdown.php @@ -4,12 +4,17 @@ namespace Ardenthq\EnhancedMarkdown; +use Laravel\Nova\Contracts\Previewable; +use Laravel\Nova\Fields\Markdown\CommonMarkPreset; +use Laravel\Nova\Fields\Markdown\DefaultPreset; +use Laravel\Nova\Fields\Markdown\MarkdownPreset; +use Laravel\Nova\Fields\Markdown\ZeroPreset; use Laravel\Nova\Fields\Trix; use Laravel\Nova\Trix\DeleteAttachments; use Laravel\Nova\Trix\DetachAttachment; use Laravel\Nova\Trix\DiscardPendingAttachments; -class EnhancedMarkdown extends Trix +class EnhancedMarkdown extends Trix implements Previewable { /** * The field's component. @@ -32,6 +37,17 @@ class EnhancedMarkdown extends Trix */ public $preset = 'default'; + /** + * The built-in presets for the Markdown field. + * + * @var string[] + */ + public $presets = [ + 'default' => DefaultPreset::class, + 'commonmark' => CommonMarkPreset::class, + 'zero' => ZeroPreset::class, + ]; + /** * Define the preset the field should use. Can be "commonmark", "zero", and "default". * @@ -67,6 +83,31 @@ public function withFiles($disk = 'public', $path = '/') return $this; } + /** + * Return a preview for the given field value. + * + * @param string $value + * @return string + */ + public function previewFor($value) + { + return $this->renderer()->convert($value); + } + + /** + * @return MarkdownPreset + */ + public function renderer() + { + /** @var string $preset */ + $preset = $this->preset; + + /** @var MarkdownPreset $renderer */ + $renderer = new $this->presets[$preset](); + + return $renderer; + } + /** * Prepare the element for JSON serialization. * diff --git a/tests/EnhancedMarkdownTest.php b/tests/EnhancedMarkdownTest.php index 50444b8..b17fda1 100644 --- a/tests/EnhancedMarkdownTest.php +++ b/tests/EnhancedMarkdownTest.php @@ -43,3 +43,9 @@ expect($field->preset)->toBe('commonmark'); }); + +it('generate previews', function () { + $field = new EnhancedMarkdown('content'); + + expect($field->previewFor('**markdown**'))->toContain('

markdown

'); +});