Skip to content

Commit

Permalink
recursive creation
Browse files Browse the repository at this point in the history
  • Loading branch information
elliotBraem committed Oct 31, 2024
1 parent bf8e399 commit 015c551
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 31 deletions.
21 changes: 19 additions & 2 deletions apps/www/src/components/form/select-type.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import {
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import { useWeb4Auth } from "@/hooks/use-web4-auth";
import { useGetTypes } from "@/lib/graph";
import { getTypes } from "@/lib/inventory";
import { useAccount } from "@/lib/providers/jazz";
import { ErrorSchema, WidgetProps } from "@rjsf/utils";

export function SelectTypeWidget(props: WidgetProps) {
Expand All @@ -23,7 +26,9 @@ export function SelectType({
id?: string | undefined
) => void;
}) {
const { data: types, isLoading, isError } = useGetTypes();
const { me } = useAccount();
const { accountId } = useWeb4Auth();
const { data: types = [], isLoading, isError } = useGetTypes();

if (isLoading) {
return <p>Loading...</p>;
Expand All @@ -32,13 +37,25 @@ export function SelectType({
if (isError) {
return <p>Failed to load types</p>;
}

const localTypes = getTypes(me)?.map((it) => {
const typeData = JSON.parse(it.data);
return {
accountId,
id: it.id,
key: typeData.name,
};
}) || [];

const combinedTypes = [...types, ...localTypes];

return (
<Select onValueChange={onChange} defaultValue={value}>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select a type" />
</SelectTrigger>
<SelectContent>
{types?.map((type: any) => (
{combinedTypes?.map((type: any) => (
<SelectItem key={type.id} value={type.id}>
{type.key}
</SelectItem>
Expand Down
6 changes: 4 additions & 2 deletions apps/www/src/components/thing/create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { AIProcessor } from "../ai-processor";
import { FormGenerator } from "../form/generator";
import { SelectType } from "../form/select-type";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import { safeJsonParse } from "@/lib/utils";

// Types
interface CreateThingProps {
Expand Down Expand Up @@ -92,6 +93,7 @@ type CreationMethod = (typeof CREATION_METHODS)[keyof typeof CREATION_METHODS];

const ThingForm = ({ type, onSubmit }: FormProps) => {
const { data, isLoading, isError } = useType({ typeId: type });

const [creationMethod, setCreationMethod] = useState<CreationMethod>(
CREATION_METHODS.AI
);
Expand All @@ -112,8 +114,8 @@ const ThingForm = ({ type, onSubmit }: FormProps) => {
// Parse the data and handle potential errors
let schema;
try {
const typeData = JSON.parse(data.data);
schema = JSON.parse(typeData.schema);
const typeData = safeJsonParse(data.data);
schema = safeJsonParse(typeData.schema);
if (!schema) {
return <ErrorState message="No schema available" />;
}
Expand Down
46 changes: 30 additions & 16 deletions apps/www/src/lib/graph.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { useWallet } from "@/lib/providers/near";
import { queryClient } from "@/main";
import { NO_DEPOSIT, THIRTY_TGAS } from "@/wallets/near-wallet";
import { getProviderByNetwork, view } from "@near-js/client";
import { parseNearAmount } from "@near-js/utils";
import { useMutation, useQuery } from "@tanstack/react-query";
import { NO_DEPOSIT, THIRTY_TGAS } from "@/wallets/near-wallet";
import { queryClient } from "@/main";
import { getThing, getThings, getTypes } from "./inventory";
import { useAccount } from "./providers/jazz";
import { Thing } from "./schema";
import { ID } from "jazz-tools";

export interface GuestBookMessage {
premium: boolean;
Expand Down Expand Up @@ -38,28 +41,39 @@ function transformToThing(input) {

export function useType({ typeId }: { typeId: string }) {
const { networkId } = useWallet();
const { me } = useAccount();

return useQuery({
queryKey: ["get-type", typeId],
queryFn: async () => {
const args = {
keys: [typeId, `${typeId}/metadata/**`]
};

const typeData = await view<number>({
account: GRAPH_CONTRACT[networkId],
method: "get",
deps: { rpcProvider: getProviderByNetwork(networkId) },
args
});
console.log("typeId", typeId)
if (typeId.startsWith("type-registry.testnet")) {
const args = {
keys: [typeId, `${typeId}/metadata/**`]
};

const typeData = await view<number>({
account: GRAPH_CONTRACT[networkId],
method: "get",
deps: { rpcProvider: getProviderByNetwork(networkId) },
args
});

return transformToThing(typeData)[0];
return transformToThing(typeData)[0];
} else {
const things = getThings(me);
const type = things.filter((thing) => {
return thing.id === typeId;
});
return type[0];
}
}
});
}

export function useGetTypes() {
const { networkId } = useWallet();
const { me } = useAccount();

return useQuery({
queryKey: ["get-types"],
Expand All @@ -68,13 +82,13 @@ export function useGetTypes() {
keys: ["type-registry.testnet/type/*"]
};

const allTypes = await view<number>({
const publicTypes = await view<number>({
account: GRAPH_CONTRACT[networkId],
method: "keys",
deps: { rpcProvider: getProviderByNetwork(networkId) },
args
});
return buildObjects(allTypes);
return buildObjects(publicTypes);
}
});
}
Expand Down
17 changes: 8 additions & 9 deletions apps/www/src/lib/inventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,11 @@ export const getThings = (me: UserAccount) => {
};

export const getTypes = (me: UserAccount) => {
me.root?.inventories?.flatMap(
(inventory) =>
inventory?.things?.filter(
(thing): thing is Exclude<typeof thing, null> => thing
) || []
) || []
const things = getThings(me);
const types = things.filter((thing) => {
return thing.type.startsWith("type-registry.testnet/type/Type");
});
return types;
}

export const getThing = (thingId: ID<Thing>) => {
Expand All @@ -47,8 +46,8 @@ export const getThingsByInventory = (me: UserAccount, inventory: Inventory) => {
const things = getThings(me);
return inventory
? things?.filter(
(item) => item?.inventory?.id === inventory.id && !item.deleted
)
(item) => item?.inventory?.id === inventory.id && !item.deleted
)
: things?.filter((item) => !item?.deleted);
};

Expand Down Expand Up @@ -81,7 +80,7 @@ export const deleteItem = (item: Thing) => {
item.inventory?.things?.splice(found, 1);
};

export const mintItem = (item: Thing) => {};
export const mintItem = (item: Thing) => { };

export const getInventories = (me: UserAccount) => {
return useCoState(InventoryList, me.root?._refs.inventories?.id, [
Expand Down
17 changes: 17 additions & 0 deletions apps/www/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,20 @@ import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

export function safeJsonParse(input) {
try {
return JSON.parse(input);
} catch (error) {
// Basic fixes: add missing quotes, handle common syntax errors, etc.
let fixedInput = input.replace(/:\s*([\w]+)/g, ': "$1"'); // Fixes unquoted property values
fixedInput = fixedInput.replace(/(["'])?(\w+)(["'])?(\s*:\s*)/g, '"$2"$4'); // Fixes unquoted keys

try {
return JSON.parse(fixedInput);
} catch (e) {
console.error("JSON parsing failed after attempts:", e);
return null; // Or handle the error more gracefully
}
}
}
4 changes: 2 additions & 2 deletions apps/www/src/routes/_layout/_auth/inventory/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DataTable } from "@/components/common/data-table";
import { columns } from "@/components/things/columns";
import { getThings } from "@/lib/inventory";
import { useAccountOrGuest } from "@/lib/providers/jazz";
import { useAccount } from "@/lib/providers/jazz";
import { createFileRoute } from "@tanstack/react-router";

// shows all things across all inventories
Expand All @@ -11,7 +11,7 @@ export const Route = createFileRoute("/_layout/_auth/inventory/")({
});

export default function InventoryPage() {
const { me } = useAccountOrGuest();
const { me } = useAccount();
const things = getThings(me);
const filteredThings = things?.filter((item) => !item?.deleted);

Expand Down

0 comments on commit 015c551

Please sign in to comment.