@giphy/js-util 4.4.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/index.cjs +365 -0
  2. package/dist/index.d.ts +79 -8
  3. package/dist/index.js +320 -41
  4. package/package.json +10 -9
  5. package/src/__tests__/gif-utils.test.ts +3 -10
  6. package/dist/bestfit.d.ts +0 -18
  7. package/dist/bestfit.js +0 -61
  8. package/dist/bestfit.js.map +0 -1
  9. package/dist/collections.d.ts +0 -5
  10. package/dist/collections.js +0 -42
  11. package/dist/collections.js.map +0 -1
  12. package/dist/get-client-rect-from-el.d.ts +0 -6
  13. package/dist/get-client-rect-from-el.js +0 -42
  14. package/dist/get-client-rect-from-el.js.map +0 -1
  15. package/dist/get-pingback-id.d.ts +0 -2
  16. package/dist/get-pingback-id.js +0 -45
  17. package/dist/get-pingback-id.js.map +0 -1
  18. package/dist/gif-utils.d.ts +0 -23
  19. package/dist/gif-utils.js +0 -125
  20. package/dist/gif-utils.js.map +0 -1
  21. package/dist/index.js.map +0 -1
  22. package/dist/log.d.ts +0 -15
  23. package/dist/log.js +0 -65
  24. package/dist/log.js.map +0 -1
  25. package/dist/sdk-headers.d.ts +0 -5
  26. package/dist/sdk-headers.js +0 -19
  27. package/dist/sdk-headers.js.map +0 -1
  28. package/dist/webp-check.d.ts +0 -2
  29. package/dist/webp-check.js +0 -22
  30. package/dist/webp-check.js.map +0 -1
  31. package/esm/bestfit.d.ts +0 -18
  32. package/esm/bestfit.js +0 -57
  33. package/esm/bestfit.js.map +0 -1
  34. package/esm/collections.d.ts +0 -5
  35. package/esm/collections.js +0 -34
  36. package/esm/collections.js.map +0 -1
  37. package/esm/get-client-rect-from-el.d.ts +0 -6
  38. package/esm/get-client-rect-from-el.js +0 -40
  39. package/esm/get-client-rect-from-el.js.map +0 -1
  40. package/esm/get-pingback-id.d.ts +0 -2
  41. package/esm/get-pingback-id.js +0 -43
  42. package/esm/get-pingback-id.js.map +0 -1
  43. package/esm/gif-utils.d.ts +0 -23
  44. package/esm/gif-utils.js +0 -112
  45. package/esm/gif-utils.js.map +0 -1
  46. package/esm/index.d.ts +0 -8
  47. package/esm/index.js +0 -9
  48. package/esm/index.js.map +0 -1
  49. package/esm/log.d.ts +0 -15
  50. package/esm/log.js +0 -62
  51. package/esm/log.js.map +0 -1
  52. package/esm/sdk-headers.d.ts +0 -5
  53. package/esm/sdk-headers.js +0 -13
  54. package/esm/sdk-headers.js.map +0 -1
  55. package/esm/webp-check.d.ts +0 -2
  56. package/esm/webp-check.js +0 -19
  57. package/esm/webp-check.js.map +0 -1
  58. package/src/__mocks__/webp-check.ts +0 -2
package/dist/index.cjs ADDED
@@ -0,0 +1,365 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+
37
+ // src/index.ts
38
+ var src_exports = {};
39
+ __export(src_exports, {
40
+ LogLevel: () => LogLevel,
41
+ Logger: () => Logger,
42
+ appendGiphySDKRequestHeader: () => appendGiphySDKRequestHeader,
43
+ appendGiphySDKRequestParam: () => appendGiphySDKRequestParam,
44
+ bestfit: () => bestfit_default,
45
+ checkIfWebP: () => checkIfWebP,
46
+ forEach: () => forEach,
47
+ getAltText: () => getAltText,
48
+ getBestRendition: () => getBestRendition,
49
+ getBestRenditionUrl: () => getBestRenditionUrl,
50
+ getBestVideo: () => getBestVideo,
51
+ getClientRect: () => get_client_rect_from_el_default,
52
+ getGifHeight: () => getGifHeight,
53
+ getGifWidth: () => getGifWidth,
54
+ getGiphySDKRequestHeaders: () => getGiphySDKRequestHeaders,
55
+ getPingbackId: () => get_pingback_id_default,
56
+ getSpecificRendition: () => getSpecificRendition,
57
+ mapValues: () => mapValues,
58
+ pick: () => pick,
59
+ setRenditionScaleUpMaxPixels: () => setRenditionScaleUpMaxPixels,
60
+ take: () => take,
61
+ without: () => without
62
+ });
63
+ module.exports = __toCommonJS(src_exports);
64
+
65
+ // src/log.ts
66
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
67
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
68
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
69
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
70
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
71
+ return LogLevel2;
72
+ })(LogLevel || {});
73
+ var Logger = {
74
+ ENABLED: typeof window !== "undefined" && typeof location !== "undefined" && location.search.indexOf("giphy-debug") !== -1,
75
+ LEVEL: 0,
76
+ PREFIX: "GiphyJS",
77
+ debug: (...msg) => {
78
+ if (Logger.ENABLED && Logger.LEVEL <= 0 /* DEBUG */) {
79
+ console.debug(Logger.PREFIX, ...msg);
80
+ }
81
+ },
82
+ info: (...msg) => {
83
+ if (Logger.ENABLED && Logger.LEVEL <= 1 /* INFO */) {
84
+ console.info(Logger.PREFIX, ...msg);
85
+ }
86
+ },
87
+ warn: (...msg) => {
88
+ if (Logger.ENABLED && Logger.LEVEL <= 2 /* WARN */) {
89
+ console.warn(Logger.PREFIX, ...msg);
90
+ }
91
+ },
92
+ error: (...msg) => {
93
+ if (Logger.ENABLED && Logger.LEVEL <= 3 /* ERROR */) {
94
+ console.error(Logger.PREFIX, ...msg);
95
+ }
96
+ }
97
+ };
98
+
99
+ // src/bestfit.ts
100
+ var closestArea = (width, height, renditions) => {
101
+ let currentBest = Infinity;
102
+ let result;
103
+ renditions.forEach((rendition) => {
104
+ const widthPercentage = rendition.width / width;
105
+ const heightPercentage = rendition.height / height;
106
+ const areaPercentage = widthPercentage * heightPercentage;
107
+ const testBest = Math.abs(1 - areaPercentage);
108
+ if (testBest < currentBest) {
109
+ currentBest = testBest;
110
+ result = rendition;
111
+ }
112
+ });
113
+ return result;
114
+ };
115
+ var SCALE_UP_MAX_PIXELS = 50;
116
+ var setRenditionScaleUpMaxPixels = (pixels) => {
117
+ Logger.debug(`@giphy/js-util set rendition selection scale up max pixels to ${pixels}`);
118
+ SCALE_UP_MAX_PIXELS = pixels;
119
+ };
120
+ function bestfit(renditions, width, height, scaleUpMaxPixels = SCALE_UP_MAX_PIXELS) {
121
+ let [largestRendition] = renditions;
122
+ const testRenditions = renditions.filter((rendition) => {
123
+ if (rendition.width * rendition.height > largestRendition.width * largestRendition.height) {
124
+ largestRendition = rendition;
125
+ }
126
+ return width - rendition.width <= scaleUpMaxPixels && height - rendition.height <= scaleUpMaxPixels;
127
+ });
128
+ if (testRenditions.length === 0) {
129
+ return largestRendition;
130
+ }
131
+ return closestArea(width, height, testRenditions);
132
+ }
133
+ var bestfit_default = bestfit;
134
+
135
+ // src/collections.ts
136
+ function mapValues(object, mapFn) {
137
+ if (Array.isArray(object)) {
138
+ throw `This map is just for objects, just use array.map for arrays`;
139
+ }
140
+ return Object.keys(object).reduce((result, key) => {
141
+ result[key] = mapFn(object[key], key);
142
+ return result;
143
+ }, {});
144
+ }
145
+ function forEach(object, mapFn) {
146
+ if (Array.isArray(object)) {
147
+ throw `This map is just for objects, just use array.forEach for arrays`;
148
+ }
149
+ return Object.keys(object).forEach((key) => {
150
+ mapFn(object[key], key);
151
+ });
152
+ }
153
+ function take(arr, count = 0) {
154
+ return arr.slice(0, count);
155
+ }
156
+ function without(arr, values) {
157
+ return arr.filter((val) => values.indexOf(val) === -1);
158
+ }
159
+ function pick(object, pick2) {
160
+ const res = {};
161
+ pick2.forEach((key) => {
162
+ if (object[key] !== void 0) {
163
+ res[key] = object[key];
164
+ }
165
+ });
166
+ return res;
167
+ }
168
+
169
+ // src/get-client-rect-from-el.ts
170
+ var getClientRect = (el) => {
171
+ let left = 0;
172
+ let top = 0;
173
+ const width = el.offsetWidth;
174
+ const height = el.offsetHeight;
175
+ do {
176
+ left += el.offsetLeft;
177
+ top += el.offsetTop;
178
+ el = el.offsetParent;
179
+ } while (el);
180
+ const result = {
181
+ left,
182
+ top,
183
+ width,
184
+ height,
185
+ right: left + width,
186
+ bottom: top + height,
187
+ x: left,
188
+ y: top
189
+ };
190
+ return __spreadProps(__spreadValues({}, result), { toJSON: () => JSON.stringify(result) });
191
+ };
192
+ var get_client_rect_from_el_default = getClientRect;
193
+
194
+ // src/get-pingback-id.ts
195
+ var import_uuid = require("uuid");
196
+ var pingbackId = "";
197
+ var idLength = 16;
198
+ var noUUIDRandom = () => {
199
+ let result = "";
200
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
201
+ const charactersLength = characters.length;
202
+ for (let i = 0; i < idLength; i++) {
203
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
204
+ }
205
+ return result;
206
+ };
207
+ var getPingbackId = () => {
208
+ if (!pingbackId) {
209
+ try {
210
+ pingbackId = sessionStorage.getItem("giphyPingbackId");
211
+ } catch (_) {
212
+ }
213
+ if (!pingbackId) {
214
+ const hexTime = (/* @__PURE__ */ new Date()).getTime().toString(16);
215
+ try {
216
+ pingbackId = `${hexTime}${(0, import_uuid.v4)().replace(/-/g, "")}`.substring(0, idLength);
217
+ } catch (error) {
218
+ pingbackId = noUUIDRandom();
219
+ }
220
+ try {
221
+ sessionStorage.setItem("giphyPingbackId", pingbackId);
222
+ } catch (_) {
223
+ }
224
+ }
225
+ }
226
+ return pingbackId;
227
+ };
228
+ var get_pingback_id_default = getPingbackId;
229
+
230
+ // src/webp-check.ts
231
+ var SUPPORTS_WEBP = null;
232
+ var checkIfWebP = new Promise((resolve) => {
233
+ if (typeof Image === "undefined") {
234
+ resolve(false);
235
+ }
236
+ const webp = new Image();
237
+ webp.onload = () => {
238
+ SUPPORTS_WEBP = true;
239
+ resolve(SUPPORTS_WEBP);
240
+ };
241
+ webp.onerror = () => {
242
+ SUPPORTS_WEBP = false;
243
+ resolve(SUPPORTS_WEBP);
244
+ };
245
+ webp.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
246
+ });
247
+
248
+ // src/gif-utils.ts
249
+ var getSpecificRendition = ({ images, is_sticker: isSticker }, renditionLabel, isStill = false, useVideo = false) => {
250
+ if (!images || !renditionLabel)
251
+ return "";
252
+ isStill = isStill && !useVideo;
253
+ const rendition = images[`${renditionLabel}${isStill ? "_still" : ""}`];
254
+ if (rendition) {
255
+ if (isSticker || isStill) {
256
+ return rendition.url;
257
+ }
258
+ const webP = SUPPORTS_WEBP && rendition.webp;
259
+ return useVideo ? rendition.mp4 : webP || rendition.url;
260
+ }
261
+ return "";
262
+ };
263
+ var getBestVideo = (video, width, height) => {
264
+ let assets = video == null ? void 0 : video.assets;
265
+ if (assets) {
266
+ assets = __spreadValues({}, assets);
267
+ delete assets.source;
268
+ const filteredAssets = Object.values(assets).sort((a, b) => a.width - b.width);
269
+ return bestfit_default(filteredAssets, width, height);
270
+ }
271
+ };
272
+ var getRenditions = (type, images, video) => type === "video" && video && video.previews && !Object.keys(images).length ? video.previews : images;
273
+ var getBestRendition = (images, gifWidth, gifHeight, scaleUpMaxPixels) => {
274
+ const checkRenditions = pick(images, [
275
+ "original",
276
+ "fixed_width",
277
+ "fixed_height",
278
+ "fixed_width_small",
279
+ "fixed_height_small"
280
+ ]);
281
+ const testImages = Object.entries(checkRenditions).map(([renditionName, val]) => __spreadValues({
282
+ renditionName
283
+ }, val));
284
+ return bestfit_default(testImages, gifWidth, gifHeight, scaleUpMaxPixels);
285
+ };
286
+ var getBestRenditionUrl = ({ images, video, type }, gifWidth, gifHeight, options = { isStill: false, useVideo: false }) => {
287
+ if (!gifWidth || !gifHeight || !images)
288
+ return "";
289
+ const { useVideo, isStill, scaleUpMaxPixels } = options;
290
+ const renditions = getRenditions(type, images, video);
291
+ const { renditionName } = getBestRendition(renditions, gifWidth, gifHeight, scaleUpMaxPixels);
292
+ const key = `${renditionName}${isStill && !useVideo ? "_still" : ""}`;
293
+ const rendition = renditions[key];
294
+ const match = useVideo ? rendition.mp4 : SUPPORTS_WEBP && rendition.webp ? rendition.webp : rendition.url;
295
+ return match || "";
296
+ };
297
+ var getGifHeight = ({ images }, gifWidth) => {
298
+ const { fixed_width } = images;
299
+ if (fixed_width) {
300
+ const { width, height } = fixed_width;
301
+ const aspectRatio = width / height;
302
+ return Math.round(gifWidth / aspectRatio);
303
+ }
304
+ return 0;
305
+ };
306
+ var getGifWidth = ({ images }, gifHeight) => {
307
+ const { fixed_width } = images;
308
+ if (fixed_width) {
309
+ const { width, height } = fixed_width;
310
+ const aspectRatio = width / height;
311
+ return Math.round(gifHeight * aspectRatio);
312
+ }
313
+ return 0;
314
+ };
315
+ var getAltText = ({ alt_text, user, tags = [], is_sticker = false, title = "" }) => {
316
+ if (alt_text) {
317
+ return alt_text;
318
+ }
319
+ if (title) {
320
+ return title;
321
+ }
322
+ const username = user && user.username || "";
323
+ const filteredTags = take(without(tags, ["transparent"]), username ? 4 : 5);
324
+ return `${username ? `${username} ` : ``}${filteredTags.join(" ")} ${is_sticker ? "Sticker" : "GIF"}`;
325
+ };
326
+
327
+ // src/sdk-headers.ts
328
+ var gl = (typeof window !== "undefined" ? window : global) || {};
329
+ gl._GIPHY_SDK_HEADERS_ = gl._GIPHY_SDK_HEADERS_ || (gl.Headers ? new gl.Headers({
330
+ "X-GIPHY-SDK-PLATFORM": "web"
331
+ }) : void 0);
332
+ var getGiphySDKRequestHeaders = () => gl._GIPHY_SDK_HEADERS_;
333
+ var appendGiphySDKRequestHeader = (key, value) => {
334
+ var _a;
335
+ return (_a = getGiphySDKRequestHeaders()) == null ? void 0 : _a.set(key, value);
336
+ };
337
+ var appendGiphySDKRequestParam = (key, value) => {
338
+ var _a;
339
+ return (_a = getGiphySDKRequestHeaders()) == null ? void 0 : _a.set(key, value);
340
+ };
341
+ // Annotate the CommonJS export names for ESM import in node:
342
+ 0 && (module.exports = {
343
+ LogLevel,
344
+ Logger,
345
+ appendGiphySDKRequestHeader,
346
+ appendGiphySDKRequestParam,
347
+ bestfit,
348
+ checkIfWebP,
349
+ forEach,
350
+ getAltText,
351
+ getBestRendition,
352
+ getBestRenditionUrl,
353
+ getBestVideo,
354
+ getClientRect,
355
+ getGifHeight,
356
+ getGifWidth,
357
+ getGiphySDKRequestHeaders,
358
+ getPingbackId,
359
+ getSpecificRendition,
360
+ mapValues,
361
+ pick,
362
+ setRenditionScaleUpMaxPixels,
363
+ take,
364
+ without
365
+ });
package/dist/index.d.ts CHANGED
@@ -1,8 +1,79 @@
1
- export { default as bestfit, setRenditionScaleUpMaxPixels } from './bestfit';
2
- export * from './collections';
3
- export { default as getClientRect } from './get-client-rect-from-el';
4
- export { default as getPingbackId } from './get-pingback-id';
5
- export { getAltText, getBestRendition, getBestRenditionUrl, getBestVideo, getGifHeight, getGifWidth, getSpecificRendition, } from './gif-utils';
6
- export * from './log';
7
- export * from './sdk-headers';
8
- export { checkIfWebP } from './webp-check';
1
+ import { IRendition, IGif, IImage, IImages } from '@giphy/js-types';
2
+
3
+ declare const setRenditionScaleUpMaxPixels: (pixels: number) => void;
4
+ /**
5
+ * Finds image rendition that best fits a given container preferring images
6
+ * ##### Note: all renditions are assumed to have the same aspect ratio
7
+ *
8
+ * When we have a portrait target and landscape gif, we choose a higher rendition to match
9
+ * the height of the portrait target, otherwise it's blurry (same applies for landscape to portrait)
10
+ *
11
+ * @name bestfit
12
+ * @function
13
+ * @param {Array.<Object>} renditions available image renditions each having a width and height property
14
+ * @param {Number} width
15
+ * @param {Number} height
16
+ * @param {Number} scaleUpMaxPixels the maximum pixels an asset should be scaled up
17
+ */
18
+ declare function bestfit(renditions: Array<IRendition>, width: number, height: number, scaleUpMaxPixels?: number): IRendition;
19
+
20
+ declare function mapValues(object: any, mapFn: (val: any, key: string) => any): any;
21
+ declare function forEach(object: any, mapFn: (val: any, key: any) => void): void;
22
+ declare function take<T>(arr: T[], count?: number): T[];
23
+ declare function without<T>(arr: T[], values: T[]): T[];
24
+ declare function pick<T extends object, U extends keyof T>(object: T, pick: Array<U>): Pick<T, U>;
25
+
26
+ /**
27
+ * @param el HTMLElement
28
+ * @returns calculated properties of DOMReact
29
+ */
30
+ declare const getClientRect: (el: HTMLElement) => DOMRectReadOnly;
31
+
32
+ declare const getPingbackId: () => string;
33
+
34
+ declare const getSpecificRendition: ({ images, is_sticker: isSticker }: IGif, renditionLabel: string, isStill?: boolean, useVideo?: boolean) => string;
35
+ interface IRenditionWithName extends IRendition {
36
+ renditionName: keyof IImages;
37
+ }
38
+ declare const getBestVideo: (video: IGif['video'], width: number, height: number) => IImage | undefined;
39
+ declare const getBestRendition: (images: IImages, gifWidth: number, gifHeight: number, scaleUpMaxPixels?: number) => IRenditionWithName;
40
+ type Options = {
41
+ isStill?: boolean;
42
+ useVideo?: boolean;
43
+ scaleUpMaxPixels?: number;
44
+ };
45
+ declare const getBestRenditionUrl: ({ images, video, type }: IGif, gifWidth: number, gifHeight: number, options?: Options) => keyof IImages | '';
46
+ declare const getGifHeight: ({ images }: IGif, gifWidth: number) => number;
47
+ declare const getGifWidth: ({ images }: IGif, gifHeight: number) => number;
48
+ /**
49
+ * GIF Text - Alt Text: Generates alt text for
50
+ * GIF images based on username and tags.
51
+ * @prop {Gif}
52
+ * @return {String} GIF alt text.
53
+ */
54
+ declare const getAltText: ({ alt_text, user, tags, is_sticker, title }: IGif) => string;
55
+
56
+ declare enum LogLevel {
57
+ DEBUG = 0,
58
+ INFO = 1,
59
+ WARN = 2,
60
+ ERROR = 3
61
+ }
62
+ declare const Logger: {
63
+ ENABLED: boolean;
64
+ LEVEL: number;
65
+ PREFIX: string;
66
+ debug: (...msg: any) => void;
67
+ info: (...msg: any) => void;
68
+ warn: (...msg: any) => void;
69
+ error: (...msg: any) => void;
70
+ };
71
+
72
+ type GiphySDKRequestHeader = 'X-GIPHY-SDK-NAME' | 'X-GIPHY-SDK-VERSION' | 'X-GIPHY-SDK-PLATFORM';
73
+ declare const getGiphySDKRequestHeaders: () => Headers | undefined;
74
+ declare const appendGiphySDKRequestHeader: (key: GiphySDKRequestHeader, value: string) => void | undefined;
75
+ declare const appendGiphySDKRequestParam: (key: GiphySDKRequestHeader, value: string) => void | undefined;
76
+
77
+ declare const checkIfWebP: Promise<unknown>;
78
+
79
+ export { LogLevel, Logger, appendGiphySDKRequestHeader, appendGiphySDKRequestParam, bestfit, checkIfWebP, forEach, getAltText, getBestRendition, getBestRenditionUrl, getBestVideo, getClientRect, getGifHeight, getGifWidth, getGiphySDKRequestHeaders, getPingbackId, getSpecificRendition, mapValues, pick, setRenditionScaleUpMaxPixels, take, without };