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

feat: add haptics command #115

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion demo/with-next/components/ClientContent/ExternalLinks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,16 @@ export const ExternalLinks = () => {
>
Valid Associated Domain (Link)
</Link>
<Link
href="worldapp://mini-app?app_id=app_staging_e387587d26a286fb5bea1d436ba0b2a3&path=features"
className="bg-green-500 text-white text-center rounded-lg p-3"
>
worldapp:// deep link
</Link>
<button
onClick={() => {
window.open(
"https://worldcoin.org/mini-app?app_id=app_staging_d3b49eb04b497130e18533b9d8846319",
"https://world.org/mini-app?app_id=app_staging_e387587d26a286fb5bea1d436ba0b2a3&path=features",
"_blank"
);
}}
Expand Down
118 changes: 118 additions & 0 deletions demo/with-next/components/ClientContent/SendHapticFeedback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import {
MiniKit,
ResponseEvent,
MiniAppSendHapticFeedbackPayload,
SendHapticFeedbackCommandInput,
SendHapticFeedbackErrorCodes,
} from "@worldcoin/minikit-js";
import { useCallback, useEffect, useState } from "react";
import { validateSchema } from "./helpers/validate-schema";
import * as yup from "yup";

const sendHapticFeedbackSuccessPayloadSchema = yup.object({
status: yup.string<"success">().oneOf(["success"]),
});

const sendHapticFeedbackErrorPayloadSchema = yup.object({
error_code: yup
.string<SendHapticFeedbackErrorCodes>()
.oneOf(Object.values(SendHapticFeedbackErrorCodes))
.required(),
status: yup.string<"error">().equals(["error"]).required(),
version: yup.number().required(),
});

const allPossibleHaptics: SendHapticFeedbackCommandInput[] = [
{ hapticsType: "impact", style: "heavy" },
{ hapticsType: "impact", style: "light" },
{ hapticsType: "impact", style: "medium" },
{ hapticsType: "notification", style: "error" },
{ hapticsType: "notification", style: "success" },
{ hapticsType: "notification", style: "warning" },
{ hapticsType: "selection-changed" },
];

export const SendHapticFeedback = () => {
const [sentHapticFeedbackPayload, setSentHapticFeedbackPayload] =
useState<Record<string, any> | null>(null);

useEffect(() => {
if (!MiniKit.isInstalled()) {
return;
}

MiniKit.subscribe(
ResponseEvent.MiniAppSendHapticFeedback,
async (payload: MiniAppSendHapticFeedbackPayload) => {
console.log("MiniAppSendHapticFeedback, SUBSCRIBE PAYLOAD", payload);

if (payload.status === "error") {
const validationErrorMessage = await validateSchema(
sendHapticFeedbackErrorPayloadSchema,
payload
);

if (!validationErrorMessage) {
console.log("Payload is valid");
} else {
console.error(validationErrorMessage);
}
} else {
const validationErrorMessage = await validateSchema(
sendHapticFeedbackSuccessPayloadSchema,
payload
);

// This checks if the response format is correct
if (!validationErrorMessage) {
console.log("Payload is valid");
} else {
console.error(validationErrorMessage);
}
}
}
);

return () => {
MiniKit.unsubscribe(ResponseEvent.MiniAppSignTypedData);
};
}, []);

const onSendHapticFeedback = useCallback(
async (input: SendHapticFeedbackCommandInput) => {
const payload = MiniKit.commands.sendHapticFeedback(input);

setSentHapticFeedbackPayload({
payload,
});
},
[]
);

return (
<div>
<div className="grid gap-y-2">
<h2 className="text-2xl font-bold">Sign Typed Data</h2>

<div>
<div className="bg-gray-300 min-h-[100px] p-2">
<pre className="break-all whitespace-break-spaces max-h-[250px] overflow-y-scroll ">
{JSON.stringify(sentHapticFeedbackPayload, null, 2)}
</pre>
</div>
</div>
<div className="grid grid-cols-2 gap-x-3">
{allPossibleHaptics.map((haptic, i) => (
<button
key={i}
className="bg-black text-white rounded-lg p-4 w-full"
onClick={() => onSendHapticFeedback(haptic)}
>
{`Send ${haptic.hapticsType}-${haptic?.style}`}
</button>
))}
</div>
</div>
</div>
);
};
145 changes: 145 additions & 0 deletions demo/with-next/components/ClientContent/ShareContacts.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import {
MiniKit,
ShareContactsErrorCodes,
ResponseEvent,
Contact,
ShareContactsPayload,
} from "@worldcoin/minikit-js";
import { useCallback, useEffect, useState } from "react";
import { validateSchema } from "./helpers/validate-schema";
import * as yup from "yup";

const shareContactsSuccessPayloadSchema = yup.object({
status: yup.string<"success">().equals(["success"]).required(),
version: yup.number().required(),
contacts: yup.array().of(yup.object<Contact>().required()),
});

const shareContactsErrorPayloadSchema = yup.object({
error_code: yup
.string<ShareContactsErrorCodes>()
.oneOf(Object.values(ShareContactsErrorCodes))
.required(),
status: yup.string<"error">().equals(["error"]).required(),
version: yup.number().required(),
});

export const ShareContacts = () => {
const [shareContactsAppPayload, setShareContactsAppPayload] = useState<
string | undefined
>();

const [
shareContactsPayloadValidationMessage,
setShareContactsPayloadValidationMessage,
] = useState<string | null>();

const [sentShareContactsPayload, setSentShareContactsPayload] =
useState<Record<string, any> | null>(null);

const [tempInstallFix, setTempInstallFix] = useState(0);

useEffect(() => {
if (!MiniKit.isInstalled()) {
return;
}

MiniKit.subscribe(ResponseEvent.MiniAppShareContacts, async (payload) => {
console.log("MiniAppShareContacts, SUBSCRIBE PAYLOAD", payload);
setShareContactsAppPayload(JSON.stringify(payload, null, 2));
if (payload.status === "error") {
const errorMessage = await validateSchema(
shareContactsErrorPayloadSchema,
payload
);

if (!errorMessage) {
setShareContactsPayloadValidationMessage("Payload is valid");
} else {
setShareContactsPayloadValidationMessage(errorMessage);
}
} else {
const errorMessage = await validateSchema(
shareContactsSuccessPayloadSchema,
payload
);

// This checks if the response format is correct
if (!errorMessage) {
setShareContactsPayloadValidationMessage("Payload is valid");
} else {
setShareContactsPayloadValidationMessage(errorMessage);
}
}
});

return () => {
MiniKit.unsubscribe(ResponseEvent.MiniAppShareContacts);
};
}, [tempInstallFix]);

const onShareContacts = useCallback(
async (isMultiSelectEnabled: boolean = false) => {
const shareContactsPayload: ShareContactsPayload = {
isMultiSelectEnabled,
};

const payload = MiniKit.commands.shareContacts(shareContactsPayload);
setSentShareContactsPayload({
payload,
});
console.log("payload", payload);
setTempInstallFix((prev) => prev + 1);
},
[]
);

return (
<div>
<div className="grid gap-y-2">
<h2 className="text-2xl font-bold">Share Contacts</h2>

<div>
<div className="bg-gray-300 min-h-[100px] p-2">
<pre className="break-all whitespace-break-spaces">
{JSON.stringify(sentShareContactsPayload, null, 2)}
</pre>
</div>
</div>
<div className="grid gap-4 grid-cols-2">
<button
className="bg-black text-white rounded-lg p-4 w-full"
onClick={() => onShareContacts(true)}
>
Share Contacts (Multi enabled)
</button>
<button
className="bg-black text-white rounded-lg p-4 w-full"
onClick={() => onShareContacts(false)}
>
Share Contacts (multi disabled)
</button>
</div>
</div>

<hr />

<div className="w-full grid gap-y-2">
<p>Message from &quot;{ResponseEvent.MiniAppShareContacts}&quot; </p>

<div className="bg-gray-300 min-h-[100px] p-2">
<pre className="break-all whitespace-break-spaces">
{shareContactsAppPayload ?? JSON.stringify(null)}
</pre>
</div>

<div className="grid gap-y-2">
<p>Response Validation:</p>
<p className="bg-gray-300 p-2">
{shareContactsPayloadValidationMessage ?? "No validation"}
</p>
</div>
</div>
</div>
);
};
59 changes: 59 additions & 0 deletions demo/with-next/components/ClientContent/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,29 @@ import { CameraComponent } from "./Camera";
import { SendTransaction } from "./Transaction";
import { SignMessage } from "./SignMessage";
import { SignTypedData } from "./SignTypedMessage";
import { ShareContacts } from "./ShareContacts";
import {
GetSearchedUsernameResult,
UsernameSearch,
} from "@worldcoin/minikit-react";
import { useState } from "react";
import Image from "next/image";
import { SendHapticFeedback } from "./SendHapticFeedback";

const VersionsNoSSR = dynamic(
() => import("./Versions").then((comp) => comp.Versions),
{ ssr: false }
);

export const ClientContent = () => {
const [searchValue, setSearchValue] = useState("");
const [searchResults, setSearchResults] =
useState<GetSearchedUsernameResult>();

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchValue(e.target.value);
};

return (
<div className="p-2 lg:p-8 grid content-start min-h-[100dvh] gap-y-2">
<Nav />
Expand All @@ -27,6 +43,45 @@ export const ClientContent = () => {
<User />
<hr />

<UsernameSearch
value={searchValue}
handleChange={handleChange}
setSearchedUsernames={setSearchResults}
className="p-2 border rounded"
inputProps={{
placeholder: "Search usernames...",
}}
/>

{/* Display search results */}
{searchResults && (
<div className="mt-4">
{searchResults.status === 200 ? (
<ul>
{searchResults.data?.map((user) => (
<li
key={user.address}
className="grid grid-cols-[auto_1fr] gap-x-2 items-center"
>
{user.profile_picture_url && (
<Image
src={user.profile_picture_url}
alt={user.username}
width={32}
height={32}
className="w-10 h-10 rounded-full"
/>
)}
{user.username} - {user.address}
</li>
))}
</ul>
) : (
<p>Error: {searchResults.error}</p>
)}
</div>
)}

<div className="grid gap-y-8">
<VersionsNoSSR />
<hr />
Expand All @@ -42,6 +97,10 @@ export const ClientContent = () => {
<hr />
<SignTypedData />
<hr />
<ShareContacts />
<hr />
<SendHapticFeedback />
<hr />
<input className="text-xs border-black border-2" />
<ExternalLinks />
<hr />
Expand Down
6 changes: 5 additions & 1 deletion demo/with-next/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
const nextConfig = {
images: {
domains: ["static.usernames.app-backend.toolsforhumanity.com"],
},
};

export default nextConfig;
Loading