move common dir
All checks were successful
Deploy App / docker (ubuntu-latest) (push) Successful in 1m9s

This commit is contained in:
Lee
2024-04-20 02:35:52 +01:00
parent 6356be7ac3
commit 18a782243e
36 changed files with 39 additions and 38 deletions

8
src/app/common/colors.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* Re-useable colors.
*/
export const Colors = {
green: "#0FFF50",
red: "#8B0000",
yellow: "#FFD700",
};

View File

@ -0,0 +1,99 @@
/* eslint-disable */
import * as fs from "node:fs";
import path from "node:path";
// @ts-ignore
import read from "read-file";
type Metadata = {
/**
* The title of the documentation page.
*/
title: string;
/**
* The description of the documentation page.
*/
description?: string;
};
/**
* The directory where the documentation files are stored.
*/
const documentationDirectory = path.join(process.cwd(), "documentation");
/**
* Gets all the documentation files recursively.
*
* @param dirPath the directory path to search for documentation files.
*/
function getDocumentationFiles(dirPath: string): string[] {
let files: string[] = [];
const items = fs.readdirSync(dirPath);
items.forEach(item => {
const itemPath = path.join(dirPath, item);
const stat = fs.statSync(itemPath);
if (stat.isDirectory()) {
// Recursively traverse directories
files.push(...getDocumentationFiles(itemPath));
} else if (stat.isFile() && path.extname(item) === ".md") {
// Collect markdown files
files.push(itemPath);
}
});
return files;
}
/**
* Gets the content of a documentation file.
*
* @param file the file to get the content of.
*/
function getDocumentationFileContent(file: string) {
return read.sync(file, "utf8");
}
/**
* Gets all the documentation pages.
*/
export function getDocumentation() {
const files = getDocumentationFiles(documentationDirectory);
return files.map(file => {
const { metadata, content } = parseFrontmatter(getDocumentationFileContent(file));
let slug = path.relative(documentationDirectory, file).replace(/\.(md)$/, "");
slug = slug.replace(/\\/g, "/"); // Normalize path separators
return {
metadata,
content,
slug,
};
});
}
/**
* Parses the frontmatter of a file.
*
* @param fileContent the content of the file.
*/
function parseFrontmatter(fileContent: string) {
let frontmatterRegex = /---\s*([\s\S]*?)\s*---/;
let match = frontmatterRegex.exec(fileContent);
let frontMatterBlock = match![1];
let content = fileContent.replace(frontmatterRegex, "").trim();
let frontMatterLines = frontMatterBlock.trim().split("\n");
let metadata: Partial<Metadata> = {};
frontMatterLines.forEach(line => {
let [key, ...valueArr] = line.split(": ");
let value = valueArr.join(": ").trim();
value = value.replace(/^['"](.*)['"]$/, "$1"); // Remove quotes
metadata[key.trim() as keyof Metadata] = value;
});
return { metadata: metadata as Metadata, content };
}

60
src/app/common/embed.ts Normal file
View File

@ -0,0 +1,60 @@
import { Metadata } from "next";
type Embed = {
/**
* The title of the embed.
*/
title: string;
/**
* The title of the embed.
*/
embedTitle?: string;
/**
* The description of the embed.
*/
description: string;
/**
* The image to show as the thumbmail.
*/
image?: string;
};
/**
* Generates metadata for a embed.
*
* @param title the title of the embed
* @param embedTitle the title of the embed
* @param description the description of the embed
* @param image the image to show as the thumbmail
* @returns the metadata for the embed
*/
export function generateEmbed({ title, embedTitle, description, image }: Embed): Metadata {
// Fall back to the title
if (!embedTitle) {
embedTitle = title;
}
const metadata: Metadata = {
title: `${title}`,
openGraph: {
title: `${title}`,
description: description,
},
twitter: {
card: "summary",
},
};
if (image) {
metadata.openGraph!.images = [
{
url: image || "",
},
];
}
return metadata;
}

View File

@ -0,0 +1,9 @@
/**
* Formats a number using the browser's locale
*
* @param number the number to format
* @returns the formatted number
*/
export function formatNumber(number: number): string {
return new Intl.NumberFormat().format(number);
}

16
src/app/common/player.ts Normal file
View File

@ -0,0 +1,16 @@
import { getPlayer } from "mcutils-library";
/**
* Checks if the player is valid.
*
* @param id the player's id
* @returns true if valid, false otherwise
*/
export async function isValidPlayer(id: string): Promise<boolean> {
try {
await getPlayer(id);
return true;
} catch {
return false;
}
}

17
src/app/common/server.ts Normal file
View File

@ -0,0 +1,17 @@
import { getServer, ServerPlatform } from "mcutils-library";
/**
* Checks if the server is valid.
*
* @param platform the server's platform
* @param query the hostname for the server
* @returns true if valid, false otherwise
*/
export async function isValidServer(platform: ServerPlatform, query: string): Promise<boolean> {
try {
await getServer(platform, query);
return true;
} catch {
return false;
}
}

View File

@ -0,0 +1,9 @@
/**
* Capitalizes the first letter of a string
*
* @param str the string to change
* @returns the updated string
*/
export function capitalizeFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}

View File

@ -0,0 +1,11 @@
import moment from "moment";
/**
* Formats the time
*
* @param time the time to format
* @returns the formatted time
*/
export function formatTime(time: Date): string {
return moment(time).format("lll");
}

189
src/app/common/use-toast.ts Normal file
View File

@ -0,0 +1,189 @@
"use client";
// Inspired by react-hot-toast library
import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/app/components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const;
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString();
}
type ActionType = typeof actionTypes;
type Action =
| {
type: ActionType["ADD_TOAST"];
toast: ToasterToast;
}
| {
type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast>;
}
| {
type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"];
}
| {
type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map(t => (t.id === action.toast.id ? { ...t, ...action.toast } : t)),
};
case "DISMISS_TOAST": {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach(toast => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map(t =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
};
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter(t => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach(listener => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
});
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: open => {
if (!open) dismiss();
},
},
});
return {
id: id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
};
}
export { useToast, toast };

12
src/app/common/utils.ts Normal file
View File

@ -0,0 +1,12 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Merge class values together
*
* @param inputs the class values
* @returns the merged class values
*/
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}