tinkr 0.0.43

Tinkr is a web framework for quickly building full-stack web applications with Leptos.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use leptos::prelude::*;

#[cfg(feature = "ssr")]
use image::{ImageFormat, imageops::FilterType};

#[cfg(feature = "ssr")]
pub mod image_handler {
    use crate::AppError;
    use axum::{
        extract::Query,
        http::{StatusCode, header},
        response::{IntoResponse, Response},
    };
    use image::{ImageFormat, imageops::FilterType};
    use serde::Deserialize;
    use std::path::Path;

    #[derive(Deserialize)]
    pub struct ImageParams {
        pub src: String,
        #[serde(default)]
        pub width: Option<u32>,
        #[serde(default)]
        pub height: Option<u32>,
        #[serde(default)]
        pub quality: Option<u8>,
    }

    /// Get the site root directory from LEPTOS_SITE_ROOT env var, defaults to "target/site"
    fn get_site_root() -> String {
        std::env::var("LEPTOS_SITE_ROOT").unwrap_or_else(|_| "target/site".to_string())
    }

    /// Server function to get the optimized image URL
    #[tracing::instrument(name = "get_optimized_image_url", skip_all, fields(src = %src, width = ?width, height = ?height, quality = ?quality))]
    pub async fn get_optimized_image_url_ssr(
        src: String,
        width: Option<u32>,
        height: Option<u32>,
        quality: Option<u8>,
    ) -> Result<String, AppError> {
        use std::path::Path;

        let site_root = get_site_root();

        // Resolve URL path to filesystem path (same logic as image_handler)
        let resolved_src = if src.contains("..") {
            return Err(AppError::new("Path traversal attempt detected".to_string()));
        } else if src.starts_with('/') {
            if src.starts_with("/uploads/") {
                src.trim_start_matches('/').to_string()
            } else if src.starts_with("/images/")
                || src.starts_with("/logo")
                || src.starts_with("/favicon")
            {
                format!("{}{}", site_root, src)
            } else {
                format!("{}{}", site_root, src)
            }
        } else {
            src.clone()
        };

        // Validate input path exists
        if !Path::new(&resolved_src).exists() {
            return Err(AppError::new(format!(
                "Source image not found: {} (resolved to {})",
                src, resolved_src
            )));
        }

        // Generate optimized path
        let quality = quality.unwrap_or(80);
        let cache_key = format!(
            "{}_{}x{}_q{}",
            src.replace("/", "_").replace(".", "_"),
            width.unwrap_or(0),
            height.unwrap_or(0),
            quality
        );

        let optimized_dir = "uploads/optimized";
        let optimized_path = format!("{}/{}.jpg", optimized_dir, cache_key);

        // Check if optimized version exists
        if !Path::new(&optimized_path).exists() {
            // Create optimized directory if it doesn't exist
            tokio::fs::create_dir_all(optimized_dir)
                .await
                .map_err(|e| {
                    AppError::new(format!("Failed to create optimized directory: {}", e))
                })?;

            // Load and process image using resolved path
            let img = image::open(&resolved_src)
                .map_err(|e| AppError::new(format!("Failed to open image: {}", e)))?;

            let processed = if let (Some(w), Some(h)) = (width, height) {
                img.resize_to_fill(w, h, FilterType::Lanczos3)
            } else if let Some(w) = width {
                img.resize(w, u32::MAX, FilterType::Lanczos3)
            } else if let Some(h) = height {
                img.resize(u32::MAX, h, FilterType::Lanczos3)
            } else {
                img
            };

            // Save as progressive JPEG
            use jpeg_encoder::{Encoder, ColorType};

            let mut encoder = Encoder::new_file(&optimized_path, quality)
                .map_err(|e| AppError::new(format!("Failed to create encoder: {}", e)))?;

            // Enable progressive encoding
            encoder.set_progressive(true);

            // Convert image color type
            let color_type = match processed.color() {
                image::ColorType::Rgb8 => ColorType::Rgb,
                image::ColorType::Rgba8 => ColorType::Rgba,
                image::ColorType::L8 => ColorType::Luma,
                _ => {
                    // Convert to RGB if not supported
                    let rgb_img = processed.to_rgb8();
                    encoder.encode(
                        rgb_img.as_raw(),
                        rgb_img.width() as u16,
                        rgb_img.height() as u16,
                        ColorType::Rgb
                    ).map_err(|e| AppError::new(format!("Failed to encode progressive JPEG: {}", e)))?;
                    return Ok(format!("/{}", optimized_path));
                }
            };

            encoder.encode(
                processed.as_bytes(),
                processed.width() as u16,
                processed.height() as u16,
                color_type
            ).map_err(|e| AppError::new(format!("Failed to encode progressive JPEG: {}", e)))?;
        }

        Ok(format!("/{}", optimized_path))
    }

    /// Resolve URL path to filesystem path
    /// - `/images/foo.jpg` → `{site_root}/images/foo.jpg` (site_root from LEPTOS_SITE_ROOT or "target/site")
    /// - `/uploads/foo.jpg` → `uploads/foo.jpg`
    /// - `uploads/foo.jpg` → `uploads/foo.jpg` (relative paths unchanged)
    fn resolve_image_path(src: &str) -> Result<String, StatusCode> {
        // Security: prevent path traversal
        if src.contains("..") {
            tracing::error!(
                src = %src,
                "Path traversal attempt detected"
            );
            return Err(StatusCode::BAD_REQUEST);
        }

        let site_root = get_site_root();

        let resolved = if src.starts_with('/') {
            // URL path - need to resolve to filesystem
            if src.starts_with("/uploads/") {
                // /uploads/foo.jpg → uploads/foo.jpg
                src.trim_start_matches('/').to_string()
            } else if src.starts_with("/images/")
                || src.starts_with("/logo")
                || src.starts_with("/favicon")
            {
                // /images/foo.jpg → {site_root}/images/foo.jpg
                // /logo.svg → {site_root}/logo.svg
                format!("{}{}", site_root, src)
            } else {
                // Other root paths → {site_root}/...
                format!("{}{}", site_root, src)
            }
        } else {
            // Relative path - use as-is
            src.to_string()
        };

        Ok(resolved)
    }

    #[tracing::instrument(name = "serve_optimized_image", skip_all, fields(src = %params.src, width = ?params.width, height = ?params.height, quality = ?params.quality))]
    pub async fn serve_optimized_image(
        Query(params): Query<ImageParams>,
    ) -> Result<Response, StatusCode> {
        // Resolve URL path to filesystem path
        let resolved_src = resolve_image_path(&params.src)?;

        let quality = params.quality.unwrap_or(80);
        let cache_key = format!(
            "{}_{}x{}_q{}",
            params.src.replace("/", "_").replace(".", "_"),
            params.width.unwrap_or(0),
            params.height.unwrap_or(0),
            quality
        );

        let optimized_dir = "uploads/optimized";
        let optimized_path = format!("{}/{}.jpg", optimized_dir, cache_key);

        // Check if optimized version exists in cache
        if !Path::new(&optimized_path).exists() {
            // Validate source path exists
            if !Path::new(&resolved_src).exists() {
                tracing::error!(
                    src = %params.src,
                    resolved_src = %resolved_src,
                    "Source image not found"
                );
                return Err(StatusCode::NOT_FOUND);
            }

            tracing::debug!(
                src = %params.src,
                optimized_path = %optimized_path,
                "Generating optimized image"
            );

            // Create optimized directory if it doesn't exist
            tokio::fs::create_dir_all(optimized_dir)
                .await
                .map_err(|e| {
                    tracing::error!(
                        error = %e,
                        dir = %optimized_dir,
                        "Failed to create optimized directory"
                    );
                    StatusCode::INTERNAL_SERVER_ERROR
                })?;

            // Load and process image using resolved path
            let img = image::open(&resolved_src).map_err(|e| {
                tracing::error!(
                    error = %e,
                    src = %params.src,
                    resolved_src = %resolved_src,
                    "Failed to open source image"
                );
                StatusCode::INTERNAL_SERVER_ERROR
            })?;

            let processed = if let (Some(w), Some(h)) = (params.width, params.height) {
                img.resize_to_fill(w, h, FilterType::Lanczos3)
            } else if let Some(w) = params.width {
                img.resize(w, u32::MAX, FilterType::Lanczos3)
            } else if let Some(h) = params.height {
                img.resize(u32::MAX, h, FilterType::Lanczos3)
            } else {
                img
            };

            // Save as progressive JPEG
            use jpeg_encoder::{Encoder, ColorType};

            let mut encoder = Encoder::new_file(&optimized_path, quality).map_err(|e| {
                tracing::error!(
                    error = %e,
                    path = %optimized_path,
                    "Failed to create encoder"
                );
                StatusCode::INTERNAL_SERVER_ERROR
            })?;

            // Enable progressive encoding
            encoder.set_progressive(true);

            // Convert image color type
            let encode_result = match processed.color() {
                image::ColorType::Rgb8 => {
                    encoder.encode(
                        processed.as_bytes(),
                        processed.width() as u16,
                        processed.height() as u16,
                        ColorType::Rgb
                    )
                }
                image::ColorType::Rgba8 => {
                    encoder.encode(
                        processed.as_bytes(),
                        processed.width() as u16,
                        processed.height() as u16,
                        ColorType::Rgba
                    )
                }
                image::ColorType::L8 => {
                    encoder.encode(
                        processed.as_bytes(),
                        processed.width() as u16,
                        processed.height() as u16,
                        ColorType::Luma
                    )
                }
                _ => {
                    // Convert to RGB if not supported
                    let rgb_img = processed.to_rgb8();
                    encoder.encode(
                        rgb_img.as_raw(),
                        rgb_img.width() as u16,
                        rgb_img.height() as u16,
                        ColorType::Rgb
                    )
                }
            };

            encode_result.map_err(|e| {
                tracing::error!(
                    error = %e,
                    path = %optimized_path,
                    "Failed to encode progressive JPEG"
                );
                StatusCode::INTERNAL_SERVER_ERROR
            })?;

            tracing::info!(
                src = %params.src,
                optimized_path = %optimized_path,
                width = ?params.width,
                height = ?params.height,
                quality = %quality,
                "Successfully generated optimized image"
            );
        } else {
            tracing::debug!(
                optimized_path = %optimized_path,
                "Serving cached optimized image"
            );
        }

        // Read and serve the optimized image
        let image_data = tokio::fs::read(&optimized_path).await.map_err(|e| {
            tracing::error!(
                error = %e,
                path = %optimized_path,
                "Failed to read optimized image"
            );
            StatusCode::INTERNAL_SERVER_ERROR
        })?;

        Ok((
            StatusCode::OK,
            [
                (header::CONTENT_TYPE, "image/jpeg"),
                (header::CACHE_CONTROL, "public, max-age=31536000, immutable"),
            ],
            image_data,
        )
            .into_response())
    }
}

#[server]
pub async fn get_optimized_image_url(
    src: String,
    width: Option<u32>,
    height: Option<u32>,
    quality: Option<u8>,
) -> Result<String, ServerFnError> {
    let result = image_handler::get_optimized_image_url_ssr(src, width, height, quality).await?;
    Ok(result)
}

#[component]
pub fn Image(
    #[prop(into)] src: String,
    #[prop(optional, into)] alt: Option<String>,
    #[prop(optional)] width: Option<u32>,
    #[prop(optional)] height: Option<u32>,
    #[prop(optional)] quality: Option<u8>,
    #[prop(optional, into)] class: Option<String>,
    #[prop(optional, into)] fallback_src: Option<String>,
    #[prop(optional, default = true)] lazy: bool,
) -> impl IntoView {
    let (current_src, set_current_src) = signal(src.clone());
    let (has_error, set_has_error) = signal(false);
    let (is_loading, set_is_loading) = signal(true);

    // Clone fallback_src for use in closures
    let fallback_src_clone = fallback_src.clone();
    let fallback_src_clone2 = fallback_src.clone();

    // Use server function during SSR to pre-generate optimized image
    // This will run on the server and return the optimized path
    let optimized_resource = Resource::new(
        move || (current_src.get(), width, height, quality),
        move |(src_val, w, h, q)| async move {
            // Only optimize if we have optimization params
            if w.is_some() || h.is_some() || q.is_some() {
                // Call server function to generate optimized image
                match get_optimized_image_url(src_val.clone(), w, h, q).await {
                    Ok(optimized_path) => optimized_path,
                    Err(_) => src_val, // Fallback to original on error
                }
            } else {
                src_val
            }
        },
    );

    let final_src = move || {
        if has_error.get() {
            // Use fallback if available
            return fallback_src_clone.clone().unwrap_or_default();
        }

        // Use optimized path from resource if available
        match optimized_resource.get() {
            Some(path) => path,
            None => current_src.get(), // Loading state - use original
        }
    };

    let img_class = move || {
        let base_class = class
            .clone()
            .unwrap_or_else(|| "bg-black w-full h-full object-cover".to_string());
        // if is_loading.get() {
        //     format!("{} opacity-0 transition-opacity duration-300", base_class)
        // } else {
        //     format!("{} opacity-100 transition-opacity duration-300", base_class)
        // }
        base_class
    };

    // let loading_attr = if lazy { "lazy" } else { "eager" };

    view! {
        <Transition fallback=move || {
            view! {
                <div
                    class="bg-neutral-900 animate-pulse"
                    style=format!(
                        "width: {}px; height: {}px;",
                        width.unwrap_or(400),
                        height.unwrap_or(300),
                    )
                ></div>
            }
        }>

            {move || {
                let src = final_src();
                let clas = img_class();
                view! {
                    <img
                        src=src
                        // alt=alt.clone().unwrap_or_else(|| "Image".to_string())
                        class=clas
                        loading="lazy"
                        fetchpriority="high"
                    />
                }
            }}

        </Transition>
    }
}

#[component]
pub fn ImageIPFSold(
    #[prop(into)] src: String,
    #[prop(optional, into)] alt: Option<String>,
    #[prop(optional, into)] class: Option<String>,
    #[prop(optional, into)] fallback_src: Option<String>,
) -> impl IntoView {
    let (current_gateway_index, set_current_gateway_index) = signal(0);
    let (use_fallback, set_use_fallback) = signal(false);

    // List of fallback gateways
    let gateways = vec![
        "https://ipfs.io/ipfs/",
        "https://gateway.pinata.cloud/ipfs/",
        "https://cloudflare-ipfs.com/ipfs/",
        "https://dweb.link/ipfs/",
    ];

    // Clone for event handlers
    let gateways_len = gateways.len();
    let has_fallback = fallback_src.is_some();
    let fallback_src_clone = fallback_src.clone();

    // Check if this is an IPFS URL
    let is_ipfs = src.starts_with("ipfs://");
    let source_url = if is_ipfs {
        src.strip_prefix("ipfs://").unwrap_or(&src).to_string()
    } else {
        src.clone()
    };

    let file_url = move || {
        if source_url.trim().is_empty() {
            return fallback_src_clone.clone().unwrap_or_default();
        }

        let use_fallback_local = use_fallback.get();

        if use_fallback_local {
            fallback_src_clone.clone().unwrap_or_default()
        } else if is_ipfs {
            let index = current_gateway_index.get();
            if index < gateways.len() {
                format!("{}{}", gateways[index], source_url)
            } else {
                String::new()
            }
        } else {
            source_url.clone()
        }
    };

    view! {
        <img
            src=move || file_url()
            alt=alt.clone().unwrap_or_else(|| "Image".to_string())
            class=class.clone().unwrap_or_else(|| "w-full h-full object-cover".to_string())
            loading="lazy"

            on:error=move |_| {
                if !use_fallback.get() {
                    if is_ipfs {
                        let next_index = current_gateway_index.get() + 1;
                        if next_index < gateways_len {
                            set_current_gateway_index.set(next_index);
                        } else if has_fallback {
                            set_use_fallback.set(true);
                        }
                    } else if has_fallback {
                        set_use_fallback.set(true);
                    }
                }
            }
        />
    }
}