rearranging utility function to conform to their respective locations

This commit is contained in:
matthieu42morin 2024-04-04 20:11:12 +02:00
parent ff649cc9e9
commit bd5276207f
2 changed files with 33 additions and 139 deletions

View File

@ -1,5 +1,4 @@
import type { create_ssr_component } from 'svelte/internal';
type DateStyle = Intl.DateTimeFormatOptions['dateStyle'];
/**
* Sorts an array of objects by their `date` property in descending order.
@ -11,27 +10,42 @@ export function dateSort<T extends { date?: string }>(a: T, b: T): number {
return Date.parse(b.date) - Date.parse(a.date);
}
/**
* Renders an mdsvex component and returns the resulting HTML string.
* @param component - The mdsvex component to render.
* @returns The HTML string that was generated by rendering the component.
* @throws An error if the `render` property of the component is not a function.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function renderMdsvexComponent(component: any): string {
if (typeof component['render'] != 'function') {
throw new Error(
"Unable to render something that isn't a mdsvex component",
);
throw new Error("Unable to render something that isn't a mdsvex component");
}
return (component as ReturnType<typeof create_ssr_component>).render().html;
}
/**
* Converts an md file path to a slug by removing the last segment of the path and the `.md` extension.
* @param path - The path of the md file.
* @returns The slug of the md file.
*/
export function mdPathToSlug(path: string) {
return path.split('/').at(-1).slice(0, -3);
}
export function parseReadContent<T extends { date?: string }>(
data: Record<string, T>,
): T[] {
/**
* Parses an object of data that has string keys and values of type `T` that have an optional `date` property.
* @param data - The object of data to parse.
* @param dateSort - A function that sorts an array of objects by their `date` property in descending order.
* @param mdPathToSlug - A function that converts an md file path to a slug.
* @returns An array of objects that have a `slug` property and the properties of the original data objects.
*/
export function parseReadContent<T extends { date?: string }>(data: Record<string, T>): T[] {
return Object.entries(data)
.map(([file, data]) => ({
slug: mdPathToSlug(file),
...data,
...data
}))
.sort(dateSort);
}
@ -44,123 +58,27 @@ export function parseReadContent<T extends { date?: string }>(
// * @param locales - The locale to use when formatting the date. Defaults to 'en'.
// * @returns The formatted date string.
// */
// // export function formatDate(date: string, dateStyle: DateStyle = 'medium', locales = 'en') {
// // const formatter = new Intl.DateTimeFormat(locales, { dateStyle });
// // return formatter.format(new Date(date));
// // }
// /**
// * Renders an mdsvex component and returns the resulting HTML string.
// * @param component - The mdsvex component to render.
// * @returns The HTML string that was generated by rendering the component.
// * @throws An error if the `render` property of the component is not a function.
// */
// export function renderMdsvexComponent(component: ReturnType<typeof create_ssr_component>): string {
// if (typeof component['render'] !== 'function') {
// throw new Error("Unable to render something that isn't a mdsvex component");
// export function formatDate(date: string, dateStyle: DateStyle = 'medium', locales = 'en') {
// const formatter = new Intl.DateTimeFormat(locales, { dateStyle });
// return formatter.format(new Date(date));
// }
// return component.render().html;
// }
// /**
// * Converts an md file path to a slug by removing the last segment of the path and the `.md` extension.
// * @param path - The path of the md file.
// * @returns The slug of the md file.
// */
// export function mdPathToSlug(path: string): string {
// return (path.split('/').at(-1) || '')?.slice(0, -3) || '';
// }
// /**
// * Parses an object of data that has string keys and values of type `T` that have an optional `date` property.
// * @param data - The object of data to parse.
// * @param dateSort - A function that sorts an array of objects by their `date` property in descending order.
// * @param mdPathToSlug - A function that converts an md file path to a slug.
// * @returns An array of objects that have a `slug` property and the properties of the original data objects.
// */
// export function parseReadContent<T extends { date?: string }>(data: Record<string, T>): T[] {
// return Object.entries(data)
// .map(
// ([file, data]) =>
// ({
// slug: mdPathToSlug(file),
// ...data
// } as { slug: string } & T & { date: string })
// )
// .sort(dateSort);
// }
import { readable } from 'svelte/store';
export const isEurope = () => {
const offset = new Date().getTimezoneOffset();
return offset <= 0 && offset >= -180;
};
export const stringToBeautifiedFragment = (str: string = '') =>
(str || '')
.toLocaleLowerCase()
.replace(/\s/g, '-')
.replace(/\?/g, '')
.replace(/,/g, '');
export const showHideOverflowY = (bool: boolean) => {
const html = document.querySelector('html');
if (bool) {
html.classList.add('overflow-y-hidden');
} else {
html.classList.remove('overflow-y-hidden');
}
};
// type DateStyle = Intl.DateTimeFormatOptions['dateStyle'];
/**
* Formats a date string into a human-readable format.
* @param date - The date string to format.
* @returns A string representing the formatted date, or an empty string if the input is invalid.
*/
export const formatDate = (date) => {
try {
const d = new Date(date);
return `${d.toLocaleString('default', {
month: 'long',
month: 'long'
})} ${d.getDate()}, ${d.getFullYear()}`;
} catch (e) {
return '';
}
};
export const scrollToElement = async (
element: HTMLElement,
selector: string,
) => {
const firstElement: HTMLElement = element.querySelector(selector);
if (!firstElement) {
return;
}
firstElement.scrollIntoView({
behavior: 'smooth',
});
};
export const removeTrailingSlash = (site: string) => {
return site.replace(/\/$/, '');
};
export const useMediaQuery = (mediaQueryString: string) => {
const matches = readable<boolean>(null, (set) => {
if (typeof globalThis['window'] === 'undefined') return;
const match = window.matchMedia(mediaQueryString);
set(match.matches);
const element = (event: MediaQueryListEvent) => set(event.matches);
match.addEventListener('change', element);
return () => {
match.removeEventListener('change', element);
};
});
return matches;
};
export const scrollIntoView = (selector: string) => {
const scrollToElement = document.querySelector(selector);
@ -171,14 +89,6 @@ export const scrollIntoView = (selector: string) => {
scrollToElement.scrollIntoView({
block: 'nearest',
inline: 'start',
behavior: mediaQuery.matches ? 'auto' : 'smooth',
behavior: mediaQuery.matches ? 'auto' : 'smooth'
});
};
export const getVariantFromStatus = (status: string) => {
if (status === 'soon' || status === 'Early Access') {
return 'pink';
} else {
return 'orange';
}
};

View File

@ -30,22 +30,6 @@ export const showHideOverflowY = (bool: boolean) => {
}
};
/**
* Formats a date string into a human-readable format.
* @param date - The date string to format.
* @returns A string representing the formatted date, or an empty string if the input is invalid.
*/
export const formatDate = (date: string) => {
try {
const d = new Date(date);
return `${d.toLocaleString('default', {
month: 'long'
})} ${d.getDate()}, ${d.getFullYear()}`;
} catch (e) {
return '';
}
};
/**
* Scrolls to the first element that matches the given selector within the provided element.
* @param element The element to search within.