Compare commits

..

4 commits

Author SHA1 Message Date
a6b444fcea fix: cropping images decreases resolution 2026-03-27 18:21:38 +00:00
1e1c38ffc0 fix: #10
Fixes/adds:
- ability to edit instructions
- center indicator on range inputs
- birthdays
2026-03-27 18:15:09 +00:00
540480b665 fix: outdated add mii tutorial for switch 2026-03-27 12:37:07 +00:00
2066b9fb4b feat: crop portrait and split portrait+features image 2026-03-27 12:21:51 +00:00
32 changed files with 623 additions and 247 deletions

View file

@ -30,6 +30,7 @@
"react": "^19.2.4", "react": "^19.2.4",
"react-dom": "^19.2.4", "react-dom": "^19.2.4",
"react-dropzone": "^15.0.0", "react-dropzone": "^15.0.0",
"react-image-crop": "^11.0.10",
"redis": "^5.11.0", "redis": "^5.11.0",
"satori": "^0.25.0", "satori": "^0.25.0",
"seedrandom": "^3.0.5", "seedrandom": "^3.0.5",

View file

@ -65,6 +65,9 @@ importers:
react-dropzone: react-dropzone:
specifier: ^15.0.0 specifier: ^15.0.0
version: 15.0.0(react@19.2.4) version: 15.0.0(react@19.2.4)
react-image-crop:
specifier: ^11.0.10
version: 11.0.10(react@19.2.4)
redis: redis:
specifier: ^5.11.0 specifier: ^5.11.0
version: 5.11.0 version: 5.11.0
@ -2934,6 +2937,11 @@ packages:
peerDependencies: peerDependencies:
react: '>= 16.8 || 18.0.0' react: '>= 16.8 || 18.0.0'
react-image-crop@11.0.10:
resolution: {integrity: sha512-+5FfDXUgYLLqBh1Y/uQhIycpHCbXkI50a+nbfkB1C0xXXUTwkisHDo2QCB1SQJyHCqIuia4FeyReqXuMDKWQTQ==}
peerDependencies:
react: '>=16.13.1'
react-is@16.13.1: react-is@16.13.1:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
@ -5294,8 +5302,8 @@ snapshots:
'@next/eslint-plugin-next': 16.2.0 '@next/eslint-plugin-next': 16.2.0
eslint: 10.0.3(jiti@2.6.1) eslint: 10.0.3(jiti@2.6.1)
eslint-import-resolver-node: 0.3.9 eslint-import-resolver-node: 0.3.9
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@10.0.3(jiti@2.6.1)) eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1))
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@10.0.3(jiti@2.6.1)) eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1))
eslint-plugin-jsx-a11y: 6.10.2(eslint@10.0.3(jiti@2.6.1)) eslint-plugin-jsx-a11y: 6.10.2(eslint@10.0.3(jiti@2.6.1))
eslint-plugin-react: 7.37.5(eslint@10.0.3(jiti@2.6.1)) eslint-plugin-react: 7.37.5(eslint@10.0.3(jiti@2.6.1))
eslint-plugin-react-hooks: 7.0.1(eslint@10.0.3(jiti@2.6.1)) eslint-plugin-react-hooks: 7.0.1(eslint@10.0.3(jiti@2.6.1))
@ -5317,7 +5325,7 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@10.0.3(jiti@2.6.1)): eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)):
dependencies: dependencies:
'@nolyfill/is-core-module': 1.0.39 '@nolyfill/is-core-module': 1.0.39
debug: 4.4.3 debug: 4.4.3
@ -5328,22 +5336,22 @@ snapshots:
tinyglobby: 0.2.15 tinyglobby: 0.2.15
unrs-resolver: 1.11.1 unrs-resolver: 1.11.1
optionalDependencies: optionalDependencies:
eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@10.0.3(jiti@2.6.1)) eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1))
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
eslint-module-utils@2.12.1(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@10.0.3(jiti@2.6.1)): eslint-module-utils@2.12.1(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)):
dependencies: dependencies:
debug: 3.2.7 debug: 3.2.7
optionalDependencies: optionalDependencies:
'@typescript-eslint/parser': 8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3) '@typescript-eslint/parser': 8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3)
eslint: 10.0.3(jiti@2.6.1) eslint: 10.0.3(jiti@2.6.1)
eslint-import-resolver-node: 0.3.9 eslint-import-resolver-node: 0.3.9
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@10.0.3(jiti@2.6.1)) eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1))
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@10.0.3(jiti@2.6.1)): eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)):
dependencies: dependencies:
'@rtsao/scc': 1.1.0 '@rtsao/scc': 1.1.0
array-includes: 3.1.9 array-includes: 3.1.9
@ -5354,7 +5362,7 @@ snapshots:
doctrine: 2.1.0 doctrine: 2.1.0
eslint: 10.0.3(jiti@2.6.1) eslint: 10.0.3(jiti@2.6.1)
eslint-import-resolver-node: 0.3.9 eslint-import-resolver-node: 0.3.9
eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@10.0.3(jiti@2.6.1)) eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.57.1(eslint@10.0.3(jiti@2.6.1))(typescript@5.9.3))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1)))(eslint@10.0.3(jiti@2.6.1))
hasown: 2.0.2 hasown: 2.0.2
is-core-module: 2.16.1 is-core-module: 2.16.1
is-glob: 4.0.3 is-glob: 4.0.3
@ -6289,6 +6297,10 @@ snapshots:
prop-types: 15.8.1 prop-types: 15.8.1
react: 19.2.4 react: 19.2.4
react-image-crop@11.0.10(react@19.2.4):
dependencies:
react: 19.2.4
react-is@16.13.1: {} react-is@16.13.1: {}
react-is@18.3.1: {} react-is@18.3.1: {}

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

View file

Before

Width:  |  Height:  |  Size: 151 KiB

After

Width:  |  Height:  |  Size: 151 KiB

View file

@ -11,9 +11,11 @@ import { profanity } from "@2toad/profanity";
import { auth } from "@/lib/auth"; import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma"; import { prisma } from "@/lib/prisma";
import { idSchema, nameSchema, tagsSchema } from "@/lib/schemas"; import { idSchema, nameSchema, switchMiiInstructionsSchema, tagsSchema } from "@/lib/schemas";
import { generateMetadataImage, validateImage } from "@/lib/images"; import { generateMetadataImage, validateImage } from "@/lib/images";
import { RateLimit } from "@/lib/rate-limit"; import { RateLimit } from "@/lib/rate-limit";
import { SwitchMiiInstructions } from "@/types";
import { minifyInstructions } from "@/lib/switch";
const uploadsDirectory = path.join(process.cwd(), "uploads", "mii"); const uploadsDirectory = path.join(process.cwd(), "uploads", "mii");
@ -21,6 +23,7 @@ const editSchema = z.object({
name: nameSchema.optional(), name: nameSchema.optional(),
tags: tagsSchema.optional(), tags: tagsSchema.optional(),
description: z.string().trim().max(256).optional(), description: z.string().trim().max(256).optional(),
instructions: switchMiiInstructionsSchema,
image1: z.union([z.instanceof(File), z.any()]).optional(), image1: z.union([z.instanceof(File), z.any()]).optional(),
image2: z.union([z.instanceof(File), z.any()]).optional(), image2: z.union([z.instanceof(File), z.any()]).optional(),
image3: z.union([z.instanceof(File), z.any()]).optional(), image3: z.union([z.instanceof(File), z.any()]).optional(),
@ -31,7 +34,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
Sentry.setUser({ id: session.user?.id, name: session.user?.name }); Sentry.setUser({ id: session.user?.id, name: session.user?.name });
const rateLimit = new RateLimit(request, 1); // no grouped pathname; edit each mii 1 time a minute const rateLimit = new RateLimit(request, 3); // no grouped pathname; edit each mii 1 time a minute
const check = await rateLimit.handle(); const check = await rateLimit.handle();
if (check) return check; if (check) return check;
@ -63,17 +66,22 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
return rateLimit.sendResponse({ error: "Invalid JSON in tags" }, 400); return rateLimit.sendResponse({ error: "Invalid JSON in tags" }, 400);
} }
let minifiedInstructions: Partial<SwitchMiiInstructions> | undefined;
if (mii.platform === "SWITCH")
minifiedInstructions = minifyInstructions(JSON.parse((formData.get("instructions") as string) ?? "{}") as SwitchMiiInstructions);
const parsed = editSchema.safeParse({ const parsed = editSchema.safeParse({
name: formData.get("name") ?? undefined, name: formData.get("name") ?? undefined,
tags: rawTags, tags: rawTags,
description: formData.get("description") ?? undefined, description: formData.get("description") ?? undefined,
instructions: minifiedInstructions,
image1: formData.get("image1"), image1: formData.get("image1"),
image2: formData.get("image2"), image2: formData.get("image2"),
image3: formData.get("image3"), image3: formData.get("image3"),
}); });
if (!parsed.success) return rateLimit.sendResponse({ error: parsed.error.issues[0].message }, 400); if (!parsed.success) return rateLimit.sendResponse({ error: parsed.error.issues[0].message }, 400);
const { name, tags, description, image1, image2, image3 } = parsed.data; const { name, tags, description, instructions, image1, image2, image3 } = parsed.data;
// Validate image files // Validate image files
const images: File[] = []; const images: File[] = [];
@ -91,9 +99,10 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
// Edit Mii in database // Edit Mii in database
const updateData: Prisma.MiiUpdateInput = {}; const updateData: Prisma.MiiUpdateInput = {};
if (name !== undefined) updateData.name = profanity.censor(name); // Censor potential inappropriate words if (name !== undefined) updateData.name = profanity.censor(name); // Censor potentially inappropriate words
if (tags !== undefined) updateData.tags = tags.map((t) => profanity.censor(t)); // Same here if (tags !== undefined) updateData.tags = tags.map((t) => profanity.censor(t));
if (description !== undefined) updateData.description = profanity.censor(description); if (description !== undefined) updateData.description = profanity.censor(description);
if (instructions !== undefined) updateData.instructions = instructions;
if (images.length > 0) updateData.imageCount = images.length; if (images.length > 0) updateData.imageCount = images.length;
if (Object.keys(updateData).length == 0) return rateLimit.sendResponse({ error: "Nothing was changed" }, 400); if (Object.keys(updateData).length == 0) return rateLimit.sendResponse({ error: "Nothing was changed" }, 400);

View file

@ -20,6 +20,7 @@ import Mii from "@/lib/mii.js/mii";
import { ThreeDsTomodachiLifeMii } from "@/lib/three-ds-tomodachi-life-mii"; import { ThreeDsTomodachiLifeMii } from "@/lib/three-ds-tomodachi-life-mii";
import { SwitchMiiInstructions } from "@/types"; import { SwitchMiiInstructions } from "@/types";
import { minifyInstructions } from "@/lib/switch";
const uploadsDirectory = path.join(process.cwd(), "uploads", "mii"); const uploadsDirectory = path.join(process.cwd(), "uploads", "mii");
@ -33,6 +34,7 @@ const submitSchema = z
// Switch // Switch
gender: z.enum(MiiGender).default("MALE"), gender: z.enum(MiiGender).default("MALE"),
miiPortraitImage: z.union([z.instanceof(File), z.any()]).optional(), miiPortraitImage: z.union([z.instanceof(File), z.any()]).optional(),
miiFeaturesImage: z.union([z.instanceof(File), z.any()]).optional(),
instructions: switchMiiInstructionsSchema, instructions: switchMiiInstructionsSchema,
// QR code // QR code
@ -51,15 +53,15 @@ const submitSchema = z
// This refine function is probably useless // This refine function is probably useless
.refine( .refine(
(data) => { (data) => {
// If platform is Switch, gender and miiPortraitImage must be present // If platform is Switch, gender, miiPortraitImage, and miiFeaturesImage must be present
if (data.platform === "SWITCH") { if (data.platform === "SWITCH") {
return data.gender !== undefined && data.miiPortraitImage !== undefined; return data.gender !== undefined && data.miiPortraitImage !== undefined;
} }
return true; return true;
}, },
{ {
message: "Gender, Mii portrait image, and instructions are required for Switch platform", message: "Gender, Mii portrait & features image, and instructions are required for Switch platform",
path: ["gender", "miiPortraitImage", "instructions"], path: ["gender", "miiPortraitImage", "miiFeaturesImage", "instructions"],
}, },
); );
@ -93,32 +95,8 @@ export async function POST(request: NextRequest) {
// Minify instructions to save space and improve user experience // Minify instructions to save space and improve user experience
let minifiedInstructions: Partial<SwitchMiiInstructions> | undefined; let minifiedInstructions: Partial<SwitchMiiInstructions> | undefined;
if (formData.get("platform") === "SWITCH") { if (formData.get("platform") === "SWITCH")
const DEFAULT_ZERO_FIELDS = new Set(["height", "distance", "rotation", "size", "stretch"]); minifiedInstructions = minifyInstructions(JSON.parse((formData.get("instructions") as string) ?? "{}") as SwitchMiiInstructions);
function minify(object: Partial<SwitchMiiInstructions>): Partial<SwitchMiiInstructions> {
for (const key in object) {
const value = object[key as keyof SwitchMiiInstructions];
if (!value || (DEFAULT_ZERO_FIELDS.has(key) && value === 0)) {
delete object[key as keyof SwitchMiiInstructions];
continue;
}
if (typeof value === "object" && !Array.isArray(value)) {
minify(value as Partial<SwitchMiiInstructions>);
if (Object.keys(value).length === 0) {
delete object[key as keyof SwitchMiiInstructions];
}
}
}
return object;
}
minifiedInstructions = minify(JSON.parse((formData.get("instructions") as string) ?? "{}") as SwitchMiiInstructions);
}
// Parse and check all submission info // Parse and check all submission info
const parsed = submitSchema.safeParse({ const parsed = submitSchema.safeParse({
@ -129,6 +107,7 @@ export async function POST(request: NextRequest) {
gender: formData.get("gender") ?? undefined, // ZOD MOMENT gender: formData.get("gender") ?? undefined, // ZOD MOMENT
miiPortraitImage: formData.get("miiPortraitImage"), miiPortraitImage: formData.get("miiPortraitImage"),
miiFeaturesImage: formData.get("miiFeaturesImage"),
instructions: minifiedInstructions, instructions: minifiedInstructions,
qrBytesRaw: rawQrBytesRaw, qrBytesRaw: rawQrBytesRaw,
@ -159,6 +138,7 @@ export async function POST(request: NextRequest) {
qrBytesRaw, qrBytesRaw,
gender, gender,
miiPortraitImage, miiPortraitImage,
miiFeaturesImage,
image1, image1,
image2, image2,
image3, image3,
@ -183,10 +163,12 @@ export async function POST(request: NextRequest) {
} }
} }
// Check Mii portrait image as well (Switch) // Check Mii portrait & features image (Switch)
if (platform === "SWITCH") { if (platform === "SWITCH") {
const imageValidation = await validateImage(miiPortraitImage); const portraitValidation = await validateImage(miiPortraitImage);
if (!imageValidation.valid) return rateLimit.sendResponse({ error: imageValidation.error }, imageValidation.status ?? 400); const featuresValidation = await validateImage(miiFeaturesImage);
if (!portraitValidation.valid) return rateLimit.sendResponse({ error: portraitValidation.error }, portraitValidation.status ?? 400);
if (!featuresValidation.valid) return rateLimit.sendResponse({ error: featuresValidation.error }, featuresValidation.status ?? 400);
} }
const qrBytes = new Uint8Array(qrBytesRaw ?? []); const qrBytes = new Uint8Array(qrBytesRaw ?? []);
@ -246,8 +228,15 @@ export async function POST(request: NextRequest) {
portraitBuffer = Buffer.from(await studioResponse.arrayBuffer()); portraitBuffer = Buffer.from(await studioResponse.arrayBuffer());
} else if (platform === "SWITCH") { } else if (platform === "SWITCH") {
portraitBuffer = Buffer.from(await miiPortraitImage.arrayBuffer()); portraitBuffer = Buffer.from(await miiPortraitImage.arrayBuffer());
// Save features image
const featuresBuffer = Buffer.from(await miiFeaturesImage.arrayBuffer());
const pngBuffer = await sharp(featuresBuffer).png({ quality: 85 }).toBuffer();
const fileLocation = path.join(miiUploadsDirectory, "features.png");
await fs.writeFile(fileLocation, pngBuffer);
} }
// Save portrait image
if (!portraitBuffer) throw Error("Mii portrait buffer not initialised"); if (!portraitBuffer) throw Error("Mii portrait buffer not initialised");
const pngBuffer = await sharp(portraitBuffer).png({ quality: 85 }).toBuffer(); const pngBuffer = await sharp(portraitBuffer).png({ quality: 85 }).toBuffer();
const fileLocation = path.join(miiUploadsDirectory, "mii.png"); const fileLocation = path.join(miiUploadsDirectory, "mii.png");
@ -258,9 +247,9 @@ export async function POST(request: NextRequest) {
// Clean up if something went wrong // Clean up if something went wrong
await prisma.mii.delete({ where: { id: miiRecord.id } }); await prisma.mii.delete({ where: { id: miiRecord.id } });
console.error("Failed to download/store Mii portrait:", error); console.error("Failed to download/store Mii portrait/features:", error);
Sentry.captureException(error, { extra: { miiId: miiRecord.id, stage: "studio-image-download" } }); Sentry.captureException(error, { extra: { miiId: miiRecord.id, stage: "studio-image-download" } });
return rateLimit.sendResponse({ error: "Failed to download/store Mii portrait" }, 500); return rateLimit.sendResponse({ error: "Failed to download/store Mii portrait/features" }, 500);
} }
if (platform === "THREE_DS") { if (platform === "THREE_DS") {

View file

@ -126,7 +126,7 @@ input[type="range"] {
/* Track */ /* Track */
input[type="range"]::-webkit-slider-runnable-track { input[type="range"]::-webkit-slider-runnable-track {
@apply h-2 bg-orange-200 border-2 border-orange-400 rounded-full; @apply h-1 bg-orange-200 border-2 border-orange-400 rounded-full;
} }
input[type="range"]::-moz-range-track { input[type="range"]::-moz-range-track {

View file

@ -5,6 +5,7 @@ import { Lexend } from "next/font/google";
import { WebSite, WithContext } from "schema-dts"; import { WebSite, WithContext } from "schema-dts";
import "./globals.css"; import "./globals.css";
import "react-image-crop/dist/ReactCrop.css";
import Providers from "./provider"; import Providers from "./provider";
import Header from "@/components/header"; import Header from "@/components/header";

View file

@ -12,8 +12,8 @@ import { prisma } from "@/lib/prisma";
const searchParamsSchema = z.object({ const searchParamsSchema = z.object({
type: z type: z
.enum(["mii", "qr-code", "image0", "image1", "image2", "metadata"], { .enum(["mii", "qr-code", "features", "image0", "image1", "image2", "metadata"], {
message: "Image type must be either 'mii', 'qr-code', 'image[number from 0 to 2]' or 'metadata'", message: "Image type must be either 'mii', 'qr-code', 'features', 'image[number from 0 to 2]' or 'metadata'",
}) })
.default("mii"), .default("mii"),
}); });

View file

@ -135,7 +135,7 @@ export default async function MiiPage({ params }: Props) {
/> />
</div> </div>
{/* QR Code */} {/* QR Code */}
{mii.platform === "THREE_DS" && ( {mii.platform === "THREE_DS" ? (
<div className="bg-amber-200 overflow-hidden rounded-xl w-full mb-4 flex justify-center p-2"> <div className="bg-amber-200 overflow-hidden rounded-xl w-full mb-4 flex justify-center p-2">
<ImageViewer <ImageViewer
src={`/mii/${mii.id}/image?type=qr-code`} src={`/mii/${mii.id}/image?type=qr-code`}
@ -145,6 +145,14 @@ export default async function MiiPage({ params }: Props) {
className="border-2 border-amber-300 rounded-lg hover:brightness-90 transition-all" className="border-2 border-amber-300 rounded-lg hover:brightness-90 transition-all"
/> />
</div> </div>
) : (
<ImageViewer
src={`/mii/${mii.id}/image?type=features`}
alt="mii features"
width={300}
height={300}
className="rounded-lg hover:brightness-90 mb-4 transition-all"
/>
)} )}
<hr className="w-full border-t-2 border-t-amber-400" /> <hr className="w-full border-t-2 border-t-amber-400" />

View file

@ -113,7 +113,7 @@ function Section({ name, instructions, children, isSubSection }: SectionProps) {
export default function MiiInstructions({ instructions }: Props) { export default function MiiInstructions({ instructions }: Props) {
if (Object.keys(instructions).length === 0) return null; if (Object.keys(instructions).length === 0) return null;
const { head, hair, eyebrows, eyes, nose, lips, ears, glasses, other, height, weight, datingPreferences, voice, personality } = instructions; const { head, hair, eyebrows, eyes, nose, lips, ears, glasses, other, height, weight, birthday, datingPreferences, voice, personality } = instructions;
return ( return (
<div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex flex-col gap-3 max-h-96 overflow-y-auto"> <div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg p-4 flex flex-col gap-3 max-h-96 overflow-y-auto">
@ -122,7 +122,15 @@ export default function MiiInstructions({ instructions }: Props) {
Instructions Instructions
</h2> </h2>
{head && <Section name="Head" instructions={head}></Section>} {head && (
<Section name="Head" instructions={head}>
{head.skinColor && (
<TableCell label="Skin Color">
<ColorPosition color={head.skinColor} />
</TableCell>
)}
</Section>
)}
{hair && ( {hair && (
<Section name="Hair" instructions={hair}> <Section name="Hair" instructions={hair}>
{hair.subColor && ( {hair.subColor && (
@ -196,7 +204,10 @@ export default function MiiInstructions({ instructions }: Props) {
<label htmlFor="height" className="w-16"> <label htmlFor="height" className="w-16">
Height Height
</label> </label>
<input id="height" type="range" min={0} max={100} step={1} disabled value={height} /> <div className="relative h-5 flex justify-center items-center">
<input id="height" type="range" min={0} max={128} step={1} disabled value={height} />
<div className="absolute h-4 w-1.5 rounded bg-orange-400 z-0"></div>
</div>
</div> </div>
)} )}
{weight && ( {weight && (
@ -204,7 +215,23 @@ export default function MiiInstructions({ instructions }: Props) {
<label htmlFor="weight" className="w-16"> <label htmlFor="weight" className="w-16">
Weight Weight
</label> </label>
<input id="weight" type="range" min={0} max={100} step={1} disabled value={weight} /> <div className="relative h-5 flex justify-center items-center">
<input id="weight" type="range" min={0} max={128} step={1} disabled value={weight} />
<div className="absolute h-4 w-1.5 rounded bg-orange-400 z-0"></div>
</div>
</div>
)}
{birthday && (
<div className="pl-2 not-nth-2:mt-4">
<h4 className="font-semibold text-xl text-amber-800 mb-1">Birthday</h4>
<table className="w-full">
<tbody>
{birthday.day && <TableCell label="Day">{birthday.day}</TableCell>}
{birthday.month && <TableCell label="Month">{birthday.month}</TableCell>}
{birthday.age && <TableCell label="Age">{birthday.age}</TableCell>}
{birthday.dontAge && <TableCell label="Don't Age">{birthday.dontAge ? "Yes" : "No"}</TableCell>}
</tbody>
</table>
</div> </div>
)} )}
{datingPreferences && ( {datingPreferences && (

View file

@ -197,7 +197,7 @@ export default async function MiiList({ searchParams, userId, inLikesPage }: Pro
<Carousel <Carousel
images={[ images={[
`/mii/${mii.id}/image?type=mii`, `/mii/${mii.id}/image?type=mii`,
...(mii.platform === "THREE_DS" ? [`/mii/${mii.id}/image?type=qr-code`] : []), ...(mii.platform === "THREE_DS" ? [`/mii/${mii.id}/image?type=qr-code`] : [`/mii/${mii.id}/image?type=features`]),
...Array.from({ length: mii.imageCount }, (_, index) => `/mii/${mii.id}/image?type=image${index}`), ...Array.from({ length: mii.imageCount }, (_, index) => `/mii/${mii.id}/image?type=image${index}`),
]} ]}
/> />

View file

@ -15,23 +15,26 @@ export default function VoiceViewer({ data, onClick, onClickTone }: Props) {
return ( return (
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
{VOICE_SETTINGS.map((label) => ( {VOICE_SETTINGS.map((label) => (
<div key={label} className="flex gap-3"> <div key={label} className="relative flex gap-3">
<label htmlFor={label} className="text-sm w-14"> <label htmlFor={label} className="text-sm w-14">
{label} {label}
</label> </label>
<div className="relative h-5 flex justify-center items-center">
<input <input
type="range" type="range"
name={label} name={label}
className="grow" className="grow z-10"
min={0} min={0}
max={100} max={50}
step={1} step={1}
value={data[label as keyof typeof data] ?? 50} value={data[label as keyof typeof data] ?? 25}
disabled={!onClick} disabled={!onClick}
onChange={(e) => { onChange={(e) => {
if (onClick) onClick(e, label); if (onClick) onClick(e, label);
}} }}
/> />
<div className="absolute h-4 w-1.5 rounded bg-orange-400 z-0"></div>
</div>
</div> </div>
))} ))}

View file

@ -10,10 +10,11 @@ import { useSelect } from "downshift";
interface Props { interface Props {
isOpen: boolean; isOpen: boolean;
setIsOpen: React.Dispatch<React.SetStateAction<boolean>>; setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
setQrBytesRaw: React.Dispatch<React.SetStateAction<number[]>>; setImage?: React.Dispatch<React.SetStateAction<string | undefined>>;
setQrBytesRaw?: React.Dispatch<React.SetStateAction<number[]>>;
} }
export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) { export default function Camera({ isOpen, setIsOpen, setImage, setQrBytesRaw }: Props) {
const [isVisible, setIsVisible] = useState(false); const [isVisible, setIsVisible] = useState(false);
const [permissionGranted, setPermissionGranted] = useState<boolean | null>(null); const [permissionGranted, setPermissionGranted] = useState<boolean | null>(null);
@ -45,11 +46,11 @@ export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) {
}, },
}); });
const scanQRCode = useCallback(() => { const takePicture = useCallback(() => {
if (!isOpen) return; if (!isOpen) return;
// Continue scanning in a loop // Continue scanning in a loop
requestRef.current = requestAnimationFrame(scanQRCode); if (setQrBytesRaw) requestRef.current = requestAnimationFrame(takePicture);
const video = videoRef.current; const video = videoRef.current;
const canvas = canvasRef.current; const canvas = canvasRef.current;
@ -62,6 +63,13 @@ export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) {
canvas.height = video.videoHeight; canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
if (setImage) {
setImage(canvas.toDataURL());
close();
return;
}
if (!setQrBytesRaw) return;
const imageData = ctx.getImageData(0, 0, video.videoWidth, video.videoHeight); const imageData = ctx.getImageData(0, 0, video.videoWidth, video.videoHeight);
const code = jsQR(imageData.data, imageData.width, imageData.height); const code = jsQR(imageData.data, imageData.width, imageData.height);
if (!code || !code.binaryData) return; if (!code || !code.binaryData) return;
@ -73,7 +81,7 @@ export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) {
} }
setQrBytesRaw(code.binaryData); setQrBytesRaw(code.binaryData);
setIsOpen(false); close();
}, [isOpen, setIsOpen, setQrBytesRaw]); }, [isOpen, setIsOpen, setQrBytesRaw]);
const requestPermission = () => { const requestPermission = () => {
@ -129,7 +137,7 @@ export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) {
}) })
.catch((err) => console.error("Camera error", err)); .catch((err) => console.error("Camera error", err));
requestRef.current = requestAnimationFrame(scanQRCode); if (setQrBytesRaw) requestRef.current = requestAnimationFrame(takePicture);
// cleanup // cleanup
return () => { return () => {
@ -142,7 +150,7 @@ export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) {
videoRef.current.srcObject = null; videoRef.current.srcObject = null;
} }
}; };
}, [isOpen, permissionGranted, selectedDeviceId, scanQRCode]); }, [isOpen, permissionGranted, selectedDeviceId, takePicture]);
return ( return (
<div className={`fixed inset-0 h-[calc(100%-var(--header-height))] top-(--header-height) flex items-center justify-center z-40 ${!isOpen ? "hidden" : ""}`}> <div className={`fixed inset-0 h-[calc(100%-var(--header-height))] top-(--header-height) flex items-center justify-center z-40 ${!isOpen ? "hidden" : ""}`}>
@ -157,7 +165,7 @@ export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) {
}`} }`}
> >
<div className="flex justify-between items-center mb-2"> <div className="flex justify-between items-center mb-2">
<h2 className="text-xl font-bold">Scan QR Code</h2> <h2 className="text-xl font-bold">{setQrBytesRaw ? "Scan QR Code" : "Take Picture"}</h2>
<button type="button" aria-label="Close" onClick={close} className="text-red-400 hover:text-red-500 text-2xl cursor-pointer"> <button type="button" aria-label="Close" onClick={close} className="text-red-400 hover:text-red-500 text-2xl cursor-pointer">
<Icon icon="material-symbols:close-rounded" /> <Icon icon="material-symbols:close-rounded" />
</button> </button>
@ -199,26 +207,31 @@ export default function QrScanner({ isOpen, setIsOpen, setQrBytesRaw }: Props) {
</div> </div>
</div> </div>
<div className="relative w-full aspect-square"> <div className={`relative w-full ${setQrBytesRaw ? "aspect-square" : ""}`}>
{!permissionGranted && ( {!permissionGranted && (
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center rounded-2xl bg-amber-50 border-2 border-amber-500 text-center p-8"> <div className="absolute inset-0 z-20 flex flex-col items-center justify-center rounded-2xl bg-amber-50 border-2 border-amber-500 text-center p-8">
<p className="text-red-400 font-bold text-lg mb-2">Camera access denied</p> <p className="text-red-400 font-bold text-lg mb-2">Camera access denied</p>
<p className="text-gray-600">Please allow camera access in your browser settings to scan QR codes</p> <p className="text-gray-600">Please allow camera access in your browser settings to {setQrBytesRaw ? "scan QR codes" : "take pictures"}</p>
<button type="button" onClick={requestPermission} className="pill button text-xs mt-2 py-0.5! px-2!"> <button type="button" onClick={requestPermission} className="pill button text-xs mt-2 py-0.5! px-2!">
Request Permission Request Permission
</button> </button>
</div> </div>
)} )}
<video ref={videoRef} className="size-full object-cover rounded-2xl border-2 border-amber-500" /> <video ref={videoRef} className={`size-full rounded-2xl border-2 border-amber-500 max-h-96 ${setQrBytesRaw ? "object-cover" : ""}`} />
<QrFinder /> {setQrBytesRaw && <QrFinder />}
<canvas ref={canvasRef} className="hidden" /> <canvas ref={canvasRef} className="hidden" />
</div> </div>
<div className="mt-4 flex justify-center"> <div className="mt-4 flex justify-center gap-2">
<button type="button" onClick={close} className="pill button"> <button type="button" onClick={close} className="pill button">
Cancel Cancel
</button> </button>
{setImage && (
<button type="button" onClick={takePicture} className="pill button">
Take Picture
</button>
)}
</div> </div>
</div> </div>
</div> </div>

View file

@ -0,0 +1,95 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import ReactCrop, { Crop } from "react-image-crop";
import { Icon } from "@iconify/react";
interface Props {
isOpen: boolean;
setIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
image: string | undefined;
setImage: React.Dispatch<React.SetStateAction<string | undefined>>;
}
export default function CropPortrait({ isOpen, setIsOpen, image, setImage }: Props) {
const [isVisible, setIsVisible] = useState(false);
const [crop, setCrop] = useState<Crop>();
const imageRef = useRef<HTMLImageElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const applyCrop = useCallback(() => {
if (!imageRef.current || !canvasRef.current || !crop) return;
const image = imageRef.current;
const canvas = canvasRef.current;
if (!crop.width || !crop.height || image.naturalWidth === 0 || image.naturalHeight === 0) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width * scaleX;
canvas.height = crop.height * scaleY;
ctx.drawImage(image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width * scaleX, crop.height * scaleY);
setImage(canvas.toDataURL());
close();
}, [crop, setImage]);
const close = () => {
setIsVisible(false);
setTimeout(() => {
setIsOpen(false);
}, 300);
};
useEffect(() => {
if (isOpen) {
// slight delay to trigger animation
setTimeout(() => setIsVisible(true), 10);
}
}, [isOpen]);
return (
<div className={`fixed inset-0 h-[calc(100%-var(--header-height))] top-(--header-height) flex items-center justify-center z-40 ${!isOpen ? "hidden" : ""}`}>
<div
onClick={close}
className={`z-40 absolute inset-0 backdrop-brightness-75 backdrop-blur-xs transition-opacity duration-300 ${isVisible ? "opacity-100" : "opacity-0"}`}
/>
<div
className={`z-50 bg-orange-50 border-2 border-amber-500 rounded-2xl shadow-lg p-6 w-full max-w-md transition-discrete duration-300 ${
isVisible ? "scale-100 opacity-100" : "scale-75 opacity-0"
}`}
>
<div className="flex justify-between items-center mb-2">
<h2 className="text-xl font-bold">Crop Portrait</h2>
<button type="button" aria-label="Close" onClick={close} className="text-red-400 hover:text-red-500 text-2xl cursor-pointer">
<Icon icon="material-symbols:close-rounded" />
</button>
</div>
<div className="relative w-full flex justify-center">
<ReactCrop crop={crop} onChange={(c) => setCrop(c)} className="rounded-2xl border-2 border-amber-500 overflow-hidden max-h-96">
<img ref={imageRef} src={image} />
</ReactCrop>
<canvas ref={canvasRef} className="hidden" />
</div>
<div className="mt-4 flex justify-center gap-2">
<button type="button" onClick={close} className="pill button">
Cancel
</button>
<button type="button" onClick={applyCrop} className="pill button">
Crop
</button>
</div>
</div>
</div>
);
}

View file

@ -7,6 +7,8 @@ import { FileWithPath } from "react-dropzone";
import { Mii } from "@prisma/client"; import { Mii } from "@prisma/client";
import { nameSchema, tagsSchema } from "@/lib/schemas"; import { nameSchema, tagsSchema } from "@/lib/schemas";
import { defaultInstructions, minifyInstructions } from "@/lib/switch";
import { SwitchMiiInstructions } from "@/types";
import TagSelector from "../tag-selector"; import TagSelector from "../tag-selector";
import ImageList from "./image-list"; import ImageList from "./image-list";
@ -14,6 +16,8 @@ import LikeButton from "../like-button";
import Carousel from "../carousel"; import Carousel from "../carousel";
import SubmitButton from "../submit-button"; import SubmitButton from "../submit-button";
import Dropzone from "../dropzone"; import Dropzone from "../dropzone";
import MiiEditor from "./mii-editor";
import SwitchSubmitTutorialButton from "../tutorial/switch-submit";
interface Props { interface Props {
mii: Mii; mii: Mii;
@ -40,6 +44,8 @@ export default function EditForm({ mii, likes }: Props) {
const [description, setDescription] = useState(mii.description); const [description, setDescription] = useState(mii.description);
const hasFilesChanged = useRef(false); const hasFilesChanged = useRef(false);
const instructions = useRef<SwitchMiiInstructions>({ ...defaultInstructions, ...(mii.instructions as object as Partial<SwitchMiiInstructions>) });
const handleSubmit = async () => { const handleSubmit = async () => {
// Validate before sending request // Validate before sending request
const nameValidation = nameSchema.safeParse(name); const nameValidation = nameSchema.safeParse(name);
@ -58,6 +64,10 @@ export default function EditForm({ mii, likes }: Props) {
if (name != mii.name) formData.append("name", name); if (name != mii.name) formData.append("name", name);
if (tags != mii.tags) formData.append("tags", JSON.stringify(tags)); if (tags != mii.tags) formData.append("tags", JSON.stringify(tags));
if (description && description != mii.description) formData.append("description", description); if (description && description != mii.description) formData.append("description", description);
console.log(minifyInstructions(structuredClone(instructions.current)));
console.log(mii.instructions);
if (minifyInstructions(structuredClone(instructions.current)) !== (mii.instructions as object))
formData.append("instructions", JSON.stringify(instructions.current));
if (hasFilesChanged.current) { if (hasFilesChanged.current) {
files.forEach((file, index) => { files.forEach((file, index) => {
@ -179,8 +189,22 @@ export default function EditForm({ mii, likes }: Props) {
/> />
</div> </div>
{/* Instructions (Switch only) */}
{mii.platform === "SWITCH" && (
<>
<div className="flex items-center gap-4 text-zinc-500 text-sm font-medium mt-8">
<hr className="grow border-zinc-300" />
<span>Instructions</span>
<hr className="grow border-zinc-300" />
</div>
<MiiEditor instructions={instructions} />
<SwitchSubmitTutorialButton />
</>
)}
{/* Separator */} {/* Separator */}
<div className="flex items-center gap-4 text-zinc-500 text-sm font-medium mt-8 mb-2"> <div className="flex items-center gap-4 text-zinc-500 text-sm font-medium mt-8">
<hr className="grow border-zinc-300" /> <hr className="grow border-zinc-300" />
<span>Custom images</span> <span>Custom images</span>
<hr className="grow border-zinc-300" /> <hr className="grow border-zinc-300" />

View file

@ -13,13 +13,14 @@ import { nameSchema, tagsSchema } from "@/lib/schemas";
import { convertQrCode } from "@/lib/qr-codes"; import { convertQrCode } from "@/lib/qr-codes";
import Mii from "@/lib/mii.js/mii"; import Mii from "@/lib/mii.js/mii";
import { ThreeDsTomodachiLifeMii } from "@/lib/three-ds-tomodachi-life-mii"; import { ThreeDsTomodachiLifeMii } from "@/lib/three-ds-tomodachi-life-mii";
import { defaultInstructions } from "@/lib/switch";
import { SwitchMiiInstructions } from "@/types"; import { SwitchMiiInstructions } from "@/types";
import TagSelector from "../tag-selector"; import TagSelector from "../tag-selector";
import ImageList from "./image-list"; import ImageList from "./image-list";
import PortraitUpload from "./portrait-upload"; import SwitchFileUpload from "./switch-file-upload";
import QrUpload from "./qr-upload"; import QrUpload from "./qr-upload";
import QrScanner from "./qr-scanner"; import Camera from "./camera";
import ThreeDsSubmitTutorialButton from "../tutorial/3ds-submit"; import ThreeDsSubmitTutorialButton from "../tutorial/3ds-submit";
import MiiEditor from "./mii-editor"; import MiiEditor from "./mii-editor";
import SwitchSubmitTutorialButton from "../tutorial/switch-submit"; import SwitchSubmitTutorialButton from "../tutorial/switch-submit";
@ -41,6 +42,7 @@ export default function SubmitForm() {
const [isQrScannerOpen, setIsQrScannerOpen] = useState(false); const [isQrScannerOpen, setIsQrScannerOpen] = useState(false);
const [miiPortraitUri, setMiiPortraitUri] = useState<string | undefined>(); const [miiPortraitUri, setMiiPortraitUri] = useState<string | undefined>();
const [miiFeaturesUri, setMiiFeaturesUri] = useState<string | undefined>();
const [generatedQrCodeUri, setGeneratedQrCodeUri] = useState<string | undefined>(); const [generatedQrCodeUri, setGeneratedQrCodeUri] = useState<string | undefined>();
const [name, setName] = useState(""); const [name, setName] = useState("");
@ -50,45 +52,7 @@ export default function SubmitForm() {
const [platform, setPlatform] = useState<MiiPlatform>("SWITCH"); const [platform, setPlatform] = useState<MiiPlatform>("SWITCH");
const [gender, setGender] = useState<MiiGender>("MALE"); const [gender, setGender] = useState<MiiGender>("MALE");
const instructions = useRef<SwitchMiiInstructions>({ const instructions = useRef<SwitchMiiInstructions>(defaultInstructions);
head: { skinColor: null },
hair: {
color: null,
subColor: null,
subColor2: null,
style: null,
isFlipped: false,
},
eyebrows: { color: null, height: null, distance: null, rotation: null, size: null, stretch: null },
eyes: {
main: { color: null, height: null, distance: null, rotation: null, size: null, stretch: null },
eyelashesTop: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyelashesBottom: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyelidTop: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyelidBottom: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyeliner: { color: null },
pupil: { height: null, distance: null, rotation: null, size: null, stretch: null },
},
nose: { height: null, size: null },
lips: { color: null, height: null, rotation: null, size: null, stretch: null, hasLipstick: false },
ears: { height: null, size: null },
glasses: { ringColor: null, shadesColor: null, height: null, size: null, stretch: null },
other: {
wrinkles1: { height: null, distance: null, size: null, stretch: null },
wrinkles2: { height: null, distance: null, size: null, stretch: null },
beard: { color: null },
moustache: { color: null, height: null, isFlipped: false, size: null, stretch: null },
goatee: { color: null },
mole: { color: null, height: null, distance: null, size: null },
eyeShadow: { color: null, height: null, distance: null, size: null, stretch: null },
blush: { color: null, height: null, distance: null, size: null, stretch: null },
},
height: null,
weight: null,
datingPreferences: [],
voice: { speed: null, pitch: null, depth: null, delivery: null, tone: null },
personality: { movement: null, speech: null, energy: null, thinking: null, overall: null },
});
const [error, setError] = useState<string | undefined>(undefined); const [error, setError] = useState<string | undefined>(undefined);
@ -119,21 +83,24 @@ export default function SubmitForm() {
if (platform === "THREE_DS") { if (platform === "THREE_DS") {
formData.append("qrBytesRaw", JSON.stringify(qrBytesRaw)); formData.append("qrBytesRaw", JSON.stringify(qrBytesRaw));
} else if (platform === "SWITCH") { } else if (platform === "SWITCH") {
const response = await fetch(miiPortraitUri!); const portraitResponse = await fetch(miiPortraitUri!);
const featuresResponse = await fetch(miiFeaturesUri!);
if (!response.ok) { if (!portraitResponse.ok || !featuresResponse.ok) {
setError("Failed to check Mii portrait. Did you upload one?"); setError("Failed to get Mii portrait/features screenshot. Did you upload one?");
return; return;
} }
const blob = await response.blob(); const portraitBlob = await portraitResponse.blob();
if (!blob.type.startsWith("image/")) { const featuresBlob = await featuresResponse.blob();
setError("Invalid image file returned"); if (!portraitBlob.type.startsWith("image/") || !featuresBlob.type.startsWith("image/")) {
setError("Invalid image file found");
return; return;
} }
formData.append("gender", gender); formData.append("gender", gender);
formData.append("miiPortraitImage", blob); formData.append("miiPortraitImage", portraitBlob);
formData.append("miiFeaturesImage", featuresBlob);
formData.append("instructions", JSON.stringify(instructions.current)); formData.append("instructions", JSON.stringify(instructions.current));
} }
@ -197,7 +164,7 @@ export default function SubmitForm() {
<Carousel <Carousel
images={[ images={[
miiPortraitUri ?? "/loading.svg", miiPortraitUri ?? "/loading.svg",
...(platform === "THREE_DS" ? [generatedQrCodeUri ?? "/loading.svg"] : []), ...(platform === "THREE_DS" ? [generatedQrCodeUri ?? "/loading.svg"] : [miiFeaturesUri ?? "/loading.svg"]),
...files.map((file) => URL.createObjectURL(file)), ...files.map((file) => URL.createObjectURL(file)),
]} ]}
/> />
@ -369,7 +336,8 @@ export default function SubmitForm() {
</div> </div>
<div className="flex flex-col items-center gap-2"> <div className="flex flex-col items-center gap-2">
<PortraitUpload setImage={setMiiPortraitUri} /> <SwitchFileUpload text="a screenshot of your Mii here" image={miiPortraitUri} setImage={setMiiPortraitUri} hasCrop />
<SwitchFileUpload text="a screenshot of your Mii's features here" setImage={setMiiFeaturesUri} />
<SwitchSubmitTutorialButton /> <SwitchSubmitTutorialButton />
</div> </div>
@ -393,7 +361,7 @@ export default function SubmitForm() {
Use your camera Use your camera
</button> </button>
<QrScanner isOpen={isQrScannerOpen} setIsOpen={setIsQrScannerOpen} setQrBytesRaw={setQrBytesRaw} /> <Camera isOpen={isQrScannerOpen} setIsOpen={setIsQrScannerOpen} setQrBytesRaw={setQrBytesRaw} />
<ThreeDsSubmitTutorialButton /> <ThreeDsSubmitTutorialButton />
<span className="text-xs text-zinc-400">For emulators, aes_keys.txt is required.</span> <span className="text-xs text-zinc-400">For emulators, aes_keys.txt is required.</span>

View file

@ -8,7 +8,7 @@ interface Props {
} }
export default function EyebrowsTab({ instructions }: Props) { export default function EyebrowsTab({ instructions }: Props) {
const [color, setColor] = useState(3); const [color, setColor] = useState(instructions.current.eyebrows.color ?? 3);
return ( return (
<> <>

View file

@ -19,9 +19,13 @@ const TABS: { name: keyof SwitchMiiInstructions["eyes"]; length: number; colorsD
export default function EyesTab({ instructions }: Props) { export default function EyesTab({ instructions }: Props) {
const [tab, setTab] = useState(0); const [tab, setTab] = useState(0);
const [colors, setColors] = useState<number[]>(() =>
// One type/color state per tab TABS.map((t) => {
const [colors, setColors] = useState<number[]>(Array(TABS.length).fill(122)); const entry = instructions.current.eyes[t.name];
const color = "color" in entry ? entry.color : null;
return color ?? 122;
}),
);
const currentTab = TABS[tab]; const currentTab = TABS[tab];

View file

@ -8,8 +8,8 @@ interface Props {
} }
export default function GlassesTab({ instructions }: Props) { export default function GlassesTab({ instructions }: Props) {
const [ringColor, setRingColor] = useState(133); const [ringColor, setRingColor] = useState(instructions.current.glasses.ringColor ?? 133);
const [shadesColor, setShadesColor] = useState(133); const [shadesColor, setShadesColor] = useState(instructions.current.glasses.shadesColor ?? 133);
return ( return (
<> <>

View file

@ -10,11 +10,11 @@ type Tab = "sets" | "bangs" | "back";
export default function HairTab({ instructions }: Props) { export default function HairTab({ instructions }: Props) {
const [tab, setTab] = useState<Tab>("sets"); const [tab, setTab] = useState<Tab>("sets");
const [color, setColor] = useState(3); const [color, setColor] = useState(instructions.current.hair.color ?? 3);
const [subColor, setSubColor] = useState<number | null>(null); const [subColor, setSubColor] = useState<number | null>(instructions.current.hair.subColor);
const [subColor2, setSubColor2] = useState<number | null>(null); const [subColor2, setSubColor2] = useState<number | null>(instructions.current.hair.subColor2);
const [style, setStyle] = useState<number | null>(null); const [style, setStyle] = useState<number | null>(instructions.current.hair.style);
const [isFlipped, setIsFlipped] = useState(false); const [isFlipped, setIsFlipped] = useState(instructions.current.hair.isFlipped);
return ( return (
<> <>

View file

@ -9,7 +9,7 @@ interface Props {
const COLORS = ["FFD8BA", "FFD5AC", "FEC1A4", "FEC68F", "FEB089", "FEBA6B", "F39866", "E89854", "E37E3F", "B45627", "914220", "59371F", "662D16", "392D1E"]; const COLORS = ["FFD8BA", "FFD5AC", "FEC1A4", "FEC68F", "FEB089", "FEBA6B", "F39866", "E89854", "E37E3F", "B45627", "914220", "59371F", "662D16", "392D1E"];
export default function HeadTab({ instructions }: Props) { export default function HeadTab({ instructions }: Props) {
const [color, setColor] = useState(109); const [color, setColor] = useState(instructions.current.head.skinColor ?? 109);
return ( return (
<> <>
@ -29,7 +29,10 @@ export default function HeadTab({ instructions }: Props) {
<button <button
type="button" type="button"
key={i + 108} key={i + 108}
onClick={() => setColor(i + 108)} onClick={() => {
setColor(i + 108);
instructions.current.head.skinColor = i + 108;
}}
className={`size-9 rounded-lg cursor-pointer ring-offset-2 ring-orange-500 ${color === i + 108 ? "ring-2" : ""}`} className={`size-9 rounded-lg cursor-pointer ring-offset-2 ring-orange-500 ${color === i + 108 ? "ring-2" : ""}`}
style={{ backgroundColor: `#${hex}` }} style={{ backgroundColor: `#${hex}` }}
></button> ></button>

View file

@ -8,8 +8,8 @@ interface Props {
} }
export default function LipsTab({ instructions }: Props) { export default function LipsTab({ instructions }: Props) {
const [color, setColor] = useState(128); const [color, setColor] = useState(instructions.current.lips.color ?? 128);
const [hasLipstick, setHasLipstick] = useState(false); const [hasLipstick, setHasLipstick] = useState(instructions.current.lips.hasLipstick);
return ( return (
<> <>

View file

@ -12,22 +12,28 @@ interface Props {
} }
export default function HeadTab({ instructions }: Props) { export default function HeadTab({ instructions }: Props) {
const [height, setHeight] = useState(50); const [height, setHeight] = useState(instructions.current.height ?? 64);
const [weight, setWeight] = useState(50); const [weight, setWeight] = useState(instructions.current.weight ?? 64);
const [datingPreferences, setDatingPreferences] = useState<MiiGender[]>([]); const [datingPreferences, setDatingPreferences] = useState<MiiGender[]>(instructions.current.datingPreferences ?? []);
const [voice, setVoice] = useState({ const [voice, setVoice] = useState({
speed: 50, speed: instructions.current.voice.speed ?? 25,
pitch: 50, pitch: instructions.current.voice.pitch ?? 25,
depth: 50, depth: instructions.current.voice.depth ?? 25,
delivery: 50, delivery: instructions.current.voice.delivery ?? 25,
tone: 0, tone: instructions.current.voice.tone ?? 0,
});
const [birthday, setBirthday] = useState({
day: instructions.current.birthday.day ?? (null as number | null),
month: instructions.current.birthday.month ?? (null as number | null),
age: instructions.current.birthday.age ?? (null as number | null),
dontAge: instructions.current.birthday.dontAge,
}); });
const [personality, setPersonality] = useState({ const [personality, setPersonality] = useState({
movement: -1, movement: instructions.current.personality.movement ?? -1,
speech: -1, speech: instructions.current.personality.speech ?? -1,
energy: -1, energy: instructions.current.personality.energy ?? -1,
thinking: -1, thinking: instructions.current.personality.thinking ?? -1,
overall: -1, overall: instructions.current.personality.overall ?? -1,
}); });
return ( return (
@ -47,11 +53,13 @@ export default function HeadTab({ instructions }: Props) {
<label htmlFor="height" className="text-sm"> <label htmlFor="height" className="text-sm">
Height Height
</label> </label>
<div className="relative h-5 flex justify-center items-center">
<input <input
type="range" type="range"
id="height" id="height"
className="grow z-10"
min={0} min={0}
max={100} max={128}
step={1} step={1}
value={height} value={height}
onChange={(e) => { onChange={(e) => {
@ -59,17 +67,21 @@ export default function HeadTab({ instructions }: Props) {
instructions.current.height = e.target.valueAsNumber; instructions.current.height = e.target.valueAsNumber;
}} }}
/> />
<div className="absolute h-4 w-1.5 rounded bg-orange-400 z-0"></div>
</div>
</div> </div>
<div className="flex flex-col"> <div className="flex flex-col">
<label htmlFor="weight" className="text-sm"> <label htmlFor="weight" className="text-sm">
Weight Weight
</label> </label>
<div className="relative h-5 flex justify-center items-center">
<input <input
type="range" type="range"
id="weight" id="weight"
className="grow z-10"
min={0} min={0}
max={100} max={128}
step={1} step={1}
value={weight} value={weight}
onChange={(e) => { onChange={(e) => {
@ -77,6 +89,8 @@ export default function HeadTab({ instructions }: Props) {
instructions.current.weight = e.target.valueAsNumber; instructions.current.weight = e.target.valueAsNumber;
}} }}
/> />
<div className="absolute h-4 w-1.5 rounded bg-orange-400 z-0"></div>
</div>
</div> </div>
<div className="flex items-center gap-4 text-zinc-500 text-sm font-medium mt-1.5 mb-2"> <div className="flex items-center gap-4 text-zinc-500 text-sm font-medium mt-1.5 mb-2">
@ -117,6 +131,81 @@ export default function HeadTab({ instructions }: Props) {
instructions.current.voice.tone = i; instructions.current.voice.tone = i;
}} }}
/> />
<div className="flex items-center gap-4 text-zinc-500 text-sm font-medium mt-1.5 mb-2">
<hr className="grow border-zinc-300" />
<span>Birthday</span>
<hr className="grow border-zinc-300" />
</div>
<div className="grid grid-cols-3 gap-2">
<div>
<label htmlFor="day" className="text-xs">
Day
</label>
<input
type="number"
id="day"
min={1}
max={31}
className="pill input text-sm py-1! px-3! w-full"
value={birthday.day ?? undefined}
onChange={(e) => {
setBirthday((p) => ({ ...p, day: e.target.valueAsNumber }));
instructions.current.birthday.day = e.target.valueAsNumber;
}}
/>
</div>
<div>
<label htmlFor="month" className="text-xs">
Month
</label>
<input
type="number"
id="month"
min={1}
max={12}
className="pill input text-sm py-1! px-3! w-full"
value={birthday.month ?? undefined}
onChange={(e) => {
setBirthday((p) => ({ ...p, month: e.target.valueAsNumber }));
instructions.current.birthday.month = e.target.valueAsNumber;
}}
/>
</div>
<div>
<label htmlFor="age" className="text-xs">
Age
</label>
<input
type="number"
id="age"
min={1}
max={100}
className="pill input text-sm py-1! px-3! w-full"
value={birthday.age ?? undefined}
onChange={(e) => {
setBirthday((p) => ({ ...p, age: e.target.valueAsNumber }));
instructions.current.birthday.age = e.target.valueAsNumber;
}}
/>
</div>
<div className="flex gap-1.5 col-span-2">
<input
type="checkbox"
id="dontAge"
className="checkbox"
checked={birthday.dontAge}
onChange={(e) => {
setBirthday((p) => ({ ...p, dontAge: e.target.checked }));
instructions.current.birthday.dontAge = e.target.checked;
}}
/>
<label htmlFor="dontAge" className="text-sm select-none">
Don't Age
</label>
</div>
</div>
</div> </div>
</div> </div>

View file

@ -7,14 +7,14 @@ interface Props {
instructions: React.RefObject<SwitchMiiInstructions>; instructions: React.RefObject<SwitchMiiInstructions>;
} }
const TABS: { name: keyof SwitchMiiInstructions["other"]; length: number }[] = [ const TABS: { name: keyof SwitchMiiInstructions["other"]; length: number; defaultColor?: number }[] = [
{ name: "wrinkles1", length: 9 }, { name: "wrinkles1", length: 9 },
{ name: "wrinkles2", length: 15 }, { name: "wrinkles2", length: 15 },
{ name: "beard", length: 15 }, { name: "beard", length: 15 },
{ name: "moustache", length: 16 }, { name: "moustache", length: 16 },
{ name: "goatee", length: 14 }, { name: "goatee", length: 14 },
{ name: "mole", length: 2 }, { name: "mole", length: 2 },
{ name: "eyeShadow", length: 4 }, { name: "eyeShadow", length: 4, defaultColor: 139 },
{ name: "blush", length: 8 }, { name: "blush", length: 8 },
]; ];
@ -22,8 +22,13 @@ export default function OtherTab({ instructions }: Props) {
const [tab, setTab] = useState(0); const [tab, setTab] = useState(0);
const [isFlipped, setIsFlipped] = useState(false); const [isFlipped, setIsFlipped] = useState(false);
// One type/color state per tab const [colors, setColors] = useState<number[]>(() =>
const [colors, setColors] = useState<number[]>([0, 0, 0, 0, 0, 0, 139, 0]); TABS.map((t) => {
const entry = instructions.current.other[t.name];
const color = "color" in entry ? entry.color : null;
return color ?? t.defaultColor ?? 0;
}),
);
const currentTab = TABS[tab]; const currentTab = TABS[tab];

View file

@ -1,45 +0,0 @@
"use client";
import { useCallback, useState } from "react";
import { FileWithPath } from "react-dropzone";
import Dropzone from "../dropzone";
interface Props {
setImage: React.Dispatch<React.SetStateAction<string | undefined>>;
}
export default function PortraitUpload({ setImage }: Props) {
const [hasImage, setHasImage] = useState(false);
const handleDrop = useCallback(
(acceptedFiles: FileWithPath[]) => {
const file = acceptedFiles[0];
// Convert to Data URI
const reader = new FileReader();
reader.onload = async (event) => {
setImage(event.target!.result as string);
setHasImage(true);
};
reader.readAsDataURL(file);
},
[setImage],
);
return (
<div className="max-w-md w-full">
<Dropzone onDrop={handleDrop} options={{ maxFiles: 1 }}>
<p className="text-center text-sm">
{!hasImage ? (
<>
Drag and drop a screenshot of your Mii&apos;s features here
<br />
or click to open
</>
) : (
"Uploaded!"
)}
</p>
</Dropzone>
</div>
);
}

View file

@ -0,0 +1,77 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { FileWithPath } from "react-dropzone";
import { Icon } from "@iconify/react";
import Dropzone from "../dropzone";
import Camera from "./camera";
import CropPortrait from "./crop-portrait";
interface Props {
text: string;
hasCrop?: boolean;
image?: string | undefined;
setImage: React.Dispatch<React.SetStateAction<string | undefined>>;
}
export default function SwitchFileUpload({ text, hasCrop = false, image, setImage }: Props) {
const [isCameraOpen, setIsCameraOpen] = useState(false);
const [isCropOpen, setIsCropOpen] = useState(false);
const [hasImage, setHasImage] = useState(false);
const handleDrop = useCallback(
(acceptedFiles: FileWithPath[]) => {
const file = acceptedFiles[0];
// Convert to Data URI
const reader = new FileReader();
reader.onload = async (event) => {
setImage(event.target!.result as string);
setHasImage(true);
if (hasCrop) setIsCropOpen(true);
};
reader.readAsDataURL(file);
},
[setImage],
);
useEffect(() => {
if (!isCameraOpen) return;
if (hasCrop) setIsCropOpen(true);
}, [isCameraOpen]);
return (
<div className="max-w-md w-full flex flex-col items-center gap-2">
<Dropzone onDrop={handleDrop} options={{ maxFiles: 1 }}>
<p className="text-center text-sm">
{!hasImage ? (
<>
Drag and drop {text}
<br />
or click to open
</>
) : (
"Uploaded!"
)}
</p>
</Dropzone>
<span>or</span>
<button type="button" aria-label="Use your camera" onClick={() => setIsCameraOpen(true)} className="pill button gap-2">
<Icon icon="mdi:camera" fontSize={20} />
Use your camera
</button>
{hasCrop && (
<>
<button type="button" aria-label="Crop image" onClick={() => setIsCropOpen(true)} className="pill button gap-2">
<Icon icon="material-symbols:crop" fontSize={20} />
Crop Image
</button>
<CropPortrait isOpen={isCropOpen} setIsOpen={setIsCropOpen} image={image} setImage={setImage} />
</>
)}
<Camera isOpen={isCameraOpen} setIsOpen={setIsCameraOpen} setImage={setImage} />
</div>
);
}

View file

@ -27,15 +27,19 @@ export default function SwitchAddMiiTutorialButton() {
imageSrc: "/tutorial/switch/adding-mii/step1.jpg", imageSrc: "/tutorial/switch/adding-mii/step1.jpg",
}, },
{ {
text: "2. Press 'From scratch' and choose the Male template (instructions may be slightly inaccurate if you select Female)", text: "2. Press 'From scratch' and choose the Male template",
imageSrc: "/tutorial/switch/adding-mii/step2.jpg", imageSrc: "/tutorial/switch/adding-mii/step2.jpg",
}, },
{ {
text: "3. Follow all instructions (not all instructions will be there, check next slide for more)", text: "3. Click on the features image on this page to zoom it in and add all features on the mii editor",
imageSrc: "/tutorial/switch/adding-mii/step3.jpg", imageSrc: "/tutorial/switch/adding-mii/step3.png",
}, },
{ {
text: "4. If the instructions have height, distance, etc. the value will be relative to how many times to click the button - positive for up/left, negative for down/right", text: "4. If the author added instructions, follow them (not all instructions will be there, check next slide for more)",
imageSrc: "/tutorial/switch/adding-mii/step4.jpg",
},
{
text: "5. For instructions like height or distance, use the number of button clicks (positive for buttons on right, negative for buttons on left)",
imageSrc: "/tutorial/switch/step4.jpg", imageSrc: "/tutorial/switch/step4.jpg",
}, },
{ type: "finish" }, { type: "finish" },

View file

@ -4,7 +4,7 @@ import { useState } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import Tutorial from "."; import Tutorial from ".";
export default function SubmitTutorialButton() { export default function SwitchSubmitTutorialButton() {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
return ( return (

View file

@ -279,15 +279,23 @@ export const switchMiiInstructionsSchema = z
.optional(), .optional(),
}) })
.optional(), .optional(),
height: z.number().int().min(0).max(100).optional(), height: z.number().int().min(0).max(128).optional(),
weight: z.number().int().min(0).max(100).optional(), weight: z.number().int().min(0).max(128).optional(),
datingPreferences: z.array(z.enum(MiiGender)).optional(), datingPreferences: z.array(z.enum(MiiGender)).optional(),
birthday: z
.object({
day: z.number().int().min(1).max(31).optional(),
month: z.number().int().min(1).max(12).optional(),
age: z.number().int().min(1).max(100).optional(),
dontAge: z.boolean().optional(),
})
.optional(),
voice: z voice: z
.object({ .object({
speed: z.number().int().min(0).max(100).optional(), speed: z.number().int().min(0).max(50).optional(),
pitch: z.number().int().min(0).max(100).optional(), pitch: z.number().int().min(0).max(50).optional(),
depth: z.number().int().min(0).max(100).optional(), depth: z.number().int().min(0).max(50).optional(),
delivery: z.number().int().min(0).max(100).optional(), delivery: z.number().int().min(0).max(50).optional(),
tone: z.number().int().min(1).max(6).optional(), tone: z.number().int().min(1).max(6).optional(),
}) })
.optional(), .optional(),

View file

@ -1,3 +1,78 @@
import { SwitchMiiInstructions } from "@/types";
export function minifyInstructions(instructions: Partial<SwitchMiiInstructions>) {
const DEFAULT_ZERO_FIELDS = new Set(["height", "distance", "rotation", "size", "stretch"]);
function minify(object: Partial<SwitchMiiInstructions>): Partial<SwitchMiiInstructions> {
for (const key in object) {
const value = object[key as keyof SwitchMiiInstructions];
if (!value || (DEFAULT_ZERO_FIELDS.has(key) && value === 0)) {
delete object[key as keyof SwitchMiiInstructions];
continue;
}
if (typeof value === "object" && !Array.isArray(value)) {
minify(value as Partial<SwitchMiiInstructions>);
if (Object.keys(value).length === 0) {
delete object[key as keyof SwitchMiiInstructions];
}
}
}
return object;
}
return minify(instructions);
}
export const defaultInstructions: SwitchMiiInstructions = {
head: { skinColor: null },
hair: {
color: null,
subColor: null,
subColor2: null,
style: null,
isFlipped: false,
},
eyebrows: { color: null, height: null, distance: null, rotation: null, size: null, stretch: null },
eyes: {
main: { color: null, height: null, distance: null, rotation: null, size: null, stretch: null },
eyelashesTop: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyelashesBottom: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyelidTop: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyelidBottom: { height: null, distance: null, rotation: null, size: null, stretch: null },
eyeliner: { color: null },
pupil: { height: null, distance: null, rotation: null, size: null, stretch: null },
},
nose: { height: null, size: null },
lips: { color: null, height: null, rotation: null, size: null, stretch: null, hasLipstick: false },
ears: { height: null, size: null },
glasses: { ringColor: null, shadesColor: null, height: null, size: null, stretch: null },
other: {
wrinkles1: { height: null, distance: null, size: null, stretch: null },
wrinkles2: { height: null, distance: null, size: null, stretch: null },
beard: { color: null },
moustache: { color: null, height: null, isFlipped: false, size: null, stretch: null },
goatee: { color: null },
mole: { color: null, height: null, distance: null, size: null },
eyeShadow: { color: null, height: null, distance: null, size: null, stretch: null },
blush: { color: null, height: null, distance: null, size: null, stretch: null },
},
height: null,
weight: null,
datingPreferences: [],
birthday: {
day: null,
month: null,
age: null,
dontAge: false,
},
voice: { speed: null, pitch: null, depth: null, delivery: null, tone: null },
personality: { movement: null, speech: null, energy: null, thinking: null, overall: null },
};
export const COLORS: string[] = [ export const COLORS: string[] = [
// Outside // Outside
"000000", "000000",

6
src/types.d.ts vendored
View file

@ -143,6 +143,12 @@ interface SwitchMiiInstructions {
height: number | null; height: number | null;
weight: number | null; weight: number | null;
datingPreferences: MiiGender[]; datingPreferences: MiiGender[];
birthday: {
day: number | null;
month: number | null;
age: number | null; // TODO: update accordingly with mii creation date
dontAge: boolean;
};
voice: { voice: {
speed: number | null; speed: number | null;
pitch: number | null; pitch: number | null;