sheadawson / silverstripe-shortcodable

Provides a GUI for CMS users to insert Shortcodes into the HTMLEditorField + an API for developers to define Shortcodable DataObjects and Views.
MIT License
48 stars 36 forks source link

Add option to display shortcode visual placeholder #32

Closed satrun77 closed 8 years ago

satrun77 commented 8 years ago

Issue #9

With this change the Shortcodable class have the option to implement the method getShortcodePlaceHolder. This method must output an image that will be used instead of the shortcode text. This method is optional, if it does not exists the functionality fallback to plain text.

The properties of the shortcode are stored in the title attribute of the image displayed in TinyMCE. So they are visible to user on hover.

Double click the placeholder image will fire the edit event same as highlighting the shortcode text.

Example:

class ImageGallery extends DataObject
{
    ...
    public function getShortcodePlaceHolder()
    {
        // Path to font file & size
        $fontFile = Director::baseFolder() . '/' . $this->ThemeDir() . '/fonts/FiraSans-Medium.ttf';
        $fontSize = 12;

        // Shortcode id value
        $text = Controller::curr()->getRequest()->param('ID');

        // Create an image with the shortcode id in center
        $imageBox = imagettfbbox($fontSize, 0, $fontFile, $text);

        $width = abs($imageBox[4] - $imageBox[0]) + 10;
        $height = abs($imageBox[5] - $imageBox[1]) + 10;

        $image = imagecreatetruecolor($width, $height);

        $color = imagecolorallocate($image, 1, 0, 0);
        $backgroundColor = imagecolorallocate($image, 200, 200, 200);

        imagefill($image, 0, 0, $backgroundColor);

        // Padding of 5 pixels.
        $x = 5;
        $y = $height - 5;
        imagettftext($image, $fontSize, 0, $x, $y, $color, $fontFile, $text);

        // Generate and send image to browser:
        header('Content-type: image/png');
        imagepng($image);
        imagedestroy($image);

        die;
    }
sheadawson commented 8 years ago

Hey thanks for your work on this, really appreciate it. Been wanting to add placeholders for a long time. I've just added a couple of changes to how it works, documented the feature in the readme and published a new release.