Skip to content

Commit

Permalink
other seo improvement and analytics: images
Browse files Browse the repository at this point in the history
  • Loading branch information
AngeloChecked committed Oct 5, 2024
1 parent 371efa4 commit 5370d58
Show file tree
Hide file tree
Showing 155 changed files with 185 additions and 68 deletions.
7 changes: 3 additions & 4 deletions blog/components/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const Base = (props: BaseProps) =>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta property="og:type" content="website">
${
!props.page?.relativeWebsitePath ? "" : `
Expand All @@ -41,7 +42,6 @@ export const Base = (props: BaseProps) =>
`
}
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="icon" type="image/x-icon" href="favicon.ico">
Expand Down Expand Up @@ -80,9 +80,8 @@ function googleTagManagerScript() {
<script async src="https://www.googletagmanager.com/gtag/js?id=G-LE27PDG685"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-LE27PDG685');
dataLayer.push(['js', new Date()]);
dataLayer.push(['config', 'G-LE27PDG685']);
</script>
`;
}
5 changes: 3 additions & 2 deletions blog/createPageHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { Menu } from "./components/Menu.ts";
import { RoutedPage } from "./routes.ts";
import { styleCssFile } from "./style/mainCss.ts";
import { websocketScript } from "./server.ts";
import { allMenus } from "./main.ts";
import { allMenus, domain } from "./main.ts";
import { fromStringToDomToString } from "./utils/utils.ts";

export function createPageHtml(
page?: RoutedPage,
Expand All @@ -28,6 +29,6 @@ export function createPageHtml(
page: page!,
site: { domain: domain },
});
const html = fromStringToDomToString(body);
const html = fromStringToDomToString(page!, body);
return html;
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const philosophicalRamblingsAboutEcologyProgrammingLanguagesAndOOPNotJava
],
date: "2024-04-13T13:00:00.000Z",
thumbnail: {
src: "/img/philosophical_ramblings_about_ecology_programming_languages_and_OOP_not_java/toomanyspiderman.small.webp",
src: "/img/philosophical_ramblings_about_ecology_programming_languages_and_OOP_not_java/toomanyspiderman.480x240.small.webp",
},
},
};
125 changes: 125 additions & 0 deletions blog/preprocess/apply_picture_resolutions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { HTMLDocument } from "../deps/dom.ts";
import { RoutedPage } from "../routes.ts";

type Options = {
mediaConfig: {
tiny?: string;
small?: string;
medium?: string;
large?: string;
};
};

const defaults: Options = {
mediaConfig: {
tiny: undefined,
small: "(min-width: 300px)",
medium: "(min-width: 480px)",
large: "(min-width: 600px)",
},
};

export default function pictureRelosution(
page: RoutedPage,
document: HTMLDocument,
imageInFolders: string[],
maxWidth: number
) {
const options = defaults;

if (!page?.data) return;

if (!page?.data?.thumbnail) {
page.data.thumbnail = { src: "" };
}

const images = document?.querySelectorAll("img");
if (!images) return;

for (const img of images) {
const src = img.getAttribute("src");
const alt = img.getAttribute("alt");

src && img.setAttribute("src", src);
alt && img.setAttribute("alt", alt);

if (!src) return;
const sizes = ["large", "medium", "small", "tiny"];
const imagesFound: [string, string][] = [];
const pathFileNameWithoutExtension = src.replace(/(\..*)$/, ``);

for (const size of sizes) {
const regex = new RegExp(
`${
pathFileNameWithoutExtension.split("/").slice(-1)
}\.[0-9]{1,4}x[0-9]{1,4}\.${size}.webp`,
);
const sizeImageFound = imageInFolders.find((img) => regex.test(img));
sizeImageFound && imagesFound.push([size, "/img" + sizeImageFound]);
}

const mediaConfig: Record<string, string | undefined> = options.mediaConfig;

if (imagesFound.length > 0 && document) {
const picture = document.createElement("picture");
alt && picture.setAttribute("alt", alt);

for (const [size, path] of imagesFound) {
const source = document.createElement("source");
source.setAttribute("srcset", path);

const regex = new RegExp("\.([0-9]{1,4}x[0-9]{1,4})\.");
const resolutionFromName = regex.exec(path)?.[1];
const [w, h] = resolutionFromName?.split("x") ?? [];
if (w && h && !img.getAttribute("width")) {
let ww = parseInt(w)
let hh = parseInt(h)
if (ww >= maxWidth){
hh = Math.trunc((hh*maxWidth) / ww)
ww = maxWidth
}
source.setAttribute("width", `${ww}px`);
source.setAttribute("height", `${hh}px`);
source.setAttribute(
"style",
`width:100%; height: auto; max-width:${ww}px; max-height: ${hh}px;`,
);
}

const media = mediaConfig[size];
media && source.setAttribute("media", media);

picture.appendChild(source);
}
img.replaceWith(picture);
const regex = new RegExp(
`${
pathFileNameWithoutExtension.split("/").slice(-1)
}\.[0-9]{1,4}x[0-9]{1,4}\.webp$`,
);
const sizeImageFound = imageInFolders.find((img) => regex.test(img));
if (sizeImageFound) {
const regex = new RegExp("\.([0-9]{1,4}x[0-9]{1,4})\.");
const resolutionFromName = regex.exec(sizeImageFound)?.[1];
const [w, h] = resolutionFromName?.split("x") ?? [];
if (w && h && !img.getAttribute("width")) {
let ww = parseInt(w)
let hh = parseInt(h)
if (ww >= maxWidth){
hh = Math.trunc((hh*maxWidth) / ww)
ww = maxWidth
}
img.setAttribute("width", `${ww}px`);
img.setAttribute("height", `${hh}px`);
img.setAttribute(
"style",
`width:100%; height: auto; max-width:${ww}px; max-height: ${hh}px;`,
);
}
img.setAttribute("src", "/img" + sizeImageFound);
}
picture.appendChild(img);
}
}
return document;
}
29 changes: 1 addition & 28 deletions blog/preprocess/md_picture_resolution_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,34 +52,7 @@ export default function pictureRelosution(
imageInFolders.some((img) => sizedFilePath.endsWith(img)) &&
imagesFound.push([size, sizedFilePath]);
}

const mediaConfig: Record<string, string | undefined> = options.mediaConfig;

if (imagesFound.length > 0 && document) {
const picture = document.createElement("picture");
alt && picture.setAttribute("alt", alt);

for (const [size, path] of imagesFound) {
const source = document.createElement("source");
source.setAttribute("data-srcset", path);

const media = mediaConfig[size];
media && source.setAttribute("media", media);

picture.appendChild(source);
}
img.replaceWith(picture);
imageInFolders.some((img) => src.endsWith(img)) &&
picture.appendChild(img);
}
}
const script = document.createElement("script");
script.innerText = `
window.onload = () => {
document.querySelectorAll('source').forEach(el => el.setAttribute('srcset', el.getAttribute('data-srcset')));
document.querySelectorAll('img').forEach(el => el.setAttribute('src', el.getAttribute('data-src')));
}`;
const body = document.querySelector("body");
body && body.appendChild(script);

return document;
}
3 changes: 2 additions & 1 deletion blog/resize-img/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
target
cargo.lock
.webp
*.(large|medium|small|tiny).webp

3 changes: 3 additions & 0 deletions blog/resize-img/delete-tests.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
rm -f test2.webp
ls | grep -E "(large|medium|small|tiny)" | xargs rm
ls | grep -E "[0-9]{1,4}x[0-9]{1,4}.webp" | xargs rm
4 changes: 3 additions & 1 deletion blog/resize-img/src/img_to_webp.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use image::{DynamicImage, EncodableLayout, ImageReader};
use image::{DynamicImage, EncodableLayout, GenericImageView, ImageReader};
use std::fs::File;
use std::io::Write;
use std::path::Path;
Expand All @@ -7,6 +7,8 @@ use webp::{Encoder, WebPMemory};
pub fn image_to_webp(file_path_png: &Path, file_path_webp: &Path) -> Option<()> {
let image = ImageReader::open(file_path_png).unwrap();
let image: DynamicImage = image.with_guessed_format().unwrap().decode().unwrap();
let (w, h) = image.dimensions();
dbg!(w, h);
let encoder: Encoder = Encoder::from_image(&image).unwrap();
let encoded_webp: WebPMemory = encoder.encode(65f32);
let mut webp_image = File::create(&file_path_webp).unwrap();
Expand Down
63 changes: 37 additions & 26 deletions blog/resize-img/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ fn main() {
.unwrap()
.map(|res| res.unwrap().path())
.filter(|path| {
let re = Regex::new(r"\.(tiny|small|medium|large)\.[^.]{0,4}$").unwrap();
let re = Regex::new(
r"\.[0-9]{1,4}x[0-9]{1,4}\.(tiny|small|medium|large)\.[^.]{0,4}$",
)
.unwrap();
!re.is_match(path.to_str().unwrap())
})
.collect()
Expand Down Expand Up @@ -47,18 +50,18 @@ fn main() {
let (width, height) = img.dimensions();
println!("image size: {width}, {height}");

resize_to_each_size(&img, file.to_str().unwrap());
resize_to_each_size(&img, &file);
}
}
}

fn resize_to_each_size(img: &image::DynamicImage, path: &str) {
let (width, _) = img.dimensions();
fn resize_to_each_size(img: &image::DynamicImage, path: &Path) {
let (width, height) = img.dimensions();

let tiny_width = 300u32;
let postfix = "tiny";
if width > tiny_width {
resize_image_if_not_exists(path, postfix, tiny_width, img);
resize_image_if_not_exists(&path, postfix, tiny_width, img);
}

let small_width = 480u32;
Expand All @@ -69,42 +72,50 @@ fn resize_to_each_size(img: &image::DynamicImage, path: &str) {

let medium_width = 600u32;
let postfix = "medium";
if width > medium_width {
if width >= medium_width {
resize_image_if_not_exists(path, postfix, medium_width, img);

let large_path = path_with_size_postfix(path, "large");
if !Path::new(large_path.as_str()).exists() {
let large_path = path_with_size_postfix(path, format!("{width}x{height}.large").as_str());
if !large_path.exists() {
img.save(large_path).unwrap();
}
}

let as_is_with_sizes = path_with_size_postfix(path, format!("{width}x{height}").as_str());
if !as_is_with_sizes.exists() {
img.save(as_is_with_sizes).unwrap();
}
}

fn resize_image_if_not_exists(
path: &str,
path: &Path,
postfix: &str,
small_width: u32,
new_width: u32,
img: &image::DynamicImage,
) {
let small_path = path_with_size_postfix(path, postfix);
if !Path::new(small_path.as_str()).exists() {
resize_image(small_width, img, path, postfix);
}
}

fn resize_image(small: u32, img: &image::DynamicImage, path: &str, postfix: &str) {
let (width, height) = img.dimensions();
let (new_w, new_h) = calculate_resize_dimension_by_width(width, height, small);
println!("{postfix} size: {new_w}, {new_h}");
let (new_w, new_h) = calculate_resize_dimension_by_width(width, height, new_width);
let into_path = path_with_size_postfix(&path, format!("{new_w}x{new_h}.{postfix}").as_str());
if into_path.exists() {
return;
}
let into_path_dbg = into_path.to_str().unwrap();
println!("{into_path_dbg} size: {new_w}, {new_h}");
let resized_img = img.resize(new_w, new_h, image::imageops::FilterType::Lanczos3);
let new_path = path_with_size_postfix(path, postfix);
println!("{new_path}");
resized_img.save(new_path).unwrap();
println!("{}", into_path_dbg);
resized_img.save(into_path).unwrap();
}

fn path_with_size_postfix(path: &str, postfix: &str) -> String {
let re = Regex::new(r"\.([^.]*)$").unwrap();
let new_path = re.replace(path, format!(".{}.$1", postfix));
new_path.to_string()
fn path_with_size_postfix(path: &Path, postfix: &str) -> PathBuf {
let file_name = path.file_stem().unwrap().to_str().unwrap();
let file_extension = path.extension().unwrap().to_str().unwrap();
let new_path = path.with_file_name(format!(
"{file_name}.{postfix}.{file_extension}",
file_name = file_name,
postfix = postfix,
file_extension = file_extension
));
new_path
}

fn calculate_resize_dimension_by_width(width: u32, height: u32, new_width: u32) -> (u32, u32) {
Expand Down
Binary file removed blog/resize-img/test.large.webp
Binary file not shown.
Binary file removed blog/resize-img/test.medium.webp
Binary file not shown.
Binary file removed blog/resize-img/test.small.webp
Binary file not shown.
Binary file removed blog/resize-img/test.tiny.webp
Binary file not shown.
Binary file removed blog/resize-img/test2.webp
Binary file not shown.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
4 changes: 3 additions & 1 deletion blog/style/mainCss.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { cssClass, cssElement, cssFile } from "./css.ts";

export const mainWidth = 800;

const htmlStyle = cssElement({
elementName: "body, html",
properties: {
Expand Down Expand Up @@ -51,7 +53,7 @@ export const mainClass = cssClass({
className: "main",
properties: {
margin: "auto auto auto auto",
maxWidth: "800px",
maxWidth: `${mainWidth}px`,
fontSize: "18px",
width: "90%",
fontFamily: `"Open Sans","Helvetica Neue",sans-serif`,
Expand Down
8 changes: 4 additions & 4 deletions blog/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { DOMParser } from "../deps/dom.ts";
import { jsBeautify } from "../deps/js-beautify.ts";
import pictureRelosution from "../preprocess/md_picture_resolution_plugin.ts";
import pictureRelosution from "../preprocess/apply_picture_resolutions.ts";
import { RoutedPage } from "../routes.ts";
import { mainWidth } from "../style/mainCss.ts";

export type FileOrDir = [string, FileOrDir[]] | string;

Expand Down Expand Up @@ -52,9 +53,8 @@ export function fromStringToDomToString(page: RoutedPage, body: string) {
const parser = new DOMParser();
const document = parser.parseFromString(body, "text/html");

//const documentUpdated = pictureRelosution(page, document!, imagesInFolder) ?? document

const html = `<!DOCTYPE html>\n${document.documentElement?.outerHTML || ""}`;
const documentUpdated = pictureRelosution(page, document!, imagesInFolder, mainWidth) ?? document
const html = `<!DOCTYPE html>\n${documentUpdated.documentElement?.outerHTML || ""}`;
return jsBeautify.html(html);
}

Expand Down

0 comments on commit 5370d58

Please sign in to comment.