Skip to content

Commit

Permalink
refactor item page state and hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
kibagateaux committed Feb 6, 2024
1 parent f9a9c01 commit bd57651
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 60 deletions.
27 changes: 14 additions & 13 deletions src/app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Animated, { useAnimatedStyle, useSharedValue, withSpring } from 'react-na
import { isEmpty } from 'lodash/fp';

import { useHomeConfig } from 'hooks';
// import { useAuth, useGameContent } from 'contexts';
import { useAuth, useGameContent } from 'contexts';
import { WidgetConfig, WidgetIds, obj } from 'types/UserConfig';
import { getIconForWidget } from 'utils/rendering';

Expand All @@ -25,8 +25,8 @@ import { magicRug } from 'utils/zkpid';

const HomeScreen = () => {
const { config: homeConfig, save: saveHomeConfig } = useHomeConfig();
// const { setActiveModal } = useGameContent();
// const { player, getSpellBook } = useAuth();
const { setActiveModal } = useGameContent();
const { player, getSpellBook } = useAuth();
const eggRollAngle = useSharedValue(30);
const eggAnimatedStyles = useAnimatedStyle(() => ({
transform: [{ rotate: `${eggRollAngle.value}deg` }],
Expand Down Expand Up @@ -123,16 +123,17 @@ const HomeScreen = () => {
onComplete={async (config) => {
try {
console.log('on avatar config wizard complete', config.stats);
// if(!player?.id) setActiveModal({
// name: 'create-spellbook',
// dialogueData: {
// title: "A jinni is approaching",
// text: "Wait for it to sniff you and say hi",
// }
// });
// await getSpellBook();

// setActiveModal(undefined);
if (!player?.id)
setActiveModal({
name: 'create-spellbook',
dialogueData: {
title: 'A jinni is approaching',
text: 'Wait for it to sniff you and say hi',
},
});
await getSpellBook();
setActiveModal(undefined);

await Promise.all([
finalizeRenovation(
[
Expand Down
89 changes: 46 additions & 43 deletions src/app/inventory/[item].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,45 @@ interface ItemPageProps {
const ItemPage: React.FC<ItemPageProps> = () => {
const { item: id }: { item: string } = useLocalSearchParams();
const { inventory, loading, setItemStatus } = useInventory();
const { player, getSpellBook } = useAuth();
// const item = inventory.find((i) => i.id === id);
const [item, setItem] = useState<InventoryItem | null>(null);
const status = item?.status;
// const [status, setItemStatus] = useState<ItemStatus | null>(null);
// const [activeModal, setActiveModal] = useState<string | null>(null);
const { setActiveModal } = useGameContent();
const { inventory: content } = useGameContent();
// hooks for items that require 3rd party authentication
const [itemOauthConfig, setItemOauth] = useState<OAuthProvider>(oauthConfigs.undefined);
const [activeAbilities, setActiveAbilities] = useState<ItemAbility[]>([]);
const [activeAbilities, setActiveAbilities] = useState<ItemAbility[] | void>(undefined);

const item = inventory.find((i) => i.id === id);
const status: ItemStatus = item?.status;
console.log('pg:inventory:item:Load', id, status, item?.tags);
useMemo(async () => {
// we cant store item status in config so compute and store in store
console.log('Item: check status?', item?.id && !status, item?.id, !status);
if (item?.id && !status) {
console.log('Item: setting status!!!');
const newStatus = await item!.checkStatus();
console.log('pg:Inv:Item check item status', newStatus);
setItemStatus(item.id, newStatus);
}
}, [item, status, setItemStatus]);

useMemo(async () => {
console.log(
'Item: check active abiliti?',
item?.abilities?.length && !activeAbilities,
item?.abilities?.length,
!activeAbilities,
);
if (item?.abilities?.length && !activeAbilities) {
const activeAbs = await Promise.all(
item.abilities?.filter(async (ability) => {
(await ability.canDo(status)) === 'ethereal';
}) ?? [],
);
console.log('pb:Inv:Item post item status abilitiy check', activeAbs);
setActiveAbilities(activeAbs);
}
}, [item, status, activeAbilities]);

// hooks for items that require 3rd party authentication
// TODO break functionality into actual separate components to shard state and prevent rerenders
// primarly <ItemActionbutton>, <ItemActiveAbilities>, <ItemWidgets> all have completely separate data reqs
const [itemOauthConfig, setItemOauth] = useState<OAuthProvider>(oauthConfigs.undefined);
// console.log('Item: oauth', itemOauthConfig, request, response);
const [request, response, promptAsync] = useAuthRequest(
{
clientId: itemOauthConfig.clientId,
Expand All @@ -60,37 +85,6 @@ const ItemPage: React.FC<ItemPageProps> = () => {
},
itemOauthConfig,
);
// console.log('Item: oauth', itemOauthConfig, request, response);

useMemo(() => {
// we cant store item status in config so compute and store in store
if (item?.id && !status)
item!.checkStatus().then((newStatus: ItemStatus) => {
console.log('pg:Inv:Item check item status', newStatus);
setItemStatus(item.id, newStatus);
});

if (item?.abilities?.length && status) {
Promise.all(
item.abilities?.filter(async (ability) => {
(await ability.canDo(status!)) === 'ethereal';
}) ?? [],
).then((active) => {
console.log('pb:Inv:Item post item status abilitiy check', active);
setActiveAbilities(active);
});
}
}, [item, status, setItemStatus]);

// console.log('Item: item', id, item);
// console.log('Item: status & modal', status, activeModal);

useMemo(() => {
const newItem = inventory.find((item) => item.id === id);
if (!newItem) return; // invalid id
if (id && !item) setItem(newItem); // first render
if (newItem.status !== item?.status) setItem(newItem); // status update
}, [id, item, inventory]);

useMemo(async () => {
if (item?.id) {
Expand All @@ -108,6 +102,15 @@ const ItemPage: React.FC<ItemPageProps> = () => {
}
}, [item]);

const { player, getSpellBook } = useAuth();
const { setActiveModal } = useGameContent();
const { inventory: content } = useGameContent();
// console.log('Item: status & modal', status, activeModal);

// TODO render loading screen when oauth items are generating redirect.
// OR ideally delay oauth state generation until equip()
// if (itemOauthConfig && !itemOauthConfig.state) setActiveModal({ name: 'create-spellbook' })

if (loading) return <ActivityIndicator animating size="large" />;

if (!inventory) return <Text> Item Not Currently Available For Gameplay </Text>;
Expand Down Expand Up @@ -253,7 +256,7 @@ const ItemPage: React.FC<ItemPageProps> = () => {
const renderActiveItemAbilities = () => (
<View>
<Text style={styles.sectionTitle}>Active Abilities</Text>
{activeAbilities.length ? (
{activeAbilities?.length ? (
<ScrollView horizontal style={{ flex: 1 }}>
{activeAbilities.map((ability) => (
// TODO check if canDo. yes? do(), no? checkStatus == equipped yes? nothin, no? pop up modal to equip.
Expand Down
4 changes: 1 addition & 3 deletions src/inventory/maliks-majik.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,10 @@ const equip: HoF = async () => {
return true;
} else {
throw Error('Enchanter is not a Master Djinn');
// TODO return error message. "Wrong maji for ritual"
return false;
}
} catch (e) {
console.log('Inv:MaliksMajik:equip:ERR', e);
return false;
throw e;
}
};

Expand Down
1 change: 1 addition & 0 deletions src/types/GameMechanics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export type ItemIds =
| ('AndroidHealthConnect' & OAuthProviderIds);

export type ItemStatus =
| void
| 'ethereal' // can be used by player but isnt installed or accessible at the moment
| 'unequipped' // player can equip but hasnt yet
| 'unequipping' // in the process of moving from 'equipped' -> 'unequipped'
Expand Down
2 changes: 1 addition & 1 deletion src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,8 @@ export const getStorage: <T>(slot: string, useMysticCrypt?: boolean) => Promise<
console.log(
'get storage 1 - {slot, useCrypt} + cached',
JSON.stringify({ slot, secure: useMysticCrypt }),
cached,
);
console.log(cached);
if (cached) return cached;
const val = useMysticCrypt
? await getItemAsync(slot, { requireAuthentication: !__DEV__ })
Expand Down

0 comments on commit bd57651

Please sign in to comment.