UNPKG

@danielbiegler/vendure-plugin-blurry-image-lazy-loading

Version:

Generates image hashes for displaying blurry previews when loading images on the frontend.

205 lines (204 loc) 7.34 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var PreviewImageHashPlugin_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.PreviewImageHashPlugin = void 0; const core_1 = require("@vendure/core"); const admin_resolver_1 = require("./api/admin.resolver"); const api_extensions_1 = require("./api/api-extensions"); const constants_1 = require("./constants"); const PreviewImageHashService_1 = require("./services/PreviewImageHashService"); /** * The PreviewImageHashPlugin generates image hashes for displaying blurry previews when loading images on the frontend. * * Adding this plugin requires a migration because it introduces a custom field `previewImageHash` on the Asset entity. * * ### 1. Add the plugin to your Vendure Config * * The simplest way is relying on the defaults and just adding the plugin with a hashing strategy. * * ```ts * export const config: VendureConfig = { * // ... * plugins: [ * PreviewImageHashPlugin.init({ * hashingStrategy: new ThumbHashStrategy(), // Recommended * }), * ], * } * ``` * * It's possible to pass in further configurations into both the plugin and the strategies, for example: * * ```ts * PreviewImageHashPlugin.init({ * enqueueHashingAfterAssetCreation: false, * hashingStrategy: new ThumbHashStrategy({ * encoding: "hex", * resizeOptions: { * width: 32, * fit: "contain" * } * }), * }) * ``` * * Please refer to the specific docs for how and what you can customize. * * ### 2. Generate hashes * * By default the option `enqueueHashingAfterAssetCreation` automatically adds hashing tasks to the dedicated job queue for newly added assets. * * For existing assets you can produce hashes either synchronously or via the job queue, of which the latter is recommended for production environments, via the admin API: * * ```graphql * mutation { * pluginPreviewImageHashCreateImageHash( * input: { * idAsset: "example123", * runSynchronously: true, # False by default * } * ) { * # When running asynchronously you get a short status response. * ... on PluginPreviewImageHashResult { * code * jobsAddedToQueue * message * } * * # When running synchronously, you get the Asset directly. * # This is useful for scripts. * ... on Asset { * id * name * customFields { * previewImageHash * } * } * } * } * ``` * * ### 3. Consume the hashes in your frontend * * Now that your assets have hashes you may consume them on your frontend. How and where you consume them exactly is dependent on your setup, but in general it involves the following steps. * * 1. Retrieve assets, for example: * * ```graphql * query { * collection(slug: "example") { * productVariants(options: { take: 10 }) { * items { * name * featuredAsset { * preview * width * height * customFields { * previewImageHash * } * } * } * } * } * } * ``` * * 2. For example with the `ThumbHashStrategy` and its `BufferEncoding` set to the default `"base64"` you can now decode the hashes with the provided helper like so: * * ```ts * const buffer = Buffer.from(previewImagehash, "base64"); * const dataUrl = thumbHashToDataURL(buffer); * ``` * * 3. Use the result in your frontend, for example in an imaginary react component. * * ```jsx * <MyCustomImgComponent * previewSrc={dataUrl} * src={asset.preview} * width={asset.width} * height={asset.height} * /> * ``` * * @category Plugin */ let PreviewImageHashPlugin = class PreviewImageHashPlugin { static { PreviewImageHashPlugin_1 = this; } /** @internal */ static options; /** * The static `init()` method is called with the options to configure the plugin. * * @example * ```ts * PreviewImageHashPlugin.init({ * hashingStrategy: new ThumbHashStrategy(), * }), * ``` */ static init(options) { this.options = options; return PreviewImageHashPlugin_1; } }; exports.PreviewImageHashPlugin = PreviewImageHashPlugin; exports.PreviewImageHashPlugin = PreviewImageHashPlugin = PreviewImageHashPlugin_1 = __decorate([ (0, core_1.VendurePlugin)({ imports: [core_1.PluginCommonModule], providers: [ { provide: constants_1.PLUGIN_INIT_OPTIONS, useFactory: () => PreviewImageHashPlugin.options, }, PreviewImageHashService_1.PreviewImageHashService, ], adminApiExtensions: { resolvers: [admin_resolver_1.AdminResolver, admin_resolver_1.PluginPreviewImageHashCreateResultResolver], schema: api_extensions_1.adminApiExtensions, }, configuration: (config) => { config.customFields.Asset.push({ name: constants_1.CUSTOMFIELD_NAME, type: "string", nullable: true, public: true, unique: false, readonly: true, label: [ { languageCode: core_1.LanguageCode.en, value: "Preview Image Hash" }, { languageCode: core_1.LanguageCode.de, value: "Vorschaubild Hash" }, { languageCode: core_1.LanguageCode.nl, value: "Miniatuurafbeelding Hash" }, { languageCode: core_1.LanguageCode.ru, value: "Хеш миниатюр" }, ], description: [ { languageCode: core_1.LanguageCode.en, value: "Image hash for displaying blurry previews when loading images on the frontend.", }, { languageCode: core_1.LanguageCode.de, value: "Bild-Hash um verschwommene Vorschaubilder für ladende Bilder anzeigen zu können.", }, { languageCode: core_1.LanguageCode.nl, value: "Afbeeldingshash om onscherpe voorbeeldafbeeldingen weer te geven bij het laden van afbeeldingen.", }, { languageCode: core_1.LanguageCode.ru, value: "Хеш изображения для отображения размытых изображений предварительного просмотра при загрузке изображений.", }, ], }); return config; }, compatibility: ">=3.0.0", }) ], PreviewImageHashPlugin);