Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Form Validation & Fix GitHub Input #1089

Merged
merged 3 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
"tailwind-scrollbar-hide": "1.1.7",
"tailwindcss": "^3.3.5",
"unist-util-visit": "^5.0.0",
"webpack-merge": "5.8.0"
"webpack-merge": "5.8.0",
"zod": "^3.24.1"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^3.6.3",
Expand Down
85 changes: 76 additions & 9 deletions src/components/ProfileModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTrophy } from '@fortawesome/free-solid-svg-icons';
import { useChallenges } from '../hooks/use-challenges';
import * as fcl from '@onflow/fcl';
import { z } from 'zod';

interface ProfileModalProps {
isOpen: boolean;
Expand All @@ -29,6 +30,13 @@ const flowSources = [
{ name: 'Other', description: 'Another way not listed above.' },
];

const ProfileSettingsSchema = z.object({
handle: z.string().nonempty('Username is required'),
socials: z.record(z.string().nonempty()),
referralSource: z.string().nonempty().optional(),
deployedContracts: z.record(z.string().nonempty()),
});

const ProfileModal: React.FC<ProfileModalProps> = ({ isOpen, onClose }) => {
const { challenges } = useChallenges();
const { user } = useCurrentUser();
Expand All @@ -38,16 +46,44 @@ const ProfileModal: React.FC<ProfileModalProps> = ({ isOpen, onClose }) => {
error,
mutate: mutateProfile,
} = useProfile(user.addr);
const [loaded, setLoaded] = useState(false);
const [txStatus, setTxStatus] = useState<string | null>(null);
const [tags, setTags] = useState<string[]>([]);
const [tagInput, setTagInput] = useState('');

const [settings, setSettings] = useState<ProfileSettings>({
handle: '',
socials: {},
referralSource: '',
deployedContracts: {},
});
const [loaded, setLoaded] = useState(false);
const [txStatus, setTxStatus] = useState<string | null>(null);
const [tags, setTags] = useState<string[]>([]);
const [tagInput, setTagInput] = useState('');
const [errors, setErrors] = useState<{
handle?: string;
socials?: string;
referralSource?: string;
deployedContracts?: string;
}>({});
const [touched, setTouched] = useState<{
handle?: boolean;
socials?: boolean;
referralSource?: boolean;
deployedContracts?: boolean;
}>({});

const validate = () => {
const result = ProfileSettingsSchema.safeParse(settings);
if (!result.success) {
setErrors(
result.error.errors.reduce((acc, error) => {
const field = error.path[0];
acc[field] = error.message;
return acc;
}, {}),
);
} else {
setErrors({});
}
};

const completedChallenges = Object.keys(profile?.submissions ?? {}).reduce(
(acc, key) => {
Expand All @@ -72,6 +108,10 @@ const ProfileModal: React.FC<ProfileModalProps> = ({ isOpen, onClose }) => {
}
}, [profile, settings, loaded, isLoading, error]);

useEffect(() => {
validate();
}, [settings]);

const handleAddTag = () => {
if (tagInput.trim() && !tags.includes(tagInput.trim())) {
setTags([...tags, tagInput.trim()]);
Expand All @@ -86,6 +126,15 @@ const ProfileModal: React.FC<ProfileModalProps> = ({ isOpen, onClose }) => {
async function handleSave() {
if (!settings) return;

// Set touched for all fields & validate
setTouched({
handle: true,
socials: true,
referralSource: true,
deployedContracts: true,
});
validate();

setTxStatus('Pending Approval...');
try {
let txId: string | null = null;
Expand Down Expand Up @@ -145,21 +194,36 @@ const ProfileModal: React.FC<ProfileModalProps> = ({ isOpen, onClose }) => {
onChange={(e) =>
setSettings({ ...settings, handle: e.target.value })
}
onBlur={() => setTouched({ ...touched, handle: true })}
/>
</Field>
{errors.handle && touched.handle && (
<div className="text-red-500 text-sm">{errors.handle}</div>
)}
<Field label="Github Handle" description="What's your Github handle?">
<Input
name="profile_handle"
name="github_handle"
placeholder="joedoecodes"
value={settings?.socials?.[SocialType.GITHUB] || ''}
onChange={(e) =>
onChange={(e) => {
const socials: Record<string, string> = {
...settings.socials,
[SocialType.GITHUB]: e.target.value,
};
if (!socials[SocialType.GITHUB]) {
delete socials[SocialType.GITHUB];
}
setSettings({
...settings,
socials: { [SocialType.GITHUB]: e.target.value },
})
}
socials,
});
}}
onBlur={() => setTouched({ ...touched, socials: true })}
/>
</Field>
{errors.socials && touched.socials && (
<div className="text-red-500 text-sm">{errors.socials}</div>
)}
</div>

<Field
Expand Down Expand Up @@ -204,6 +268,9 @@ const ProfileModal: React.FC<ProfileModalProps> = ({ isOpen, onClose }) => {
?.description || ''
}
/>
{errors.referralSource && touched.referralSource && (
<div className="text-red-500 text-sm">{errors.referralSource}</div>
)}
</div>

{completedChallenges.length > 0 && (
Expand Down
36 changes: 24 additions & 12 deletions src/utils/gold-star.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,28 @@ export const createProfile = async (profile: ProfileSettings) => {
arg(profile.handle, t.String),
arg(profile.referralSource, t.Optional(t.String)),
arg(
profile.socials
? Object.entries(profile.socials).map(([key, value]) => ({
profile.deployedContracts
? Object.entries(profile.deployedContracts).map(([key, value]) => ({
key,
value,
}))
: [],
t.Dictionary(t.Address, t.String),
t.Dictionary({
key: t.Address,
value: t.Array(t.String),
}),
),
arg(
profile.deployedContracts
? Object.entries(profile.deployedContracts).map(([key, value]) => ({
profile.socials
? Object.entries(profile.socials).map(([key, value]) => ({
key,
value,
}))
: [],
t.Dictionary(t.Address, t.Array(t.String)),
fcl.t.Dictionary({
key: fcl.t.String,
value: fcl.t.String,
}),
),
],
});
Expand All @@ -90,22 +96,28 @@ export const setProfile = async (profile: ProfileSettings) => {
arg(profile.handle, t.String),
arg(profile.referralSource, t.Optional(t.String)),
arg(
profile.socials
? Object.entries(profile.socials).map(([key, value]) => ({
profile.deployedContracts
? Object.entries(profile.deployedContracts).map(([key, value]) => ({
key,
value,
}))
: [],
t.Dictionary(t.Address, t.String),
t.Dictionary({
key: t.Address,
value: t.Array(t.String),
}),
),
arg(
profile.deployedContracts
? Object.entries(profile.deployedContracts).map(([key, value]) => ({
profile.socials
? Object.entries(profile.socials).map(([key, value]) => ({
key,
value,
}))
: [],
t.Dictionary(t.Address, t.Array(t.String)),
t.Dictionary({
key: t.String,
value: t.String,
}),
),
],
});
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -17817,7 +17817,7 @@ yocto-queue@^1.0.0:
resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-1.1.1.tgz#fef65ce3ac9f8a32ceac5a634f74e17e5b232110"
integrity sha512-b4JR1PFR10y1mKjhHY9LaGo6tmrgjit7hxVIeAmyMw3jegXR4dhYqLaQF5zMXZxY7tLpMyJeLjr1C4rLmkVe8g==

zod@^3.23.8:
zod@^3.23.8, zod@^3.24.1:
version "3.24.1"
resolved "https://registry.yarnpkg.com/zod/-/zod-3.24.1.tgz#27445c912738c8ad1e9de1bea0359fa44d9d35ee"
integrity sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==
Expand Down