An open API service indexing awesome lists of open source software.

https://github.com/proxima812/astro-ts-mastery

🚀 utils and libs for Astro.js projects.
https://github.com/proxima812/astro-ts-mastery

astro-content astro-js en getcollection js ru slug slugify ts zod

Last synced: about 1 month ago
JSON representation

🚀 utils and libs for Astro.js projects.

Awesome Lists containing this project

README

        

# Astro getTaxonomy Slug auto(EN/RU)

```ts
import { getCollection } from "astro:content";
import { slug } from "github-slugger";
import slugify from "slugify";

export const customSlugify = (content) => {
if (!content) return null;

// Проверка, содержит ли строка русские символы
const isRussian = /[а-яА-ЯЁё]/.test(content);

if (isRussian) {
// Используем slugify для русских символов
return slugify(content, { lower: true, strict: true, locale: "ru" });
} else {
// Используем стандартный slug для английских символов
return slug(content);
}
};

// Функция для преобразования строки в slug
// export const slugify = (content) => {
// if (!content) return null;
// return slug(content);
// };

// Функция для получения страниц, исключая черновики и страницы с определенными ID
export const getSinglePage = async (collection) => {
const allPage = await getCollection(collection);
const removeIndex = allPage.filter((data) => data.id.match(/^(?!-)/));
const removeDrafts = removeIndex.filter((data) => !data.data.draft);
return removeDrafts;
};

// Функция для получения всех таксономий
export const getTaxonomy = async (collection, name) => {
const singlePages = await getSinglePage(collection);
const taxonomyPages = singlePages.map((page) => page.data[name]);
let taxonomies = [];
for (let i = 0; i < taxonomyPages.length; i++) {
const categoryArray = taxonomyPages[i];
for (let j = 0; j < categoryArray.length; j++) {
// customSlugify <-> slugify
taxonomies.push(customSlugify(categoryArray[j])); // Используйте customSlugify здесь
}
}
const taxonomy = [...new Set(taxonomies)];
return taxonomy;
};

```

# markdownify

Преобразует Markdown-форматированный текст в HTML. Это полезно, когда нужно отобразить текст, написанный в Markdown, в виде HTML на веб-странице.

```ts
export const markdownify = (content: string) => {
if (!content) return null;

return marked.parseInline(content);
};
```
## Пример
```js
const markdownText = "# Заголовок\nЭто *курсив* и это **жирный** текст.";
const htmlContent = markdownify(markdownText);
// Результат: "

Заголовок

Это курсив и это жирный текст.

"
```

# humanize

Преобразует строку, содержащую подчеркивания или пробелы, в читаемый вид, делая первую букву заглавной. Это полезно для отображения идентификаторов или кодовых имен в более понятной форме.

```ts
// humanize
export const humanize = (content: string) => {
if (!content) return null;

return content
.replace(/^[\s_]+|[\s_]+$/g, "")
.replace(/[_\s]+/g, " ")
.replace(/^[a-z]/, function (m) {
return m.toUpperCase();
});
};
```
## Пример
```js
const codeName = "hello_world_example";
const humanizedName = humanize(codeName);
// Результат: "Hello world example"
```

# plainify & htmlEntityDecoder

plainify & htmlEntityDecoder: Удаляют HTML-теги и декодируют HTML-сущности, превращая HTML-контент в обычный текст. Это полезно, если вам нужно извлечь чистый текст из HTML, например, для отображения в текстовом редакторе или для дальнейшей обработки.

```ts
// plainify
export const plainify = (content: string) => {
if (!content) return null;

const filterBrackets = content.replace(/<\/?[^>]+(>|$)/gm, "");
const filterSpaces = filterBrackets.replace(/[\r\n]\s*[\r\n]/gm, "");
const stripHTML = htmlEntityDecoder(filterSpaces);
return stripHTML;
};

// strip entities for plainify
const htmlEntityDecoder = (htmlWithEntities: string): string => {
let entityList: { [key: string]: string } = {
" ": " ",
"<": "<",
">": ">",
"&": "&",
""": '"',
"'": "'",
};
let htmlWithoutEntities: string = htmlWithEntities.replace(
/(&|<|>|"|')/g,
(entity: string): string => {
return entityList[entity];
}
);
return htmlWithoutEntities;
};
```
## Пример
```js
const htmlContent = "

Hello World & everyone!

";
const plainText = plainify(htmlContent);
// Результат: "Hello World & everyone!"
```

# Время чтнения ReadingTime.ts

```ts
// content reading
const readingTime = (content: string) => {
const WPS = 275 / 60;

let images = 0;
const regex = /\w/;

let words = content.split(" ").filter((word) => {
if (word.includes(" 3) {
imageFactor -= 1;
}
images -= 1;
}

const minutes = Math.ceil(((words - imageAdjust) / WPS + imageSecs) / 60);

if (minutes < 10) {
if (minutes < 2) {
return "0" + minutes + ` Min read`;
} else {
return "0" + minutes + ` Mins read`;
}
} else {
return minutes + ` Mins read`;
}
};

export default readingTime;
```