@massimo-cassandro/minimo 1.12.1 → 1.14.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.
@@ -0,0 +1,228 @@
1
+ import { classnames } from './classnames.js';
2
+
3
+ /** @typedef {import('./dom-builder/dom-builder.js').DomBuilderItem} DomBuilderItem */
4
+
5
+ // TODO aggiungere compatibilità con immagini Unsplash basate su imgix
6
+
7
+ /**
8
+ * Creates a `picture` domBuilder item for an image rendered through the viewer.
9
+ *
10
+ * Every `source`/`img` `srcset` is built with width descriptors (`w`): for each entry
11
+ * of `sizes`, a candidate is generated for every integer density from 1 to `dpr`.
12
+ * The `sizes` attribute pairs each entry of `sizes` with the corresponding `breakpoints`
13
+ * entry as a `(max-width: …)` media condition; the last entry (without breakpoint) is
14
+ * the default, so `breakpoints` is expected to have one element less than `sizes`.
15
+ *
16
+ * @example
17
+ * // fixed-width thumb (250px, 16:9 ratio, 1x and 2x candidates)
18
+ * buildPictureTag({ baseSrc: 'https://img-viewer.example.com/abc123', alt: '…' });
19
+ * // sizes="250px", srcset="… 250w, … 500w"
20
+ *
21
+ * @example
22
+ * // responsive image: 250px up to 576px, 500px up to 992px, 800px beyond.
23
+ * // NB: `breakpoints` has one entry less than `sizes`: the missing one
24
+ * // corresponds to the *last* `sizes` entry, used as default beyond the last breakpoint
25
+ * buildPictureTag({
26
+ * baseSrc,
27
+ * sizes: [250, 500, 800],
28
+ * breakpoints: [576, 992],
29
+ * });
30
+ * // sizes="(max-width: 576px) 250px, (max-width: 992px) 500px, 800px"
31
+ *
32
+ * @example
33
+ * // custom ratio for numeric entries and candidates up to 3x
34
+ * buildPictureTag({
35
+ * baseSrc,
36
+ * sizes: [250, 500],
37
+ * breakpoints: [768],
38
+ * ratio: 4/3,
39
+ * dpr: 3,
40
+ * });
41
+ *
42
+ * @example
43
+ * // different aspect ratio per breakpoint: explicit [width, height] pairs
44
+ * // (can be mixed with numeric entries, which use `ratio`)
45
+ * buildPictureTag({
46
+ * baseSrc,
47
+ * sizes: [[250, 250], [800, 450]], // square on mobile, 16:9 on desktop
48
+ * breakpoints: [576],
49
+ * });
50
+ *
51
+ * @example
52
+ * // dev environment (no avif) and above-the-fold img (no loading="lazy")
53
+ * buildPictureTag({ baseSrc, devMode: true, lazy: false });
54
+ *
55
+ * @param {Object} args
56
+ * @param {string} args.baseSrc - Image base URL (viewer endpoint); its query params are preserved.
57
+ * @param {(number | [number, number])[]} [args.sizes=[250]] - Rendered image sizes, in ascending width order, one per breakpoint plus the default. Each entry is a width (px, height computed with `ratio`) or an explicit `[width, height]` pair (px), allowing a different aspect ratio per breakpoint.
58
+ * @param {number} [args.ratio=16/9] - Default aspect ratio (width / height, as in the CSS `aspect-ratio` property) used to compute the height of numeric `sizes` entries.
59
+ * @param {number} [args.dpr=2] - Maximum pixel density (integer): `srcset` candidates are generated for every density from 1 to `dpr`.
60
+ * @param {number[]} [args.breakpoints=[]] - `max-width` breakpoints (px) paired with `sizes` (one element less than `sizes`).
61
+ * @param {[string, string|number][]} [args.img_params=[['q','60'],['fd',1]]] - Query params (`[name, value]` pairs) added to every generated URL.
62
+ * @param {string[]} [args.formats=['avif','webp','pjpg']] - Image formats: the last one is used for the `img` fallback element, the others for the `source` elements.
63
+ * @param {boolean} [args.devMode=false] - When true, `avif` is excluded from `formats` (not supported by the local dev environment).
64
+ * @param {boolean} [args.lazy=true] - When true, the `img` element gets `loading="lazy"`.
65
+ * @param {string|null} [args.pictureExtraClass=null] - Extra class(es) for the `picture` element.
66
+ * @param {Object<string, *>} [args.pictureExtraAttrs={}] - Extra attributes for the `picture` element.
67
+ * @param {string|null} [args.imgExtraClass=null] - Extra class(es) for the `img` element.
68
+ * @param {Object<string, *>} [args.imgExtraAttrs={}] - Extra attributes for the `img` element.
69
+ * @param {string} [args.alt=''] - `alt` text for the `img` element.
70
+ * @returns {DomBuilderItem|null} The `picture` domBuilder item, or `null` when `baseSrc` is missing.
71
+ */
72
+ export function buildPictureTag({
73
+ baseSrc,
74
+ sizes = [250],
75
+ ratio = 16/9,
76
+ dpr = 2,
77
+ breakpoints = [],
78
+ img_params = [ ['q', '60'] ],
79
+ formats = ['avif', 'webp', 'pjpg'],
80
+ devMode = false,
81
+ lazy = true,
82
+ pictureExtraClass = null,
83
+ pictureExtraAttrs = {},
84
+ imgExtraClass = null,
85
+ imgExtraAttrs = {},
86
+ // addPopover: false, // TODO popover, se attivato
87
+ // popoverImgWidth: 600,
88
+ alt = '',
89
+
90
+ }){
91
+
92
+ if(baseSrc == null) {
93
+ return null;
94
+ }
95
+
96
+ // avif non supportato dall'ambiente di sviluppo locale
97
+ if(devMode) {
98
+ formats = formats.filter(fmt => fmt !== 'avif');
99
+ }
100
+
101
+ // densità generate: da 1 a `dpr`
102
+ const dprList = Array.from({length: dpr}, (_, i) => i + 1);
103
+
104
+ const base_url = new URL(baseSrc)
105
+ ,searchParams = new URLSearchParams(base_url.search)
106
+
107
+ // sizes normalizzato in coppie [width, height]:
108
+ // per le entry numeriche l'altezza è calcolata con `ratio`
109
+ ,sizePairs = sizes.map(size => Array.isArray(size)
110
+ ? size
111
+ : /** @type {[number, number]} */ ([size, Math.floor(size / ratio)])
112
+ )
113
+
114
+ // dimensioni dei candidati srcset (una per ogni densità in `dpr`),
115
+ // senza duplicati (per larghezza), in ordine crescente
116
+ ,srcsetSizes = sizePairs
117
+ .flatMap(([w, h]) => dprList.map(d => /** @type {[number, number]} */ ([w * d, h * d])))
118
+ .filter((pair, idx, arr) => arr.findIndex(p => p[0] === pair[0]) === idx)
119
+ .sort((a, b) => a[0] - b[0])
120
+
121
+ // attributo `sizes`: ogni size è abbinata al breakpoint corrispondente (max-width),
122
+ // l'ultima (senza breakpoint) è il valore di default
123
+ ,sizesAttr = sizePairs
124
+ .map(([w], i) => i < breakpoints.length? `(max-width: ${breakpoints[i]}px) ${w}px` : `${w}px`)
125
+ .join(', ')
126
+
127
+ // dimensioni intrinseche dell'elemento img (la size più grande)
128
+ ,[imgWidth, imgHeight] = sizePairs[sizePairs.length - 1]
129
+
130
+ // indice del candidato srcset usato come src di default dell'img:
131
+ // il candidato 1x della size mediana (mediana inferiore se le size sono pari)
132
+ ,defaultSrcIdx = srcsetSizes.findIndex(([w]) => w === sizePairs[Math.floor((sizePairs.length - 1) / 2)][0])
133
+ ;
134
+
135
+ img_params.forEach(([name, value]) => searchParams.set(name, String(value)));
136
+
137
+ // TODO popover, se attivato
138
+ // // nome univoco per l'associazione anchor (Anchor Positioning API) tra thumb e popover di ingrandimento
139
+ // const zoomAnchorName = `--zoom-${randomId()}`;
140
+
141
+ // // riferimento al popover di ingrandimento, valorizzato dalla sua callback domBuilder
142
+ // // (usato nel listener click della thumb, eseguito solo dopo che l'intera figure è stata costruita)
143
+ // let zoomPopoverEl;
144
+
145
+ /** @type {DomBuilderItem} */
146
+ const pictureTag = {
147
+ tag: 'picture',
148
+ className: pictureExtraClass ?? undefined,
149
+ attrs: {
150
+ // style: options.addPopover? `anchor-name: ${zoomAnchorName};` : null, // TODO popover, se attivato
151
+ ...pictureExtraAttrs
152
+ },
153
+ children: formats.map(fmt => {
154
+ const is_default_fmt = fmt === formats.at(-1);
155
+ /** @type {string[]} */
156
+ const srcsetArray = [];
157
+
158
+ searchParams.set('f', fmt);
159
+
160
+ srcsetSizes.forEach(([w, h]) => {
161
+ searchParams.set('bb', `${w}x${h}`);
162
+ base_url.search = searchParams.toString();
163
+ srcsetArray.push(`${base_url.toString()} ${w}w`);
164
+ });
165
+
166
+ if(is_default_fmt) {
167
+
168
+ return {
169
+ tag: 'img',
170
+ className: classnames(imgExtraClass/* , options.addPopover && styles.hasPopover */), // TODO popover, se attivato
171
+ attrs: {
172
+ alt: alt,
173
+ src: srcsetArray[defaultSrcIdx].split(' ')[0], // candidato 1x mediano, senza descrittore
174
+ srcset: srcsetArray.join(','),
175
+ sizes: sizesAttr,
176
+ width: imgWidth,
177
+ height: imgHeight,
178
+ loading: lazy? 'lazy' : null,
179
+ ...imgExtraAttrs
180
+ },
181
+ // TODO classe popover, se attivato
182
+ // callback: options.addPopover
183
+ // ? el => el.addEventListener('click', () => zoomPopoverEl.togglePopover())
184
+ // : null
185
+ };
186
+
187
+ } else {
188
+ // TODO con sizes con ratio differenti, generare una `source` per breakpoint
189
+ // con attributi `media`, `width` e `height`
190
+ return {
191
+ tag: 'source',
192
+ attrs: {
193
+ srcset: srcsetArray.join(','),
194
+ sizes: sizesAttr,
195
+ type: `image/${fmt}`,
196
+ // width:
197
+ // height:
198
+ // media:
199
+ }
200
+ };
201
+ }
202
+
203
+ })
204
+ };
205
+
206
+ /* TODO popover, se attivato
207
+ // popover di ingrandimento (Popover API + Anchor Positioning API)
208
+ ...(options.addPopover
209
+ ? [{
210
+ tag: 'div',
211
+ className: styles.zoomPopover,
212
+ attrs: {
213
+ popover: 'auto',
214
+ style: `position-anchor: ${zoomAnchorName};`
215
+ },
216
+ callback: el => zoomPopoverEl = el,
217
+ children: unsplashPictureTag(img_data, {width: options.popoverImgWidth, imgExtraClass: styles.popoverImg, addPopover: false})
218
+ }]
219
+ : []
220
+ )
221
+
222
+ return [ pictureTag, popoverTag ];
223
+ */
224
+
225
+
226
+ return pictureTag;
227
+
228
+ }