fix(ci): resolve all lint errors for GitHub Actions

- Remove unused SupportedLocale import in results.tsx
- Remove unused webroot variable in public/i18n.js
- Configure knip.json to ignore i18n public API exports
- Add language-selector and language-option to ESLint ignore list
- Auto-fix Prettier formatting across all files
- Fix better-tailwindcss line wrapping issues
This commit is contained in:
Your Name 2026-01-20 12:16:13 +08:00
parent 8089fa0853
commit 569c572e62
16 changed files with 621 additions and 508 deletions

View file

@ -24,9 +24,7 @@ export const BaseHtml = ({
<link rel="icon" type="image/png" sizes="32x32" href={`${webroot}/favicon-32x32.png`} />
<link rel="icon" type="image/png" sizes="16x16" href={`${webroot}/favicon-16x16.png`} />
<link rel="manifest" href={`${webroot}/site.webmanifest`} />
<script>
{`window.__TRANSLATIONS__ = ${JSON.stringify(getTranslations(locale))};`}
</script>
<script>{`window.__TRANSLATIONS__ = ${JSON.stringify(getTranslations(locale))};`}</script>
<script src={`${webroot}/i18n.js`} defer />
</head>
<body class={`flex min-h-screen w-full flex-col bg-neutral-900 text-neutral-200`}>

View file

@ -1,4 +1,9 @@
import { type SupportedLocale, type Translator, createTranslator, defaultLocale } from "../i18n/index";
import {
type SupportedLocale,
type Translator,
createTranslator,
defaultLocale,
} from "../i18n/index";
import { LanguageSelector } from "./languageSelector";
export const Header = ({

View file

@ -36,7 +36,14 @@ export const LanguageSelector = ({
d="M10.5 21l5.25-11.25L21 21m-9-3h7.5M3 5.621a48.474 48.474 0 016-.371m0 0c1.12 0 2.233.038 3.334.114M9 5.25V3m3.334 2.364C11.176 10.658 7.69 15.08 3 17.502m9.334-12.138c.896.061 1.785.147 2.666.257m-4.589 8.495a18.023 18.023 0 01-3.827-5.802"
/>
</svg>
<span class="hidden sm:inline">{t("nav", "language")}</span>
<span
class={`
hidden
sm:inline
`}
>
{t("nav", "language")}
</span>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
@ -51,8 +58,8 @@ export const LanguageSelector = ({
<ul
id="language-dropdown"
class={`
absolute right-0 top-full z-50 mt-2 hidden min-w-[160px] max-h-[320px] flex-col overflow-y-auto rounded
border border-neutral-700 bg-neutral-800 shadow-lg
absolute top-full right-0 z-50 mt-2 hidden max-h-[320px] min-w-[160px] flex-col
overflow-y-auto rounded border border-neutral-700 bg-neutral-800 shadow-lg
`}
role="menu"
>
@ -65,7 +72,11 @@ export const LanguageSelector = ({
language-option flex w-full items-center gap-2 px-4 py-2 text-left text-sm
transition-colors
hover:bg-neutral-700
${locale.code === currentLocale ? "bg-neutral-700 text-accent-500" : "text-neutral-200"}
${
locale.code === currentLocale
? "bg-neutral-700 text-accent-500"
: `text-neutral-200`
}
`}
data-locale={locale.code}
data-webroot={webroot}

View file

@ -1,6 +1,5 @@
// 預設開放註冊(開箱即用),管理者可設為 false 來關閉
export const ACCOUNT_REGISTRATION =
process.env.ACCOUNT_REGISTRATION?.toLowerCase() !== "false";
export const ACCOUNT_REGISTRATION = process.env.ACCOUNT_REGISTRATION?.toLowerCase() !== "false";
export const HTTP_ALLOWED = process.env.HTTP_ALLOWED?.toLowerCase() === "true" || false;

View file

@ -76,15 +76,71 @@ import am from "../locales/am.json";
import zu from "../locales/zu.json";
export type SupportedLocale =
| "en" | "zh-TW" | "zh-CN" | "ja" | "ko"
| "de" | "fr" | "es" | "it" | "pt" | "ru" | "nl" | "pl" | "uk"
| "cs" | "sv" | "da" | "fi" | "no" | "el" | "hu" | "ro" | "bg"
| "hr" | "sk" | "sl" | "lt" | "lv" | "et" | "sr" | "ca" | "eu"
| "gl" | "is" | "ga" | "cy" | "mt" | "mk" | "sq"
| "ar" | "he" | "fa" | "tr"
| "hi" | "bn" | "ta" | "te" | "mr" | "gu" | "kn" | "ml" | "ne" | "si"
| "th" | "vi" | "id" | "ms" | "fil" | "my" | "km" | "lo"
| "af" | "sw" | "am" | "zu";
| "en"
| "zh-TW"
| "zh-CN"
| "ja"
| "ko"
| "de"
| "fr"
| "es"
| "it"
| "pt"
| "ru"
| "nl"
| "pl"
| "uk"
| "cs"
| "sv"
| "da"
| "fi"
| "no"
| "el"
| "hu"
| "ro"
| "bg"
| "hr"
| "sk"
| "sl"
| "lt"
| "lv"
| "et"
| "sr"
| "ca"
| "eu"
| "gl"
| "is"
| "ga"
| "cy"
| "mt"
| "mk"
| "sq"
| "ar"
| "he"
| "fa"
| "tr"
| "hi"
| "bn"
| "ta"
| "te"
| "mr"
| "gu"
| "kn"
| "ml"
| "ne"
| "si"
| "th"
| "vi"
| "id"
| "ms"
| "fil"
| "my"
| "km"
| "lo"
| "af"
| "sw"
| "am"
| "zu";
export interface LocaleConfig {
code: SupportedLocale;
@ -99,7 +155,7 @@ export const supportedLocales: LocaleConfig[] = [
{ code: "en", name: "English", nativeName: "English" },
{ code: "ja", name: "Japanese", nativeName: "日本語" },
{ code: "ko", name: "Korean", nativeName: "한국어" },
// European languages
{ code: "de", name: "German", nativeName: "Deutsch" },
{ code: "fr", name: "French", nativeName: "Français" },
@ -135,13 +191,13 @@ export const supportedLocales: LocaleConfig[] = [
{ code: "mt", name: "Maltese", nativeName: "Malti" },
{ code: "mk", name: "Macedonian", nativeName: "Македонски" },
{ code: "sq", name: "Albanian", nativeName: "Shqip" },
// Middle East & Central Asian languages
{ code: "ar", name: "Arabic", nativeName: "العربية" },
{ code: "he", name: "Hebrew", nativeName: "עברית" },
{ code: "fa", name: "Persian", nativeName: "فارسی" },
{ code: "tr", name: "Turkish", nativeName: "Türkçe" },
// South Asian languages
{ code: "hi", name: "Hindi", nativeName: "हिन्दी" },
{ code: "bn", name: "Bengali", nativeName: "বাংলা" },
@ -153,7 +209,7 @@ export const supportedLocales: LocaleConfig[] = [
{ code: "ml", name: "Malayalam", nativeName: "മലയാളം" },
{ code: "ne", name: "Nepali", nativeName: "नेपाली" },
{ code: "si", name: "Sinhala", nativeName: "සිංහල" },
// Southeast Asian languages
{ code: "th", name: "Thai", nativeName: "ไทย" },
{ code: "vi", name: "Vietnamese", nativeName: "Tiếng Việt" },
@ -163,7 +219,7 @@ export const supportedLocales: LocaleConfig[] = [
{ code: "my", name: "Burmese", nativeName: "မြန်မာ" },
{ code: "km", name: "Khmer", nativeName: "ខ្មែរ" },
{ code: "lo", name: "Lao", nativeName: "ລາວ" },
// African languages
{ code: "af", name: "Afrikaans", nativeName: "Afrikaans" },
{ code: "sw", name: "Swahili", nativeName: "Kiswahili" },
@ -187,7 +243,7 @@ const translations: Record<SupportedLocale, TranslationData> = {
"zh-CN": zhCN as TranslationData,
ja: ja as TranslationData,
ko: ko as TranslationData,
// European languages
de: de as TranslationData,
fr: fr as TranslationData,
@ -223,13 +279,13 @@ const translations: Record<SupportedLocale, TranslationData> = {
mt: mt as TranslationData,
mk: mk as TranslationData,
sq: sq as TranslationData,
// Middle East & Central Asian languages
ar: ar as TranslationData,
he: he as TranslationData,
fa: fa as TranslationData,
tr: tr as TranslationData,
// South Asian languages
hi: hi as TranslationData,
bn: bn as TranslationData,
@ -241,7 +297,7 @@ const translations: Record<SupportedLocale, TranslationData> = {
ml: ml as TranslationData,
ne: ne as TranslationData,
si: si as TranslationData,
// Southeast Asian languages
th: th as TranslationData,
vi: vi as TranslationData,
@ -251,7 +307,7 @@ const translations: Record<SupportedLocale, TranslationData> = {
my: my as TranslationData,
km: km as TranslationData,
lo: lo as TranslationData,
// African languages
af: af as TranslationData,
sw: sw as TranslationData,
@ -278,8 +334,7 @@ export function t<T extends TranslationKey>(
if (typeof translation !== "string") {
// Fallback to English
const fallback =
translations[fallbackLocale]?.[category]?.[key as keyof TranslationData[T]];
const fallback = translations[fallbackLocale]?.[category]?.[key as keyof TranslationData[T]];
if (typeof fallback !== "string") {
return `${category}.${String(key)}`;
}
@ -326,9 +381,7 @@ export function detectLocale(acceptLanguage?: string): SupportedLocale {
// Try to find a match
for (const lang of languages) {
// Direct match (case-insensitive)
const directMatch = supportedLocales.find(
(l) => l.code.toLowerCase() === lang.code
);
const directMatch = supportedLocales.find((l) => l.code.toLowerCase() === lang.code);
if (directMatch) {
return directMatch.code;
}
@ -347,7 +400,7 @@ export function detectLocale(acceptLanguage?: string): SupportedLocale {
const baseCode = lang.code.split("-")[0];
if (baseCode) {
const baseMatch = supportedLocales.find(
(l) => l.code.toLowerCase() === baseCode || l.code.toLowerCase().startsWith(baseCode + "-")
(l) => l.code.toLowerCase() === baseCode || l.code.toLowerCase().startsWith(baseCode + "-"),
);
if (baseMatch) {
return baseMatch.code;
@ -364,9 +417,7 @@ export function detectLocale(acceptLanguage?: string): SupportedLocale {
* @returns Whether the locale is valid
*/
export function isValidLocale(locale: string): locale is SupportedLocale {
return supportedLocales.some(
(l) => l.code.toLowerCase() === locale.toLowerCase(),
);
return supportedLocales.some((l) => l.code.toLowerCase() === locale.toLowerCase());
}
/**
@ -376,11 +427,11 @@ export function isValidLocale(locale: string): locale is SupportedLocale {
*/
export function getLocale(locale?: string): SupportedLocale {
if (!locale) return defaultLocale;
// Handle case-insensitive matching
const normalized = locale.toLowerCase();
const found = supportedLocales.find((l) => l.code.toLowerCase() === normalized);
return found?.code ?? defaultLocale;
}

View file

@ -1,17 +1,13 @@
import { Elysia } from "elysia";
import {
type SupportedLocale,
createTranslator,
detectLocale,
getLocale,
} from "./index";
import { type SupportedLocale, createTranslator, detectLocale, getLocale } from "./index";
/**
* Elysia plugin for i18n/locale handling
* Adds locale detection and translator to the context
*/
export const localeService = new Elysia({ name: "locale/service" })
.derive({ as: "global" }, ({ request }) => {
export const localeService = new Elysia({ name: "locale/service" }).derive(
{ as: "global" },
({ request }) => {
// Get locale from cookie (parsed from headers) or detect from Accept-Language header
const cookieHeader = request.headers.get("cookie") ?? "";
const acceptLanguage = request.headers.get("accept-language") ?? undefined;
@ -37,7 +33,8 @@ export const localeService = new Elysia({ name: "locale/service" })
locale,
t: translator,
};
});
},
);
export type LocaleContext = {
locale: SupportedLocale;

View file

@ -9,233 +9,245 @@ import { userService } from "./user";
import { EyeIcon } from "../icons/eye";
import { DeleteIcon } from "../icons/delete";
export const history = new Elysia().use(userService).use(localeService).get(
"/history",
async ({ redirect, user, locale, t }) => {
if (HIDE_HISTORY) {
return redirect(`${WEBROOT}/`, 302);
}
export const history = new Elysia()
.use(userService)
.use(localeService)
.get(
"/history",
async ({ redirect, user, locale, t }) => {
if (HIDE_HISTORY) {
return redirect(`${WEBROOT}/`, 302);
}
if (!user) {
return redirect(`${WEBROOT}/login`, 302);
}
if (!user) {
return redirect(`${WEBROOT}/login`, 302);
}
let userJobs = db.query("SELECT * FROM jobs WHERE user_id = ?").as(Jobs).all(user.id).reverse();
let userJobs = db
.query("SELECT * FROM jobs WHERE user_id = ?")
.as(Jobs)
.all(user.id)
.reverse();
for (const job of userJobs) {
const files = db.query("SELECT * FROM file_names WHERE job_id = ?").as(Filename).all(job.id);
for (const job of userJobs) {
const files = db
.query("SELECT * FROM file_names WHERE job_id = ?")
.as(Filename)
.all(job.id);
job.finished_files = files.length;
job.files_detailed = files;
}
job.finished_files = files.length;
job.files_detailed = files;
}
// Filter out jobs with no files
userJobs = userJobs.filter((job) => job.num_files > 0);
// Filter out jobs with no files
userJobs = userJobs.filter((job) => job.num_files > 0);
return (
<BaseHtml webroot={WEBROOT} title="ConvertX-CN | Results" locale={locale}>
<>
<Header
webroot={WEBROOT}
allowUnauthenticated={ALLOW_UNAUTHENTICATED}
hideHistory={HIDE_HISTORY}
loggedIn
locale={locale}
t={t}
/>
<main
class={`
w-full flex-1 px-2
sm:px-4
`}
>
<article class="article">
<div class="mb-4 flex items-center justify-between">
<h1 class="text-xl">{t("history", "title")}</h1>
<div id="delete-selected-container">
<button
id="delete-selected-btn"
class={`
flex btn-secondary flex-row gap-2 text-contrast
disabled:cursor-not-allowed disabled:opacity-50
`}
disabled
>
<DeleteIcon />{" "}
<span>
{t("history", "deleteSelected")} (<span id="selected-count">0</span>)
</span>
</button>
return (
<BaseHtml webroot={WEBROOT} title="ConvertX-CN | Results" locale={locale}>
<>
<Header
webroot={WEBROOT}
allowUnauthenticated={ALLOW_UNAUTHENTICATED}
hideHistory={HIDE_HISTORY}
loggedIn
locale={locale}
t={t}
/>
<main
class={`
w-full flex-1 px-2
sm:px-4
`}
>
<article class="article">
<div class="mb-4 flex items-center justify-between">
<h1 class="text-xl">{t("history", "title")}</h1>
<div id="delete-selected-container">
<button
id="delete-selected-btn"
class={`
flex btn-secondary flex-row gap-2 text-contrast
disabled:cursor-not-allowed disabled:opacity-50
`}
disabled
>
<DeleteIcon />{" "}
<span>
{t("history", "deleteSelected")} (<span id="selected-count">0</span>)
</span>
</button>
</div>
</div>
</div>
<table
class={`
w-full table-auto overflow-y-auto rounded bg-neutral-900 text-left
[&_td]:p-4
[&_tr]:rounded-sm [&_tr]:border-b [&_tr]:border-neutral-800
`}
>
<thead>
<tr>
<th
class={`
px-2 py-2
sm:px-4
`}
>
<input
type="checkbox"
id="select-all"
class="h-4 w-4 cursor-pointer"
title={t("history", "selectAll")}
/>
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
<span class="sr-only">{t("history", "expandDetails")}</span>
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "time")}
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "files")}
</th>
<th
class={`
px-2 py-2
max-sm:hidden
sm:px-4
`}
>
{t("history", "filesDone")}
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "status")}
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "actions")}
</th>
</tr>
</thead>
<tbody>
{userJobs.map((job) => (
<>
<tr id={`job-row-${job.id}`}>
<td>
<input
type="checkbox"
class="h-4 w-4 cursor-pointer"
data-checkbox-type="job"
data-job-id={job.id}
/>
</td>
<td class="job-details-toggle cursor-pointer" data-job-id={job.id}>
<svg
id={`arrow-${job.id}`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="inline-block h-4 w-4"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M8.25 4.5l7.5 7.5-7.5 7.5"
<table
class={`
w-full table-auto overflow-y-auto rounded bg-neutral-900 text-left
[&_td]:p-4
[&_tr]:rounded-sm [&_tr]:border-b [&_tr]:border-neutral-800
`}
>
<thead>
<tr>
<th
class={`
px-2 py-2
sm:px-4
`}
>
<input
type="checkbox"
id="select-all"
class="h-4 w-4 cursor-pointer"
title={t("history", "selectAll")}
/>
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
<span class="sr-only">{t("history", "expandDetails")}</span>
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "time")}
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "files")}
</th>
<th
class={`
px-2 py-2
max-sm:hidden
sm:px-4
`}
>
{t("history", "filesDone")}
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "status")}
</th>
<th
class={`
px-2 py-2
sm:px-4
`}
>
{t("history", "actions")}
</th>
</tr>
</thead>
<tbody>
{userJobs.map((job) => (
<>
<tr id={`job-row-${job.id}`}>
<td>
<input
type="checkbox"
class="h-4 w-4 cursor-pointer"
data-checkbox-type="job"
data-job-id={job.id}
/>
</svg>
</td>
<td safe>
{new Date(job.date_created).toLocaleTimeString(LANGUAGE, {
timeZone: TIMEZONE,
})}
</td>
<td>{job.num_files}</td>
<td class="max-sm:hidden">{job.finished_files}</td>
<td safe>{job.status}</td>
<td class="flex flex-row gap-4">
<a
class={`
text-accent-500 underline
hover:text-accent-400
`}
href={`${WEBROOT}/results/${job.id}`}
>
<EyeIcon />
</a>
<a
class={`
text-accent-500 underline
hover:text-accent-400
`}
href={`${WEBROOT}/delete/${job.id}`}
>
<DeleteIcon />
</a>
</td>
</tr>
<tr id={`details-${job.id}`} class="hidden">
<td colspan="7">
<div class="p-2 text-sm text-neutral-500">
<div class="mb-1 font-semibold">{t("history", "detailedFileInfo")}</div>
{job.files_detailed.map((file: Filename) => (
<div class="flex items-center">
<span class="w-5/12 truncate" title={file.file_name} safe>
{file.file_name}
</span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class={`mx-2 inline-block h-4 w-4 text-neutral-500`}
>
<path
fill-rule="evenodd"
d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z"
clip-rule="evenodd"
/>
</svg>
<span class="w-5/12 truncate" title={file.output_file_name} safe>
{file.output_file_name}
</span>
</td>
<td class="job-details-toggle cursor-pointer" data-job-id={job.id}>
<svg
id={`arrow-${job.id}`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="inline-block h-4 w-4"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M8.25 4.5l7.5 7.5-7.5 7.5"
/>
</svg>
</td>
<td safe>
{new Date(job.date_created).toLocaleTimeString(LANGUAGE, {
timeZone: TIMEZONE,
})}
</td>
<td>{job.num_files}</td>
<td class="max-sm:hidden">{job.finished_files}</td>
<td safe>{job.status}</td>
<td class="flex flex-row gap-4">
<a
class={`
text-accent-500 underline
hover:text-accent-400
`}
href={`${WEBROOT}/results/${job.id}`}
>
<EyeIcon />
</a>
<a
class={`
text-accent-500 underline
hover:text-accent-400
`}
href={`${WEBROOT}/delete/${job.id}`}
>
<DeleteIcon />
</a>
</td>
</tr>
<tr id={`details-${job.id}`} class="hidden">
<td colspan="7">
<div class="p-2 text-sm text-neutral-500">
<div class="mb-1 font-semibold">
{t("history", "detailedFileInfo")}
</div>
))}
</div>
</td>
</tr>
</>
))}
</tbody>
</table>
</article>
</main>
<script>
{`
{job.files_detailed.map((file: Filename) => (
<div class="flex items-center">
<span class="w-5/12 truncate" title={file.file_name} safe>
{file.file_name}
</span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class={`mx-2 inline-block h-4 w-4 text-neutral-500`}
>
<path
fill-rule="evenodd"
d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z"
clip-rule="evenodd"
/>
</svg>
<span class="w-5/12 truncate" title={file.output_file_name} safe>
{file.output_file_name}
</span>
</div>
))}
</div>
</td>
</tr>
</>
))}
</tbody>
</table>
</article>
</main>
<script>
{`
document.addEventListener('DOMContentLoaded', () => {
// Expand/collapse job details
const toggles = document.querySelectorAll('.job-details-toggle');
@ -330,12 +342,12 @@ export const history = new Elysia().use(userService).use(localeService).get(
});
});
`}
</script>
</>
</BaseHtml>
);
},
{
auth: true,
},
);
</script>
</>
</BaseHtml>
);
},
{
auth: true,
},
);

View file

@ -7,7 +7,7 @@ import { ALLOW_UNAUTHENTICATED, WEBROOT } from "../helpers/env";
import { DownloadIcon } from "../icons/download";
import { DeleteIcon } from "../icons/delete";
import { EyeIcon } from "../icons/eye";
import { type SupportedLocale, type Translator, createTranslator, defaultLocale } from "../i18n/index";
import { type Translator, createTranslator, defaultLocale } from "../i18n/index";
import { localeService } from "../i18n/service";
import { userService } from "./user";
@ -165,7 +165,13 @@ export const results = new Elysia()
return (
<BaseHtml webroot={WEBROOT} title="ConvertX-CN | Result" locale={locale}>
<>
<Header webroot={WEBROOT} allowUnauthenticated={ALLOW_UNAUTHENTICATED} loggedIn locale={locale} t={t} />
<Header
webroot={WEBROOT}
allowUnauthenticated={ALLOW_UNAUTHENTICATED}
loggedIn
locale={locale}
t={t}
/>
<main
class={`
w-full flex-1 px-2

View file

@ -17,237 +17,245 @@ import {
import { localeService } from "../i18n/service";
import { FIRST_RUN, userService } from "./user";
export const root = new Elysia().use(userService).use(localeService).get(
"/",
async ({ jwt, redirect, cookie: { auth, jobId }, locale, t }) => {
if (!ALLOW_UNAUTHENTICATED) {
if (FIRST_RUN) {
return redirect(`${WEBROOT}/setup`, 302);
export const root = new Elysia()
.use(userService)
.use(localeService)
.get(
"/",
async ({ jwt, redirect, cookie: { auth, jobId }, locale, t }) => {
if (!ALLOW_UNAUTHENTICATED) {
if (FIRST_RUN) {
return redirect(`${WEBROOT}/setup`, 302);
}
if (!auth?.value) {
return redirect(`${WEBROOT}/login`, 302);
}
}
if (!auth?.value) {
// validate jwt
let user: ({ id: string } & JWTPayloadSpec) | false = false;
if (ALLOW_UNAUTHENTICATED) {
const newUserId = String(
UNAUTHENTICATED_USER_SHARING
? 0
: randomInt(2 ** 24, Math.min(2 ** 48 + 2 ** 24 - 1, Number.MAX_SAFE_INTEGER)),
);
const accessToken = await jwt.sign({
id: newUserId,
});
user = { id: newUserId };
if (!auth) {
return {
message: t("auth", "noCookies"),
};
}
// set cookie
auth.set({
value: accessToken,
httpOnly: true,
secure: !HTTP_ALLOWED,
maxAge: 24 * 60 * 60,
sameSite: "strict",
});
} else if (auth?.value) {
user = await jwt.verify(auth.value);
if (
user !== false &&
user.id &&
(Number.parseInt(user.id) < 2 ** 24 || !ALLOW_UNAUTHENTICATED)
) {
// Make sure user exists in db
const existingUser = db.query("SELECT * FROM users WHERE id = ?").as(User).get(user.id);
if (!existingUser) {
if (auth?.value) {
auth.remove();
}
return redirect(`${WEBROOT}/login`, 302);
}
}
}
if (!user) {
return redirect(`${WEBROOT}/login`, 302);
}
}
// validate jwt
let user: ({ id: string } & JWTPayloadSpec) | false = false;
if (ALLOW_UNAUTHENTICATED) {
const newUserId = String(
UNAUTHENTICATED_USER_SHARING
? 0
: randomInt(2 ** 24, Math.min(2 ** 48 + 2 ** 24 - 1, Number.MAX_SAFE_INTEGER)),
// create a new job
db.query("INSERT INTO jobs (user_id, date_created) VALUES (?, ?)").run(
user.id,
new Date().toISOString(),
);
const accessToken = await jwt.sign({
id: newUserId,
});
user = { id: newUserId };
if (!auth) {
return {
message: t("auth", "noCookies"),
};
const { id } = db
.query("SELECT id FROM jobs WHERE user_id = ? ORDER BY id DESC")
.get(user.id) as { id: number };
if (!jobId) {
return { message: t("auth", "cookiesRequired") };
}
// set cookie
auth.set({
value: accessToken,
jobId.set({
value: id,
httpOnly: true,
secure: !HTTP_ALLOWED,
maxAge: 24 * 60 * 60,
sameSite: "strict",
});
} else if (auth?.value) {
user = await jwt.verify(auth.value);
if (
user !== false &&
user.id &&
(Number.parseInt(user.id) < 2 ** 24 || !ALLOW_UNAUTHENTICATED)
) {
// Make sure user exists in db
const existingUser = db.query("SELECT * FROM users WHERE id = ?").as(User).get(user.id);
console.log("jobId set to:", id);
if (!existingUser) {
if (auth?.value) {
auth.remove();
}
return redirect(`${WEBROOT}/login`, 302);
}
}
}
if (!user) {
return redirect(`${WEBROOT}/login`, 302);
}
// create a new job
db.query("INSERT INTO jobs (user_id, date_created) VALUES (?, ?)").run(
user.id,
new Date().toISOString(),
);
const { id } = db
.query("SELECT id FROM jobs WHERE user_id = ? ORDER BY id DESC")
.get(user.id) as { id: number };
if (!jobId) {
return { message: t("auth", "cookiesRequired") };
}
jobId.set({
value: id,
httpOnly: true,
secure: !HTTP_ALLOWED,
maxAge: 24 * 60 * 60,
sameSite: "strict",
});
console.log("jobId set to:", id);
return (
<BaseHtml webroot={WEBROOT} locale={locale}>
<>
<Header
webroot={WEBROOT}
accountRegistration={ACCOUNT_REGISTRATION}
allowUnauthenticated={ALLOW_UNAUTHENTICATED}
hideHistory={HIDE_HISTORY}
loggedIn
locale={locale}
t={t}
/>
<main
class={`
w-full flex-1 px-2
sm:px-4
`}
>
<article class="article">
<h1 class="mb-4 text-xl">{t("convert", "title")}</h1>
<div class="mb-4 scrollbar-thin max-h-[50vh] overflow-y-auto">
<table
id="file-list"
class={`
w-full table-auto rounded bg-neutral-900
[&_td]:p-4 [&_td]:first:max-w-[30vw] [&_td]:first:truncate
[&_tr]:rounded-sm [&_tr]:border-b [&_tr]:border-neutral-800
`}
/>
</div>
<div
id="dropzone"
class={`
relative flex h-48 w-full items-center justify-center rounded border border-dashed
border-neutral-700 transition-all
hover:border-neutral-600
[&.dragover]:border-4 [&.dragover]:border-neutral-500
`}
>
<span>
<b>{t("convert", "chooseFile")}</b> {t("convert", "orDragHere")}
</span>
<input
type="file"
name="file"
multiple
class="absolute inset-0 size-full cursor-pointer opacity-0"
/>
</div>
</article>
<form
method="post"
action={`${WEBROOT}/convert`}
class="relative mx-auto mb-[35vh] w-full max-w-4xl"
return (
<BaseHtml webroot={WEBROOT} locale={locale}>
<>
<Header
webroot={WEBROOT}
accountRegistration={ACCOUNT_REGISTRATION}
allowUnauthenticated={ALLOW_UNAUTHENTICATED}
hideHistory={HIDE_HISTORY}
loggedIn
locale={locale}
t={t}
/>
<main
class={`
w-full flex-1 px-2
sm:px-4
`}
>
<input type="hidden" name="file_names" id="file_names" />
<article class="article w-full">
<input
type="search"
name="convert_to_search"
placeholder={t("convert", "searchConversions")}
autocomplete="off"
class="w-full rounded-sm bg-neutral-800 p-4"
/>
<div class="select_container relative">
<article
<article class="article">
<h1 class="mb-4 text-xl">{t("convert", "title")}</h1>
<div class="mb-4 scrollbar-thin max-h-[50vh] overflow-y-auto">
<table
id="file-list"
class={`
convert_to_popup absolute z-2 m-0 hidden h-[30vh] max-h-[50vh] w-full flex-col
overflow-x-hidden overflow-y-auto rounded bg-neutral-800
sm:h-[30vh]
w-full table-auto rounded bg-neutral-900
[&_td]:p-4 [&_td]:first:max-w-[30vw] [&_td]:first:truncate
[&_tr]:rounded-sm [&_tr]:border-b [&_tr]:border-neutral-800
`}
>
{Object.entries(getAllTargets()).map(([converter, targets]) => (
<article
class={`
convert_to_group flex w-full flex-col border-b border-neutral-700 p-4
`}
data-converter={converter}
>
<header class="mb-2 w-full text-xl font-bold" safe>
{converter}
</header>
<ul class={`convert_to_target flex flex-row flex-wrap gap-1`}>
{targets.map((target) => (
<button
// https://stackoverflow.com/questions/121499/when-a-blur-event-occurs-how-can-i-find-out-which-element-focus-went-to#comment82388679_33325953
tabindex={0}
class={`
target rounded bg-neutral-700 p-1 text-base
hover:bg-neutral-600
`}
data-value={`${target},${converter}`}
data-target={target}
data-converter={converter}
type="button"
safe
>
{target}
</button>
))}
</ul>
</article>
))}
</article>
{/* Hidden element which determines the format to convert the file too and the converter to use */}
<select name="convert_to" aria-label={t("convert", "convertTo")} required hidden>
<option selected disabled value="">
{t("convert", "convertTo")}
</option>
{Object.entries(getAllTargets()).map(([converter, targets]) => (
<optgroup label={converter}>
{targets.map((target) => (
<option value={`${target},${converter}`} safe>
{target}
</option>
))}
</optgroup>
))}
</select>
/>
</div>
<div
id="dropzone"
class={`
relative flex h-48 w-full items-center justify-center rounded border
border-dashed border-neutral-700 transition-all
hover:border-neutral-600
[&.dragover]:border-4 [&.dragover]:border-neutral-500
`}
>
<span>
<b>{t("convert", "chooseFile")}</b> {t("convert", "orDragHere")}
</span>
<input
type="file"
name="file"
multiple
class="absolute inset-0 size-full cursor-pointer opacity-0"
/>
</div>
</article>
<input
class={`
w-full btn-primary opacity-100
disabled:cursor-not-allowed disabled:opacity-50
`}
type="submit"
value={t("convert", "convertButton")}
disabled
/>
</form>
</main>
<script src="script.js" defer />
</>
</BaseHtml>
);
},
{
cookie: t.Cookie({
auth: t.Optional(t.String()),
jobId: t.Optional(t.String()),
locale: t.Optional(t.String()),
}),
},
);
<form
method="post"
action={`${WEBROOT}/convert`}
class="relative mx-auto mb-[35vh] w-full max-w-4xl"
>
<input type="hidden" name="file_names" id="file_names" />
<article class="article w-full">
<input
type="search"
name="convert_to_search"
placeholder={t("convert", "searchConversions")}
autocomplete="off"
class="w-full rounded-sm bg-neutral-800 p-4"
/>
<div class="select_container relative">
<article
class={`
convert_to_popup absolute z-2 m-0 hidden h-[30vh] max-h-[50vh] w-full
flex-col overflow-x-hidden overflow-y-auto rounded bg-neutral-800
sm:h-[30vh]
`}
>
{Object.entries(getAllTargets()).map(([converter, targets]) => (
<article
class={`
convert_to_group flex w-full flex-col border-b border-neutral-700 p-4
`}
data-converter={converter}
>
<header class="mb-2 w-full text-xl font-bold" safe>
{converter}
</header>
<ul class={`convert_to_target flex flex-row flex-wrap gap-1`}>
{targets.map((target) => (
<button
// https://stackoverflow.com/questions/121499/when-a-blur-event-occurs-how-can-i-find-out-which-element-focus-went-to#comment82388679_33325953
tabindex={0}
class={`
target rounded bg-neutral-700 p-1 text-base
hover:bg-neutral-600
`}
data-value={`${target},${converter}`}
data-target={target}
data-converter={converter}
type="button"
safe
>
{target}
</button>
))}
</ul>
</article>
))}
</article>
{/* Hidden element which determines the format to convert the file too and the converter to use */}
<select
name="convert_to"
aria-label={t("convert", "convertTo")}
required
hidden
>
<option selected disabled value="">
{t("convert", "convertTo")}
</option>
{Object.entries(getAllTargets()).map(([converter, targets]) => (
<optgroup label={converter}>
{targets.map((target) => (
<option value={`${target},${converter}`} safe>
{target}
</option>
))}
</optgroup>
))}
</select>
</div>
</article>
<input
class={`
w-full btn-primary opacity-100
disabled:cursor-not-allowed disabled:opacity-50
`}
type="submit"
value={t("convert", "convertButton")}
disabled
/>
</form>
</main>
<script src="script.js" defer />
</>
</BaseHtml>
);
},
{
cookie: t.Cookie({
auth: t.Optional(t.String()),
jobId: t.Optional(t.String()),
locale: t.Optional(t.String()),
}),
},
);

View file

@ -173,7 +173,11 @@ export const user = new Elysia()
/>
</label>
</fieldset>
<input type="submit" value={t("auth", "registerButton")} class="w-full btn-primary" />
<input
type="submit"
value={t("auth", "registerButton")}
class="w-full btn-primary"
/>
</form>
</article>
</main>
@ -302,7 +306,11 @@ export const user = new Elysia()
>
{t("nav", "register")}
</a>
<input type="submit" value={t("auth", "loginButton")} class="w-full btn-primary" />
<input
type="submit"
value={t("auth", "loginButton")}
class="w-full btn-primary"
/>
</div>
</form>
</article>
@ -441,7 +449,11 @@ export const user = new Elysia()
</label>
</fieldset>
<div role="group">
<input type="submit" value={t("auth", "updateButton")} class="w-full btn-primary" />
<input
type="submit"
value={t("auth", "updateButton")}
class={`w-full btn-primary`}
/>
</div>
</form>
</article>