born05 / craft-imagehotspots

Image Hotspots fieldtype for Craft CMS
Other
5 stars 3 forks source link

GraphQL Support #1

Closed rocknrolaf closed 4 years ago

rocknrolaf commented 4 years ago

Hi there!

first of all thank you for the plugin! We wanted to use this plugin with the internal GraphQL functionality of Craft and found a solution. Maybe you could check it out and integrate it.

We added a HotspotType class to define the type and coordinates:

use craft\gql\GqlEntityRegistry;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;

class HotspotType
{

    public static function getName (): string
    {
        return 'Hotspot';
    }

    public static function getFieldDefinitions (): array
    {
        return [
            'x'     => [
                'name'        => 'x',
                'type'        => Type::float(),
                'description' => 'The x coordinate.',
            ],
            'y'     => [
                'name'        => 'y',
                'type'        => Type::float(),
                'description' => 'The y coordinate.',
            ],
        ];
    }

    public static function getType (): Type
    {
        if ($type = GqlEntityRegistry::getEntity(static::class))
            return $type;

        return GqlEntityRegistry::createEntity(
            static::class,
            new ObjectType([
                'name' => static::getName(),
                'fields' => static::class . '::getFieldDefinitions',
            ])
        );
    }

}

After that we extended from your field type. But maybe you would only have to add the "getContentGqlType" to your existing field type.

use born05\imagehotspots\fields\ImageHotspots;

class GqlImageHotspotsField extends ImageHotspots {

    public static function displayName(): string
    {
        return 'Image Hotspot GraphQL';
    }

    public function getContentGqlType() {
        return HotspotType::getType();
    }

}
rocknrolaf commented 4 years ago

I forgot to mention the events for registering the type:

use craft\services\Gql;
use craft\events\RegisterComponentTypesEvent;
use craft\events\RegisterGqlTypesEvent;

Event::on(Gql::class, Gql::EVENT_REGISTER_GQL_TYPES, function(RegisterGqlTypesEvent $event) {
    $event->types[] = HotspotType::class;
});
Event::on(
    Fields::class,
    Fields::EVENT_REGISTER_FIELD_TYPES,
    function (RegisterComponentTypesEvent $event) {
        $event->types[] = ImageHotspotsField::class;
    }
);
roelvanhintum commented 4 years ago

Looks awesome! I'll integrate it as soon as possible. Thanks @rocknrolaf!

roelvanhintum commented 4 years ago

Supported as of 1.0.0 see 2826dbf