Skip to content

Commit

Permalink
fix: add preview capability (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
alfonsobries authored Sep 22, 2022
1 parent 854e82c commit e99bc13
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
43 changes: 42 additions & 1 deletion src/EnhancedMarkdown.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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".
*
Expand Down Expand Up @@ -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.
*
Expand Down
6 changes: 6 additions & 0 deletions tests/EnhancedMarkdownTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,9 @@

expect($field->preset)->toBe('commonmark');
});

it('generate previews', function () {
$field = new EnhancedMarkdown('content');

expect($field->previewFor('**markdown**'))->toContain('<p><strong>markdown</strong></p>');
});

0 comments on commit e99bc13

Please sign in to comment.