@ohmagif/js 0.0.0-stage → 0.1.1

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.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # @ohmagif/js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/ohmagif/ohmagif-js/actions/workflows/ci.yml/badge.svg)](https://github.com/ohmagif/ohmagif-js/actions/workflows/ci.yml)
4
+ [![Coverage Status](https://coveralls.io/repos/github/ohmagif/ohmagif-js/badge.svg?branch=main)](https://coveralls.io/github/ohmagif/ohmagif-js?branch=main)
5
+ [![npm: @ohmagif/js](https://img.shields.io/npm/v/@ohmagif/js?label=%40ohmagif%2Fjs&logo=npm)](https://www.npmjs.com/package/@ohmagif/js)
6
+ [![License](https://img.shields.io/github/license/ohmagif/ohmagif-js.svg)](LICENSE)
7
+
8
+ A client for the [ohmagif](https://ohmagif.com) API and a React GIF picker.
9
+ No dependencies, 5.7 kB gzipped. [Example](https://ohmagif.github.io/ohmagif-js/)
10
+
11
+ ```sh
12
+ npm install @ohmagif/js
13
+ ```
14
+
15
+ ## Client
16
+
17
+ ```ts
18
+ import { OhmagifFetch } from "@ohmagif/js";
19
+
20
+ const gf = new OhmagifFetch();
21
+
22
+ await gf.search("side eye", { limit: 12, rating: "pg" });
23
+ await gf.trending({ offset: 12 });
24
+ await gf.tag("oops");
25
+ await gf.gif("eTxuLnWv7C");
26
+ await gf.reactions();
27
+ ```
28
+
29
+ ## React
30
+
31
+ React 18 or 19.
32
+
33
+ ```tsx
34
+ import { frameSize } from "@ohmagif/js";
35
+ import { Gif, gifSize, Grid } from "@ohmagif/js/react";
36
+
37
+ <Grid
38
+ fetchGifs={(offset, signal) => gf.trending({ offset, limit: 12, signal })}
39
+ width={336}
40
+ columns={2}
41
+ noLink
42
+ onGifClick={(gif) => send({ id: gif.id, ...frameSize(gif) })}
43
+ />
44
+
45
+ <Gif gif={gif} width={322} />
46
+ ```
47
+
48
+ Keep a GIF's id and `frameSize(gif)`, not its file address.
49
+ `gifSize(frame, width)` is the room it takes before it loads. Colours follow
50
+ the page's `color-scheme`.
51
+
52
+ ## Content-Security-Policy
53
+
54
+ ```
55
+ img-src https://i.ohmagif.com;
56
+ connect-src https://ohmagif.com;
57
+ ```
58
+
59
+ ## Development
60
+
61
+ ```sh
62
+ make install
63
+ make test
64
+ make example
65
+ ```
66
+
67
+ ## Licence
68
+
69
+ GPL-3.0
@@ -0,0 +1,89 @@
1
+ import { type Gif, type Rating } from "./gif.js";
2
+ export interface OhmagifFetchOptions {
3
+ /**
4
+ * An integrator key (omg_...). Optional: without one the API allows 60
5
+ * requests a minute per address, with one 600 a minute for the key. A key
6
+ * sent from a browser can be read by anyone using the page, and its
7
+ * answers are never cached.
8
+ */
9
+ apiKey?: string;
10
+ /** The site, https://ohmagif.com by default. */
11
+ baseURL?: string;
12
+ /** Milliseconds to wait for an answer, 10000 by default; 0 waits forever. */
13
+ timeout?: number;
14
+ /** A fetch to use instead of the global one. */
15
+ fetch?: typeof globalThis.fetch;
16
+ }
17
+ export interface RequestOptions {
18
+ signal?: AbortSignal;
19
+ }
20
+ export interface PageOptions extends RequestOptions {
21
+ /** 0 to 1000, 0 by default. */
22
+ offset?: number;
23
+ /** 1 to 50, 25 by default. */
24
+ limit?: number;
25
+ /** The highest rating to include. */
26
+ rating?: Rating;
27
+ }
28
+ export interface Pagination {
29
+ /** Every match, including those past the last reachable offset. */
30
+ total_count: number;
31
+ /** GIFs in this page. */
32
+ count: number;
33
+ /** The offset this page was asked for. */
34
+ offset: number;
35
+ /** The offset of the next page, null after the last one. */
36
+ next: number | null;
37
+ }
38
+ export interface GifsResult {
39
+ data: Gif[];
40
+ pagination: Pagination;
41
+ }
42
+ export interface GifResult {
43
+ data: Gif;
44
+ }
45
+ export interface Reaction {
46
+ slug: string;
47
+ name: string;
48
+ /** Live GIFs filed under the reaction. */
49
+ gifs: number;
50
+ /** Its top GIF, null while it has none. */
51
+ top: Gif | null;
52
+ }
53
+ export interface ReactionsResult {
54
+ data: Reaction[];
55
+ }
56
+ /**
57
+ * A request the API refused or did not answer. `code` is the API's own
58
+ * (not_found, removed, search_unavailable, ...) or one of: invalid_id (no
59
+ * request was sent), network, timeout, invalid_response.
60
+ */
61
+ export declare class OhmagifError extends Error {
62
+ readonly status: number;
63
+ readonly code: string;
64
+ /** Seconds to wait before asking again, when the API said. */
65
+ readonly retryAfter: number | null;
66
+ constructor(status: number, code: string, message: string, retryAfter?: number | null);
67
+ }
68
+ export declare class OhmagifFetch {
69
+ #private;
70
+ /** Takes the options, or an API key alone. */
71
+ constructor(options?: OhmagifFetchOptions | string);
72
+ /** The page where people upload GIFs, for a link out of a picker. */
73
+ get uploadURL(): string;
74
+ /** GIFs matching the words, best match first. */
75
+ search(term: string, options?: PageOptions): Promise<GifsResult>;
76
+ /** The GIFs shared most over the last days. */
77
+ trending(options?: PageOptions): Promise<GifsResult>;
78
+ /** GIFs with a tag or reaction, by its slug (see reactions()). */
79
+ tag(slug: string, options?: PageOptions): Promise<GifsResult>;
80
+ /**
81
+ * One GIF by its id. A GIF that is gone rejects with code not_found or
82
+ * removed; an id that is not one rejects with invalid_id, without a
83
+ * request. Ask again rather than keep the answer for long: file addresses
84
+ * change when a GIF is rendered again, and the old files go an hour later.
85
+ */
86
+ gif(id: string, options?: RequestOptions): Promise<GifResult>;
87
+ /** The curated reactions, each with its top GIF. */
88
+ reactions(options?: RequestOptions): Promise<ReactionsResult>;
89
+ }
package/dist/fetch.js ADDED
@@ -0,0 +1,239 @@
1
+ // A client for the public read endpoints of the ohmagif API (/api/v1). They
2
+ // need no key and answer pages on any site.
3
+ import { asObject, DEFAULT_BASE_URL, isGifId, parseGif, RATINGS } from "./gif.js";
4
+ /**
5
+ * A request the API refused or did not answer. `code` is the API's own
6
+ * (not_found, removed, search_unavailable, ...) or one of: invalid_id (no
7
+ * request was sent), network, timeout, invalid_response.
8
+ */
9
+ export class OhmagifError extends Error {
10
+ status;
11
+ code;
12
+ /** Seconds to wait before asking again, when the API said. */
13
+ retryAfter;
14
+ constructor(status, code, message, retryAfter = null) {
15
+ super(message);
16
+ this.name = "OhmagifError";
17
+ this.status = status;
18
+ this.code = code;
19
+ this.retryAfter = retryAfter;
20
+ }
21
+ }
22
+ const MAX_LIMIT = 50;
23
+ const MAX_OFFSET = 1000;
24
+ const TAG_SLUG = /^[a-z0-9-]{1,80}$/;
25
+ function baseURL(raw) {
26
+ let url;
27
+ try {
28
+ url = new URL(raw);
29
+ }
30
+ catch {
31
+ throw new TypeError(`baseURL is not an address: ${raw}`);
32
+ }
33
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
34
+ throw new TypeError(`baseURL must be http or https: ${raw}`);
35
+ }
36
+ if (url.search || url.hash || url.username || url.password) {
37
+ throw new TypeError(`baseURL takes no query, fragment or credentials: ${raw}`);
38
+ }
39
+ return url.href.replace(/\/+$/, "");
40
+ }
41
+ function pageParams(options) {
42
+ const { offset = 0, limit = 25, rating } = options;
43
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
44
+ throw new RangeError(`limit must be 1 to ${MAX_LIMIT}`);
45
+ }
46
+ if (!Number.isInteger(offset) || offset < 0 || offset > MAX_OFFSET) {
47
+ throw new RangeError(`offset must be 0 to ${MAX_OFFSET}`);
48
+ }
49
+ const params = { limit: String(limit), offset: String(offset) };
50
+ if (rating !== undefined) {
51
+ if (!RATINGS.includes(rating))
52
+ throw new RangeError("rating must be g, pg or pg13");
53
+ params.rating = rating;
54
+ }
55
+ return params;
56
+ }
57
+ function retryAfter(res) {
58
+ const v = res.headers.get("Retry-After");
59
+ if (!v)
60
+ return null;
61
+ const n = Number(v);
62
+ if (Number.isFinite(n) && n >= 0)
63
+ return n;
64
+ const at = Date.parse(v);
65
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000));
66
+ }
67
+ function invalid(status) {
68
+ return new OhmagifError(status, "invalid_response", "Unreadable answer from ohmagif");
69
+ }
70
+ /** A count from the API: a non-negative integer, or null. */
71
+ function count(value) {
72
+ return Number.isInteger(value) && value >= 0 ? value : null;
73
+ }
74
+ /** Joins the caller's signal and the timeout into one. */
75
+ function deadline(signal, ms) {
76
+ if (!ms)
77
+ return { signal, timedOut: () => false, done: () => { } };
78
+ const ctrl = new AbortController();
79
+ let expired = false;
80
+ const timer = setTimeout(() => {
81
+ expired = true;
82
+ ctrl.abort(new DOMException("Timed out", "TimeoutError"));
83
+ }, ms);
84
+ const forward = () => ctrl.abort(signal?.reason);
85
+ if (signal?.aborted)
86
+ forward();
87
+ else
88
+ signal?.addEventListener("abort", forward, { once: true });
89
+ return {
90
+ signal: ctrl.signal,
91
+ timedOut: () => expired,
92
+ done: () => {
93
+ clearTimeout(timer);
94
+ signal?.removeEventListener("abort", forward);
95
+ },
96
+ };
97
+ }
98
+ export class OhmagifFetch {
99
+ #base;
100
+ #key;
101
+ #timeout;
102
+ #fetch;
103
+ /** Takes the options, or an API key alone. */
104
+ constructor(options = {}) {
105
+ const o = typeof options === "string" ? { apiKey: options } : options;
106
+ this.#base = baseURL(o.baseURL ?? DEFAULT_BASE_URL);
107
+ this.#key = (o.apiKey ?? "").trim();
108
+ this.#timeout = o.timeout ?? 10_000;
109
+ if (!Number.isFinite(this.#timeout) || this.#timeout < 0)
110
+ throw new RangeError("timeout must be 0 or more");
111
+ // Called unbound: a fetch kept as a method throws "Illegal invocation"
112
+ // in browsers.
113
+ const f = o.fetch ?? globalThis.fetch;
114
+ this.#fetch = (input, init) => f(input, init);
115
+ }
116
+ /** The page where people upload GIFs, for a link out of a picker. */
117
+ get uploadURL() {
118
+ return `${this.#base}/upload`;
119
+ }
120
+ /** GIFs matching the words, best match first. */
121
+ async search(term, options = {}) {
122
+ const q = term.trim();
123
+ if (!q)
124
+ throw new RangeError("term is empty");
125
+ return this.#list("/search", { q, ...pageParams(options) }, options);
126
+ }
127
+ /** The GIFs shared most over the last days. */
128
+ async trending(options = {}) {
129
+ return this.#list("/trending", pageParams(options), options);
130
+ }
131
+ /** GIFs with a tag or reaction, by its slug (see reactions()). */
132
+ async tag(slug, options = {}) {
133
+ const s = slug.trim().toLowerCase();
134
+ if (!TAG_SLUG.test(s))
135
+ throw new RangeError(`not a tag slug: ${slug}`);
136
+ return this.#list(`/tags/${s}`, pageParams(options), options);
137
+ }
138
+ /**
139
+ * One GIF by its id. A GIF that is gone rejects with code not_found or
140
+ * removed; an id that is not one rejects with invalid_id, without a
141
+ * request. Ask again rather than keep the answer for long: file addresses
142
+ * change when a GIF is rendered again, and the old files go an hour later.
143
+ */
144
+ async gif(id, options = {}) {
145
+ if (!isGifId(id))
146
+ throw new OhmagifError(0, "invalid_id", "Not a GIF id");
147
+ const { body, status } = await this.#get(`/gifs/${id}`, {}, options.signal);
148
+ const gif = parseGif(body);
149
+ if (!gif)
150
+ throw invalid(status);
151
+ return { data: gif };
152
+ }
153
+ /** The curated reactions, each with its top GIF. */
154
+ async reactions(options = {}) {
155
+ const { body, status } = await this.#get("/reactions", {}, options.signal);
156
+ const results = asObject(body)?.results;
157
+ if (!Array.isArray(results))
158
+ throw invalid(status);
159
+ const data = [];
160
+ for (const raw of results) {
161
+ const r = asObject(raw);
162
+ if (!r || typeof r.slug !== "string" || !TAG_SLUG.test(r.slug) || typeof r.name !== "string")
163
+ continue;
164
+ data.push({ slug: r.slug, name: r.name, gifs: count(r.gifs) ?? 0, top: parseGif(r.top) });
165
+ }
166
+ return { data };
167
+ }
168
+ async #list(path, params, options) {
169
+ const { body, status } = await this.#get(path, params, options.signal);
170
+ const o = asObject(body);
171
+ if (!o || !Array.isArray(o.results))
172
+ throw invalid(status);
173
+ const data = o.results.map(parseGif).filter((g) => g !== null);
174
+ const offset = Number(params.offset);
175
+ const next = count(o.next);
176
+ return {
177
+ data,
178
+ pagination: {
179
+ total_count: count(o.total) ?? offset + data.length,
180
+ count: data.length,
181
+ offset,
182
+ // A next page must move forward, or a paging loop never ends.
183
+ next: next !== null && next > offset ? next : null,
184
+ },
185
+ };
186
+ }
187
+ async #get(path, params, signal) {
188
+ const url = new URL(`${this.#base}/api/v1${path}`);
189
+ for (const [k, v] of Object.entries(params))
190
+ url.searchParams.set(k, v);
191
+ const headers = { Accept: "application/json" };
192
+ if (this.#key)
193
+ headers.Authorization = `Bearer ${this.#key}`;
194
+ const d = deadline(signal, this.#timeout);
195
+ let res;
196
+ let body;
197
+ try {
198
+ res = await this.#fetch(url.href, {
199
+ method: "GET",
200
+ headers,
201
+ // Nothing of the page travels with the request: no cookies, and not
202
+ // the address of the page (a chat room, a draft) it was made from.
203
+ credentials: "omit",
204
+ referrerPolicy: "no-referrer",
205
+ mode: "cors",
206
+ signal: d.signal ?? null,
207
+ });
208
+ try {
209
+ body = await res.json();
210
+ }
211
+ catch (err) {
212
+ // A body that is not JSON (a proxy's error page) is checked below;
213
+ // an abort while reading is not.
214
+ if (d.signal?.aborted)
215
+ throw err;
216
+ }
217
+ }
218
+ catch (err) {
219
+ if (signal?.aborted)
220
+ throw signal.reason ?? err;
221
+ if (d.timedOut()) {
222
+ throw new OhmagifError(0, "timeout", `No answer from ohmagif within ${this.#timeout / 1000} s`);
223
+ }
224
+ throw new OhmagifError(0, "network", "No answer from ohmagif");
225
+ }
226
+ finally {
227
+ d.done();
228
+ }
229
+ if (!res.ok) {
230
+ const o = asObject(body);
231
+ const code = typeof o?.code === "string" ? o.code : `http_${res.status}`;
232
+ const message = typeof o?.error === "string" ? o.error : `ohmagif answered ${res.status}`;
233
+ throw new OhmagifError(res.status, code, message, retryAfter(res));
234
+ }
235
+ if (body === undefined)
236
+ throw invalid(res.status);
237
+ return { body, status: res.status };
238
+ }
239
+ }
package/dist/gif.d.ts ADDED
@@ -0,0 +1,96 @@
1
+ /** The site the API and its pages are on. */
2
+ export declare const DEFAULT_BASE_URL = "https://ohmagif.com";
3
+ /** How suitable a GIF is: g, pg or pg13. ohmagif hosts nothing above pg13. */
4
+ export type Rating = "g" | "pg" | "pg13";
5
+ export declare const RATINGS: readonly Rating[];
6
+ /** One file of a GIF. Every file carries its creator's credit. */
7
+ export interface GifFile {
8
+ url: string;
9
+ type: string;
10
+ width: number;
11
+ height: number;
12
+ bytes: number;
13
+ }
14
+ export interface Creator {
15
+ handle: string;
16
+ name: string;
17
+ url: string;
18
+ }
19
+ /** A GIF as the ohmagif API describes it. */
20
+ export interface Gif {
21
+ /** 10 characters from [0-9A-Za-z]. */
22
+ id: string;
23
+ /** A short caption. */
24
+ title: string;
25
+ /** What happens in the GIF, for alt text. */
26
+ description: string;
27
+ /** The GIF's page on ohmagif.com. */
28
+ url: string;
29
+ embed_url: string;
30
+ embed_width: number;
31
+ embed_height: number;
32
+ /** RFC 3339, UTC. */
33
+ created: string;
34
+ /** Size of `files.full`, credit strip included. */
35
+ width: number;
36
+ height: number;
37
+ /** Seconds. */
38
+ duration: number;
39
+ rating: Rating;
40
+ tags: string[];
41
+ reaction: string | null;
42
+ creator: Creator;
43
+ files: {
44
+ /** Animated AVIF at the GIF's own size. */
45
+ full: GifFile;
46
+ /** Animated AVIF, 320 px wide. */
47
+ tiny: GifFile;
48
+ /** The first frame as JPEG, for clients without AVIF. */
49
+ poster: GifFile;
50
+ };
51
+ }
52
+ /** Whether a value is an ohmagif GIF id. */
53
+ export declare function isGifId(value: unknown): value is string;
54
+ type Obj = Record<string, unknown>;
55
+ export declare function asObject(value: unknown): Obj | null;
56
+ /**
57
+ * An absolute http or https address, or null. Anything else (javascript:,
58
+ * data:, a relative path) never reaches an href or a src.
59
+ */
60
+ export declare function httpURL(value: unknown): string | null;
61
+ /**
62
+ * Checks one GIF of an answer and copies the fields this package knows,
63
+ * nothing else. Answers null for anything that is not a complete GIF, so a
64
+ * bad entry drops out of a list rather than breaking the page.
65
+ */
66
+ export declare function parseGif(value: unknown): Gif | null;
67
+ /** The text that names a GIF to someone who cannot see it. */
68
+ export declare function gifLabel(gif: Gif): string;
69
+ /**
70
+ * Height in pixels of the credit strip under the frame of every file, full,
71
+ * tiny and poster alike. A saved or shared file keeps it; a page showing
72
+ * the GIF cuts it off and lays the credit over the frame instead, as
73
+ * ohmagif.com does.
74
+ */
75
+ export declare const CREDIT_STRIP_HEIGHT = 24;
76
+ /** A file's height without its credit strip. */
77
+ export declare function frameHeight(file: GifFile): number;
78
+ /**
79
+ * The size of the GIF's frame at full size, without the credit strip: the
80
+ * shape the components show it in. Keep this with a message to reserve
81
+ * the GIF's room before it loads.
82
+ *
83
+ * tiny.avif and full.avif round their frames apart by a fraction of a
84
+ * pixel, and a browser shows either. This is the shorter of the two shapes
85
+ * in whole pixels, so whichever it shows, the strip stays out of sight.
86
+ */
87
+ export declare function frameSize(gif: Gif): {
88
+ width: number;
89
+ height: number;
90
+ };
91
+ /** The frame of tiny.avif, the shape of a GIF in a grid. */
92
+ export declare function tinyFrameSize(gif: Gif): {
93
+ width: number;
94
+ height: number;
95
+ };
96
+ export {};
package/dist/gif.js ADDED
@@ -0,0 +1,138 @@
1
+ // The GIF object of the ohmagif API, and the checks every answer passes
2
+ // before any of it reaches a page.
3
+ /** The site the API and its pages are on. */
4
+ export const DEFAULT_BASE_URL = "https://ohmagif.com";
5
+ export const RATINGS = ["g", "pg", "pg13"];
6
+ const GIF_ID = /^[0-9A-Za-z]{10}$/;
7
+ /** Whether a value is an ohmagif GIF id. */
8
+ export function isGifId(value) {
9
+ return typeof value === "string" && GIF_ID.test(value);
10
+ }
11
+ export function asObject(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
13
+ }
14
+ function str(value) {
15
+ return typeof value === "string" ? value : null;
16
+ }
17
+ /** A non-negative finite number. */
18
+ function num(value) {
19
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
20
+ }
21
+ /** A positive integer, as every pixel size is. */
22
+ function size(value) {
23
+ return Number.isInteger(value) && value > 0 ? value : null;
24
+ }
25
+ /**
26
+ * An absolute http or https address, or null. Anything else (javascript:,
27
+ * data:, a relative path) never reaches an href or a src.
28
+ */
29
+ export function httpURL(value) {
30
+ if (typeof value !== "string")
31
+ return null;
32
+ let url;
33
+ try {
34
+ url = new URL(value);
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
40
+ }
41
+ function file(value) {
42
+ const o = asObject(value);
43
+ if (!o)
44
+ return null;
45
+ const url = httpURL(o.url);
46
+ const type = str(o.type);
47
+ const width = size(o.width);
48
+ const height = size(o.height);
49
+ if (!url || type === null || !width || !height)
50
+ return null;
51
+ return { url, type, width, height, bytes: num(o.bytes) ?? 0 };
52
+ }
53
+ function creator(value) {
54
+ const o = asObject(value);
55
+ if (!o)
56
+ return null;
57
+ const handle = str(o.handle);
58
+ const url = httpURL(o.url);
59
+ if (!handle || !url)
60
+ return null;
61
+ return { handle, name: str(o.name) ?? handle, url };
62
+ }
63
+ function isRating(value) {
64
+ return RATINGS.includes(value);
65
+ }
66
+ /**
67
+ * Checks one GIF of an answer and copies the fields this package knows,
68
+ * nothing else. Answers null for anything that is not a complete GIF, so a
69
+ * bad entry drops out of a list rather than breaking the page.
70
+ */
71
+ export function parseGif(value) {
72
+ const o = asObject(value);
73
+ if (!o || !isGifId(o.id))
74
+ return null;
75
+ const url = httpURL(o.url);
76
+ const embedURL = httpURL(o.embed_url);
77
+ const width = size(o.width);
78
+ const height = size(o.height);
79
+ const by = creator(o.creator);
80
+ const files = asObject(o.files);
81
+ const full = file(files?.full);
82
+ const tiny = file(files?.tiny);
83
+ const poster = file(files?.poster);
84
+ if (!url || !embedURL || !width || !height || !by || !full || !tiny || !poster || !isRating(o.rating)) {
85
+ return null;
86
+ }
87
+ return {
88
+ id: o.id,
89
+ title: str(o.title) ?? "",
90
+ description: str(o.description) ?? "",
91
+ url,
92
+ embed_url: embedURL,
93
+ embed_width: size(o.embed_width) ?? width,
94
+ embed_height: size(o.embed_height) ?? height,
95
+ created: str(o.created) ?? "",
96
+ width,
97
+ height,
98
+ duration: num(o.duration) ?? 0,
99
+ rating: o.rating,
100
+ tags: Array.isArray(o.tags) ? o.tags.filter((t) => typeof t === "string") : [],
101
+ reaction: str(o.reaction),
102
+ creator: by,
103
+ files: { full, tiny, poster },
104
+ };
105
+ }
106
+ /** The text that names a GIF to someone who cannot see it. */
107
+ export function gifLabel(gif) {
108
+ return gif.description || gif.title || "GIF";
109
+ }
110
+ /**
111
+ * Height in pixels of the credit strip under the frame of every file, full,
112
+ * tiny and poster alike. A saved or shared file keeps it; a page showing
113
+ * the GIF cuts it off and lays the credit over the frame instead, as
114
+ * ohmagif.com does.
115
+ */
116
+ export const CREDIT_STRIP_HEIGHT = 24;
117
+ /** A file's height without its credit strip. */
118
+ export function frameHeight(file) {
119
+ return file.height > CREDIT_STRIP_HEIGHT ? file.height - CREDIT_STRIP_HEIGHT : file.height;
120
+ }
121
+ /**
122
+ * The size of the GIF's frame at full size, without the credit strip: the
123
+ * shape the components show it in. Keep this with a message to reserve
124
+ * the GIF's room before it loads.
125
+ *
126
+ * tiny.avif and full.avif round their frames apart by a fraction of a
127
+ * pixel, and a browser shows either. This is the shorter of the two shapes
128
+ * in whole pixels, so whichever it shows, the strip stays out of sight.
129
+ */
130
+ export function frameSize(gif) {
131
+ const { full, tiny } = gif.files;
132
+ const fromTiny = Math.floor((full.width * frameHeight(tiny)) / tiny.width);
133
+ return { width: full.width, height: Math.max(1, Math.min(frameHeight(full), fromTiny)) };
134
+ }
135
+ /** The frame of tiny.avif, the shape of a GIF in a grid. */
136
+ export function tinyFrameSize(gif) {
137
+ return { width: gif.files.tiny.width, height: frameHeight(gif.files.tiny) };
138
+ }
@@ -0,0 +1,2 @@
1
+ export { OhmagifError, OhmagifFetch, type GifResult, type GifsResult, type OhmagifFetchOptions, type PageOptions, type Pagination, type Reaction, type ReactionsResult, type RequestOptions, } from "./fetch.js";
2
+ export { CREDIT_STRIP_HEIGHT, DEFAULT_BASE_URL, frameHeight, frameSize, tinyFrameSize, gifLabel, isGifId, parseGif, RATINGS, type Creator, type Gif, type GifFile, type Rating, } from "./gif.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { OhmagifError, OhmagifFetch, } from "./fetch.js";
2
+ export { CREDIT_STRIP_HEIGHT, DEFAULT_BASE_URL, frameHeight, frameSize, tinyFrameSize, gifLabel, isGifId, parseGif, RATINGS, } from "./gif.js";
@@ -0,0 +1,32 @@
1
+ import type { CSSProperties, MouseEvent } from "react";
2
+ import { type Gif } from "../gif.js";
3
+ /** Narrower than this, the credit line starts at the handle. */
4
+ export declare const FULL_CREDIT_WIDTH = 280;
5
+ /** A control at the end of a grid: Retry, or Upload to ohmagif. */
6
+ export declare const buttonStyle: CSSProperties;
7
+ export interface CardProps {
8
+ gif: Gif;
9
+ /** The width the card is shown at, in CSS pixels. */
10
+ width: number;
11
+ /** Whether the picture is there: a grid leaves it out far from the screen. */
12
+ picture?: boolean;
13
+ /** tiny.avif whatever the width, as a grid shows it. */
14
+ tinyOnly?: boolean;
15
+ /** The card links to the GIF's page. */
16
+ link: boolean;
17
+ /** Called on a click on the frame. Without link, it makes the frame a button. */
18
+ onClick?: (e: MouseEvent<HTMLElement>) => void;
19
+ /** Leave out the card and its credit line: the frame alone. */
20
+ hideAttribution?: boolean;
21
+ /** The grid's shorter credit line, "by @handle". */
22
+ shortCredit?: boolean;
23
+ lazy?: boolean;
24
+ onLoad?: () => void;
25
+ onError?: () => void;
26
+ className: string;
27
+ /** Size and place, from the caller. */
28
+ style: CSSProperties;
29
+ id?: string;
30
+ }
31
+ /** A GIF cut to its frame, in the embed's card with the credit line under it. */
32
+ export declare function Card({ gif, width, picture, tinyOnly, link, onClick, hideAttribution, shortCredit, lazy, onLoad, onError, className, style, id, }: CardProps): import("react").JSX.Element;