Skip to content

Commit

Permalink
nova funcionalidade, create picture and add sources
Browse files Browse the repository at this point in the history
  • Loading branch information
victorhdsp committed Aug 21, 2024
1 parent a773e9a commit 189369b
Show file tree
Hide file tree
Showing 15 changed files with 491 additions and 17 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ O projeto ainda está em desenvolvimento e as próximas atualizações serão vo
- [x] Conversão dos arquivos para o formato web.
- [x] Adicionar sinalização de que a aplicação esta rodando de forma constante.
- [x] Criação de um backup das imagens para caso de problemas.
- [ ] Modificação dos arquivos estáticos do site, substituindo `<img>` por `<picture>` com seus devidos `<sources>`.
- [x] Modificação dos arquivos estáticos do site, substituindo `<img>` por `<picture>` com seus devidos `<sources>`.
- [ ] Implementação em tempo real para JSX.
- [ ] Utilização de inteligência artificial para construir os "alts", melhorando a acessibilidade e dando menos trabalho.

Expand Down
4 changes: 2 additions & 2 deletions lib/convert/convert.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe("convertImages", () => {
beforeEach(() => {
jest.clearAllMocks(); // Limpa o estado dos mocks antes de cada teste
});
it("should convert images to png, webp, and avif", () => __awaiter(void 0, void 0, void 0, function* () {
it("should convert images to png, webp, avif and ignore other files", () => __awaiter(void 0, void 0, void 0, function* () {
const mockSharp = sharp_1.default;
const mockPng = jest.fn().mockReturnThis();
const mockWebp = jest.fn().mockReturnThis();
Expand All @@ -33,7 +33,7 @@ describe("convertImages", () => {
webp: mockWebp.mockReturnValue({ toFile: mockToFile }),
avif: mockAvif.mockReturnValue({ toFile: mockToFile })
});
const files = ["image1.jpg", "image2.png"];
const files = ["index.html", "image1.jpg", "image2.png"];
yield (0, index_1.convertImages)(files);
expect(mockPng).toHaveBeenCalled();
expect(mockWebp).toHaveBeenCalled();
Expand Down
4 changes: 2 additions & 2 deletions lib/convert/convert.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe("convertImages", () => {
jest.clearAllMocks(); // Limpa o estado dos mocks antes de cada teste
});

it("should convert images to png, webp, and avif", async () => {
it("should convert images to png, webp, avif and ignore other files", async () => {
const mockSharp = sharp as unknown as jest.Mock;

const mockPng = jest.fn().mockReturnThis();
Expand All @@ -26,7 +26,7 @@ describe("convertImages", () => {
avif: mockAvif.mockReturnValue({ toFile: mockToFile })
});

const files = ["image1.jpg", "image2.png"];
const files = ["index.html", "image1.jpg", "image2.png"];

await convertImages(files);

Expand Down
4 changes: 3 additions & 1 deletion lib/convert/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.convertImages = convertImages;
const fs_1 = require("fs");
const sharp_1 = __importDefault(require("sharp"));
const files_1 = require("../files");
function convertImage(file) {
return __awaiter(this, void 0, void 0, function* () {
const newFileName = file.replace(".", "_temp.");
Expand All @@ -31,7 +32,8 @@ function convertImages(files) {
return __awaiter(this, void 0, void 0, function* () {
for (let i = 0; i < files.length; i++) {
const file = files[i];
yield convertImage(file);
if ((0, files_1.verifyTypeFile)(files_1.typeImages, file))
yield convertImage(file);
console.log("Convertendo imagem: ", file);
}
console.log("Todas as imagens foram convertidas.");
Expand Down
4 changes: 3 additions & 1 deletion lib/convert/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { rmSync, renameSync } from "fs";
import sharp from "sharp";
import { typeImages, verifyTypeFile } from "../files";

async function convertImage(file: string) {
const newFileName = file.replace(".", "_temp.");
Expand All @@ -15,7 +16,8 @@ async function convertImage(file: string) {
export async function convertImages (files: string[]) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
await convertImage(file);
if (verifyTypeFile(typeImages, file))
await convertImage(file);
console.log("Convertendo imagem: ", file);
}
console.log("Todas as imagens foram convertidas.");
Expand Down
14 changes: 13 additions & 1 deletion lib/files/files.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_process_1 = require("node:process");
const node_path_1 = __importDefault(require("node:path"));
const node_process_1 = require("node:process");
const node_fs_1 = require("node:fs");
const index_1 = require("./index");
describe("getForFiles", () => {
Expand All @@ -20,6 +20,7 @@ describe("getForFiles", () => {
console.log = jest.fn();
const result = (0, index_1.getForFiles)(tmpDir);
expect(result).toEqual([
node_path_1.default.join(tmpDir, "/404.html"),
node_path_1.default.join(tmpDir, "/img/favicon.png"),
node_path_1.default.join(tmpDir, "/img/home/aboutus.png"),
node_path_1.default.join(tmpDir, "/img/home/contact.png"),
Expand All @@ -34,7 +35,18 @@ describe("getForFiles", () => {
node_path_1.default.join(tmpDir, "/img/home/portfolio/michelle-2.png"),
node_path_1.default.join(tmpDir, "/img/home/portfolio/pamella-1.png"),
node_path_1.default.join(tmpDir, "/img/home/portfolio/pamella-2.png"),
node_path_1.default.join(tmpDir, "/index.html"),
]);
expect(console.log).toHaveBeenCalledWith("Todas as imagens foram selecionadas.");
});
});
describe("makeBackup", () => {
const testDir = node_path_1.default.join((0, node_process_1.cwd)(), "/tests/files/", "/out");
it("Deve retornar o backup no history", () => {
const testHistory = node_path_1.default.join((0, node_process_1.cwd)(), "/history");
(0, index_1.makeBackup)(testDir);
const history = (0, node_fs_1.readdirSync)(testHistory);
expect(history).toContain("out");
(0, node_fs_1.rmSync)(node_path_1.default.join(testHistory, "/out"), { recursive: true });
});
});
21 changes: 18 additions & 3 deletions lib/files/files.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { cwd } from "node:process";
import path from "node:path";
import { cpSync, rmSync } from "node:fs";
import { getForFiles } from "./index";
import { cwd } from "node:process";
import { cpSync, readdirSync, rmSync } from "node:fs";
import { getForFiles, makeBackup } from "./index";

describe("getForFiles", () => {
const testDir = path.join(cwd(), "/tests/files/", "/out");
Expand All @@ -20,6 +20,7 @@ describe("getForFiles", () => {
const result = getForFiles(tmpDir);

expect(result).toEqual([
path.join(tmpDir, "/404.html"),
path.join(tmpDir, "/img/favicon.png"),
path.join(tmpDir, "/img/home/aboutus.png"),
path.join(tmpDir, "/img/home/contact.png"),
Expand All @@ -34,8 +35,22 @@ describe("getForFiles", () => {
path.join(tmpDir, "/img/home/portfolio/michelle-2.png"),
path.join(tmpDir, "/img/home/portfolio/pamella-1.png"),
path.join(tmpDir, "/img/home/portfolio/pamella-2.png"),
path.join(tmpDir, "/index.html"),
]);

expect(console.log).toHaveBeenCalledWith("Todas as imagens foram selecionadas.");
});
});

describe("makeBackup", () => {
const testDir = path.join(cwd(), "/tests/files/", "/out");

it("Deve retornar o backup no history", () => {
const testHistory = path.join(cwd(), "/history");
makeBackup(testDir);

const history = readdirSync(testHistory);
expect(history).toContain("out");
rmSync(path.join(testHistory, "/out"), { recursive: true });
})
});
17 changes: 15 additions & 2 deletions lib/files/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,29 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeMarking = exports.typeImages = void 0;
exports.verifyTypeFile = verifyTypeFile;
exports.filter = filter;
exports.getForFiles = getForFiles;
exports.makeBackup = makeBackup;
const node_fs_1 = require("node:fs");
const node_path_1 = __importDefault(require("node:path"));
const node_process_1 = require("node:process");
exports.typeImages = ["png", "jpg"];
exports.typeMarking = ["html"];
function verifyTypeFile(types, file) {
for (let i = 0; i < types.length; i++)
if (file.includes(types[i]))
return true;
return false;
}
function filter(files) {
return files.filter((file) => {
return file.includes("png") ||
file.includes("jpg");
if (verifyTypeFile(exports.typeImages, file))
return true;
if (verifyTypeFile(exports.typeMarking, file))
return true;
return false;
});
}
function getForFiles(dir) {
Expand Down
17 changes: 15 additions & 2 deletions lib/files/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,23 @@ import { readdirSync, cpSync, rmSync, existsSync } from "node:fs";
import path from "node:path";
import { cwd } from "node:process";

export const typeImages = ["png", "jpg"];
export const typeMarking = ["html"];

export function verifyTypeFile(types: string[], file:string) {
for (let i = 0; i < types.length; i++)
if (file.includes(types[i])) return true;
return false;
}

export function filter(files:string[]) {
return files.filter((file) => {
return file.includes("png") ||
file.includes("jpg");
if(verifyTypeFile(typeImages, file))
return true;
if(verifyTypeFile(typeMarking, file))
return true;

return false;
})
}

Expand Down
53 changes: 53 additions & 0 deletions lib/sources/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTagsImage = getTagsImage;
const fs_1 = require("fs");
const cheerio = __importStar(require("cheerio"));
function getTagsImage(file) {
const $ = cheerio.load((0, fs_1.readFileSync)(file, "utf8"));
$("img").each((index, img) => {
const filenameUntyped = img.attribs.src.split(".")[0];
$(img).replaceWith(`
<picture>
<source
srcset="${filenameUntyped + '.avif'}"
type="image/avif"
/>
<source
srcset="${filenameUntyped + '.webp'}"
type="image/webp"
/>
<img
src="${filenameUntyped + '.png'}"
width="${img.attribs.width}"
height="${img.attribs.height}"
alt="${img.attribs.alt}"
/>
</picture>
`);
});
(0, fs_1.writeFileSync)(file, $.html());
}
31 changes: 31 additions & 0 deletions lib/sources/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { readFileSync, writeFileSync } from "fs";
import { typeMarking, verifyTypeFile } from "../files";
import * as cheerio from "cheerio";

export function getTagsImage(file:string) {
const $ = cheerio.load(readFileSync(file, "utf8"));
$("img").each((index, img) => {
const filenameUntyped = img.attribs.src.split(".")[0];

$(img).replaceWith(`
<picture>
<source
srcset="${filenameUntyped+'.avif'}"
type="image/avif"
/>
<source
srcset="${filenameUntyped+'.webp'}"
type="image/webp"
/>
<img
src="${filenameUntyped+'.png'}"
width="${img.attribs.width}"
height="${img.attribs.height}"
alt="${img.attribs.alt}"
/>
</picture>
`)
})

writeFileSync(file, $.html());
}
52 changes: 52 additions & 0 deletions lib/sources/sources.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_fs_1 = require("node:fs");
const node_path_1 = __importDefault(require("node:path"));
const node_process_1 = require("node:process");
const cheerio = __importStar(require("cheerio"));
const _1 = require(".");
describe("Sources", () => {
const testDir = node_path_1.default.join((0, node_process_1.cwd)(), "/tests/files/", "/out");
const tmpDir = node_path_1.default.join((0, node_process_1.cwd)(), "/tests/files/", "/tmp/sources");
beforeEach(() => {
(0, node_fs_1.cpSync)(testDir, tmpDir, { recursive: true });
});
afterEach(() => {
(0, node_fs_1.rmSync)(tmpDir, { recursive: true });
});
it("Deve ter buscado os arquivos e adicionado os pictures", () => {
const file = node_path_1.default.join(tmpDir, "index.html");
const $old = cheerio.loadBuffer((0, node_fs_1.readFileSync)(file));
(0, _1.getTagsImage)(file);
const $new = cheerio.loadBuffer((0, node_fs_1.readFileSync)(file));
expect($old("img").get().length).toBe($new("picture").get().length);
expect($old("img").get().length).toBe($new("img").get().length);
expect($old("img").get().length).toBe($new("source").get().length / 2);
});
});
28 changes: 28 additions & 0 deletions lib/sources/sources.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { cpSync, readFileSync, rmSync } from "node:fs";
import path from "node:path";
import { cwd } from "node:process";
import * as cheerio from "cheerio";
import { getTagsImage } from ".";

describe("Sources", () => {
const testDir = path.join(cwd(), "/tests/files/", "/out");
const tmpDir = path.join(cwd(), "/tests/files/", "/tmp/sources");

beforeEach(() => {
cpSync(testDir, tmpDir, { recursive: true });
});

afterEach(() => {
rmSync(tmpDir, { recursive: true });
})

it("Deve ter buscado os arquivos e adicionado os pictures", () => {
const file = path.join(tmpDir, "index.html");
const $old = cheerio.loadBuffer(readFileSync(file));
getTagsImage(file);
const $new = cheerio.loadBuffer(readFileSync(file));
expect($old("img").get().length).toBe($new("picture").get().length)
expect($old("img").get().length).toBe($new("img").get().length)
expect($old("img").get().length).toBe($new("source").get().length / 2)
});
})
Loading

0 comments on commit 189369b

Please sign in to comment.