Fix cookie usage in Party and grid tabs

This commit is contained in:
Justin Edmund 2022-11-15 05:12:18 -08:00
parent cdf25a42bf
commit a3d1c1ee56
4 changed files with 875 additions and 947 deletions

View file

@ -1,23 +1,23 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useCookies } from 'react-cookie'
import { useSnapshot } from 'valtio'
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { getCookie } from "cookies-next"
import { useSnapshot } from "valtio"
import { AxiosResponse } from 'axios'
import debounce from 'lodash.debounce'
import { AxiosResponse } from "axios"
import debounce from "lodash.debounce"
import JobSection from '~components/JobSection'
import CharacterUnit from '~components/CharacterUnit'
import JobSection from "~components/JobSection"
import CharacterUnit from "~components/CharacterUnit"
import api from '~utils/api'
import { appState } from '~utils/appState'
import api from "~utils/api"
import { appState } from "~utils/appState"
import './index.scss'
import "./index.scss"
// Props
interface Props {
new: boolean
slug?: string
characters?: GridCharacter[]
createParty: () => Promise<AxiosResponse<any, any>>
pushHistory?: (path: string) => void
}
@ -27,127 +27,85 @@ const CharacterGrid = (props: Props) => {
const numCharacters: number = 5
// Cookies
const [cookies] = useCookies(['account'])
const headers = (cookies.account != null) ? {
headers: {
'Authorization': `Bearer ${cookies.account.access_token}`
}
} : {}
const cookie = getCookie("account")
const accountData: AccountCookie = cookie
? JSON.parse(cookie as string)
: null
const headers = accountData
? { headers: { Authorization: `Bearer ${accountData.token}` } }
: {}
// Set up state for view management
const { party, grid } = useSnapshot(appState)
const [slug, setSlug] = useState()
const [found, setFound] = useState(false)
const [loading, setLoading] = useState(true)
const [firstLoadComplete, setFirstLoadComplete] = useState(false)
// Create a temporary state to store previous character uncap values
const [previousUncapValues, setPreviousUncapValues] = useState<{[key: number]: number}>({})
// Fetch data from the server
useEffect(() => {
const shortcode = (props.slug) ? props.slug : slug
if (shortcode) fetchGrid(shortcode)
else appState.party.editable = true
}, [slug, props.slug])
const [previousUncapValues, setPreviousUncapValues] = useState<{
[key: number]: number
}>({})
// Set the editable flag only on first load
useEffect(() => {
if (!loading && !firstLoadComplete) {
// If user is logged in and matches
if ((cookies.account && party.user && cookies.account.user_id === party.user.id) || props.new)
if (
(accountData && party.user && accountData.userId === party.user.id) ||
props.new
)
appState.party.editable = true
else
appState.party.editable = false
setFirstLoadComplete(true)
}
}, [props.new, cookies, party, loading, firstLoadComplete])
else appState.party.editable = false
}, [props.new, accountData, party])
// Initialize an array of current uncap values for each characters
useEffect(() => {
let initialPreviousUncapValues: {[key: number]: number} = {}
Object.values(appState.grid.characters).map(o => initialPreviousUncapValues[o.position] = o.uncap_level)
let initialPreviousUncapValues: { [key: number]: number } = {}
Object.values(appState.grid.characters).map(
(o) => (initialPreviousUncapValues[o.position] = o.uncap_level)
)
setPreviousUncapValues(initialPreviousUncapValues)
}, [appState.grid.characters])
// Methods: Fetching an object from the server
async function fetchGrid(shortcode: string) {
return api.endpoints.parties.getOneWithObject({ id: shortcode, object: 'characters', params: headers })
.then(response => processResult(response))
.catch(error => processError(error))
}
function processResult(response: AxiosResponse) {
// Store the response
const party: Party = response.data.party
// Store the important party and state-keeping values
appState.party.id = party.id
appState.party.user = party.user
appState.party.favorited = party.favorited
appState.party.created_at = party.created_at
appState.party.updated_at = party.updated_at
setFound(true)
setLoading(false)
// Populate the weapons in state
populateCharacters(party.characters)
}
function processError(error: any) {
if (error.response != null) {
if (error.response.status == 404) {
setFound(false)
setLoading(false)
}
} else {
console.error(error)
}
}
function populateCharacters(list: Array<GridCharacter>) {
list.forEach((object: GridCharacter) => {
if (object.position != null)
appState.grid.characters[object.position] = object
})
}
// Methods: Adding an object from search
function receiveCharacterFromSearch(object: Character | Weapon | Summon, position: number) {
function receiveCharacterFromSearch(
object: Character | Weapon | Summon,
position: number
) {
const character = object as Character
if (!party.id) {
props.createParty()
.then(response => {
props.createParty().then((response) => {
const party = response.data.party
appState.party.id = party.id
setSlug(party.shortcode)
if (props.pushHistory) props.pushHistory(`/p/${party.shortcode}`)
saveCharacter(party.id, character, position)
.then(response => storeGridCharacter(response.data.grid_character))
.catch(error => console.error(error))
.then((response) => storeGridCharacter(response.data.grid_character))
.catch((error) => console.error(error))
})
} else {
if (party.editable)
saveCharacter(party.id, character, position)
.then(response => storeGridCharacter(response.data.grid_character))
.catch(error => console.error(error))
.then((response) => storeGridCharacter(response.data.grid_character))
.catch((error) => console.error(error))
}
}
async function saveCharacter(partyId: string, character: Character, position: number) {
return await api.endpoints.characters.create({
'character': {
'party_id': partyId,
'character_id': character.id,
'position': position,
'uncap_level': characterUncapLevel(character)
}
}, headers)
async function saveCharacter(
partyId: string,
character: Character,
position: number
) {
return await api.endpoints.characters.create(
{
character: {
party_id: partyId,
character_id: character.id,
position: position,
uncap_level: characterUncapLevel(character),
},
},
headers
)
}
function storeGridCharacter(gridCharacter: GridCharacter) {
@ -178,8 +136,9 @@ const CharacterGrid = (props: Props) => {
try {
if (uncapLevel != previousUncapValues[position])
await api.updateUncap('character', id, uncapLevel)
.then(response => { storeGridCharacter(response.data.grid_character) })
await api.updateUncap("character", id, uncapLevel).then((response) => {
storeGridCharacter(response.data.grid_character)
})
} catch (error) {
console.error(error)
@ -187,13 +146,17 @@ const CharacterGrid = (props: Props) => {
updateUncapLevel(position, previousUncapValues[position])
// Remove optimistic key
let newPreviousValues = {...previousUncapValues}
let newPreviousValues = { ...previousUncapValues }
delete newPreviousValues[position]
setPreviousUncapValues(newPreviousValues)
}
}
function initiateUncapUpdate(id: string, position: number, uncapLevel: number) {
function initiateUncapUpdate(
id: string,
position: number,
uncapLevel: number
) {
memoizeAction(id, position, uncapLevel)
// Optimistically update UI
@ -203,13 +166,16 @@ const CharacterGrid = (props: Props) => {
const memoizeAction = useCallback(
(id: string, position: number, uncapLevel: number) => {
debouncedAction(id, position, uncapLevel)
}, [props, previousUncapValues]
},
[props, previousUncapValues]
)
const debouncedAction = useMemo(() =>
const debouncedAction = useMemo(
() =>
debounce((id, position, number) => {
saveUncap(id, position, number)
}, 500), [props, saveUncap]
}, 500),
[props, saveUncap]
)
const updateUncapLevel = (position: number, uncapLevel: number) => {
@ -218,7 +184,7 @@ const CharacterGrid = (props: Props) => {
function storePreviousUncapValue(position: number) {
// Save the current value in case of an unexpected result
let newPreviousValues = {...previousUncapValues}
let newPreviousValues = { ...previousUncapValues }
if (grid.characters[position]) {
newPreviousValues[position] = grid.characters[position].uncap_level
@ -234,7 +200,7 @@ const CharacterGrid = (props: Props) => {
<ul id="grid_characters">
{Array.from(Array(numCharacters)).map((x, i) => {
return (
<li key={`grid_unit_${i}`} >
<li key={`grid_unit_${i}`}>
<CharacterUnit
gridCharacter={grid.characters[i]}
editable={party.editable}

View file

@ -1,38 +1,41 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/router'
import { useSnapshot } from 'valtio'
import { useCookies } from 'react-cookie'
import clonedeep from 'lodash.clonedeep'
import { subscribeKey } from 'valtio/utils'
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/router"
import { useSnapshot } from "valtio"
import { getCookie } from "cookies-next"
import clonedeep from "lodash.clonedeep"
import PartySegmentedControl from '~components/PartySegmentedControl'
import PartyDetails from '~components/PartyDetails'
import WeaponGrid from '~components/WeaponGrid'
import SummonGrid from '~components/SummonGrid'
import CharacterGrid from '~components/CharacterGrid'
import PartySegmentedControl from "~components/PartySegmentedControl"
import PartyDetails from "~components/PartyDetails"
import WeaponGrid from "~components/WeaponGrid"
import SummonGrid from "~components/SummonGrid"
import CharacterGrid from "~components/CharacterGrid"
import api from '~utils/api'
import { appState, initialAppState } from '~utils/appState'
import { GridType, TeamElement } from '~utils/enums'
import api from "~utils/api"
import { appState, initialAppState } from "~utils/appState"
import { GridType, TeamElement } from "~utils/enums"
import './index.scss'
import { AxiosResponse } from 'axios'
import "./index.scss"
// Props
interface Props {
new?: boolean
slug?: string
team?: Party
raids: Raid[][]
pushHistory?: (path: string) => void
}
const Party = (props: Props) => {
// Cookies
const [cookies] = useCookies(['account'])
const cookie = getCookie("account")
const accountData: AccountCookie = cookie
? JSON.parse(cookie as string)
: null
const headers = useMemo(() => {
return (cookies.account != null) ? {
headers: { 'Authorization': `Bearer ${cookies.account.access_token}` }
} : {}
}, [cookies.account])
return accountData
? { headers: { Authorization: `Bearer ${accountData.token}` } }
: {}
}, [accountData])
// Set up router
const router = useRouter()
@ -48,6 +51,7 @@ const Party = (props: Props) => {
useEffect(() => {
const resetState = clonedeep(initialAppState)
appState.grid = resetState.grid
if (props.team) storeParty(props.team)
}, [])
useEffect(() => {
@ -62,9 +66,9 @@ const Party = (props: Props) => {
async function createParty(extra: boolean = false) {
let body = {
party: {
...(cookies.account) && { user_id: cookies.account.user_id },
extra: extra
}
...(accountData && { user_id: accountData.userId }),
extra: extra,
},
}
return await api.endpoints.parties.create(body, headers)
@ -75,32 +79,47 @@ const Party = (props: Props) => {
appState.party.extra = event.target.checked
if (party.id) {
api.endpoints.parties.update(party.id, {
'party': { 'extra': event.target.checked }
}, headers)
api.endpoints.parties.update(
party.id,
{
party: { extra: event.target.checked },
},
headers
)
}
}
function jobChanged() {
if (party.id) {
api.endpoints.parties.update(party.id, {
'party': { 'job_id': (job) ? job.id : '' }
}, headers)
api.endpoints.parties.update(
party.id,
{
party: { job_id: job ? job.id : "" },
},
headers
)
}
}
function updateDetails(name?: string, description?: string, raid?: Raid) {
if (appState.party.name !== name ||
if (
appState.party.name !== name ||
appState.party.description !== description ||
appState.party.raid?.id !== raid?.id) {
appState.party.raid?.id !== raid?.id
) {
if (appState.party.id)
api.endpoints.parties.update(appState.party.id, {
'party': {
'name': name,
'description': description,
'raid_id': raid?.id
}
}, headers)
api.endpoints.parties
.update(
appState.party.id,
{
party: {
name: name,
description: description,
raid_id: raid?.id,
},
},
headers
)
.then(() => {
appState.party.name = name
appState.party.description = description
@ -113,10 +132,11 @@ const Party = (props: Props) => {
// Deleting the party
function deleteTeam(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) {
if (appState.party.editable && appState.party.id) {
api.endpoints.parties.destroy({ id: appState.party.id, params: headers })
api.endpoints.parties
.destroy({ id: appState.party.id, params: headers })
.then(() => {
// Push to route
router.push('/')
router.push("/")
// Clean state
const resetState = clonedeep(initialAppState)
@ -133,19 +153,67 @@ const Party = (props: Props) => {
}
}
// Methods: Storing party data
const storeParty = function (party: Party) {
// Store the important party and state-keeping values
appState.party.id = party.id
appState.party.extra = party.extra
appState.party.user = party.user
appState.party.favorited = party.favorited
appState.party.created_at = party.created_at
appState.party.updated_at = party.updated_at
// Populate state
storeCharacters(party.characters)
storeWeapons(party.weapons)
storeSummons(party.summons)
}
const storeCharacters = (list: Array<GridCharacter>) => {
list.forEach((object: GridCharacter) => {
if (object.position != null)
appState.grid.characters[object.position] = object
})
}
const storeWeapons = (list: Array<GridWeapon>) => {
list.forEach((gridObject: GridWeapon) => {
if (gridObject.mainhand) {
appState.grid.weapons.mainWeapon = gridObject
appState.party.element = gridObject.object.element
} else if (!gridObject.mainhand && gridObject.position != null) {
appState.grid.weapons.allWeapons[gridObject.position] = gridObject
}
})
}
const storeSummons = (list: Array<GridSummon>) => {
list.forEach((gridObject: GridSummon) => {
if (gridObject.main) appState.grid.summons.mainSummon = gridObject
else if (gridObject.friend)
appState.grid.summons.friendSummon = gridObject
else if (
!gridObject.main &&
!gridObject.friend &&
gridObject.position != null
)
appState.grid.summons.allSummons[gridObject.position] = gridObject
})
}
// Methods: Navigating with segmented control
function segmentClicked(event: React.ChangeEvent<HTMLInputElement>) {
switch(event.target.value) {
case 'class':
switch (event.target.value) {
case "class":
setCurrentTab(GridType.Class)
break
case 'characters':
case "characters":
setCurrentTab(GridType.Character)
break
case 'weapons':
case "weapons":
setCurrentTab(GridType.Weapon)
break
case 'summons':
case "summons":
setCurrentTab(GridType.Summon)
break
default:
@ -153,42 +221,6 @@ const Party = (props: Props) => {
}
}
// Methods: Fetch party details
const processResult = useCallback((response: AxiosResponse) => {
appState.party.id = response.data.party.id
appState.party.user = response.data.party.user
appState.party.favorited = response.data.party.favorited
appState.party.created_at = response.data.party.created_at
appState.party.updated_at = response.data.party.updated_at
// Store the party's user-generated details
appState.party.name = response.data.party.name
appState.party.description = response.data.party.description
appState.party.raid = response.data.party.raid
appState.party.job = response.data.party.job
}, [])
const handleError = useCallback((error: any) => {
if (error.response != null && error.response.status == 404) {
// setFound(false)
} else if (error.response != null) {
console.error(error)
} else {
console.error("There was an error.")
}
}, [])
const fetchDetails = useCallback((shortcode: string) => {
return api.endpoints.parties.getOne({ id: shortcode, params: headers })
.then(response => processResult(response))
.catch(error => handleError(error))
}, [headers, processResult, handleError])
useEffect(() => {
const shortcode = (props.slug) ? props.slug : undefined
if (shortcode) fetchDetails(shortcode)
}, [props.slug, fetchDetails])
// Render: JSX components
const navigation = (
<PartySegmentedControl
@ -201,7 +233,7 @@ const Party = (props: Props) => {
const weaponGrid = (
<WeaponGrid
new={props.new || false}
slug={props.slug}
weapons={props.team?.weapons}
createParty={createParty}
pushHistory={props.pushHistory}
/>
@ -210,7 +242,7 @@ const Party = (props: Props) => {
const summonGrid = (
<SummonGrid
new={props.new || false}
slug={props.slug}
summons={props.team?.summons}
createParty={createParty}
pushHistory={props.pushHistory}
/>
@ -219,14 +251,14 @@ const Party = (props: Props) => {
const characterGrid = (
<CharacterGrid
new={props.new || false}
slug={props.slug}
characters={props.team?.characters}
createParty={createParty}
pushHistory={props.pushHistory}
/>
)
const currentGrid = () => {
switch(currentTab) {
switch (currentTab) {
case GridType.Character:
return characterGrid
case GridType.Weapon:
@ -238,15 +270,15 @@ const Party = (props: Props) => {
return (
<div>
{ navigation }
<section id="Party">
{ currentGrid() }
</section>
{ <PartyDetails
{navigation}
<section id="Party">{currentGrid()}</section>
{
<PartyDetails
editable={party.editable}
updateCallback={updateDetails}
deleteCallback={deleteTeam}
/>}
/>
}
</div>
)
}

View file

@ -1,24 +1,24 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useCookies } from 'react-cookie'
import { useSnapshot } from 'valtio'
import { useTranslation } from 'next-i18next'
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { getCookie } from "cookies-next"
import { useSnapshot } from "valtio"
import { useTranslation } from "next-i18next"
import { AxiosResponse } from 'axios'
import debounce from 'lodash.debounce'
import { AxiosResponse } from "axios"
import debounce from "lodash.debounce"
import SummonUnit from '~components/SummonUnit'
import ExtraSummons from '~components/ExtraSummons'
import SummonUnit from "~components/SummonUnit"
import ExtraSummons from "~components/ExtraSummons"
import api from '~utils/api'
import { appState } from '~utils/appState'
import api from "~utils/api"
import { appState } from "~utils/appState"
import './index.scss'
import "./index.scss"
// Props
interface Props {
new: boolean
slug?: string
summons?: GridSummon[]
createParty: () => Promise<AxiosResponse<any, any>>
pushHistory?: (path: string) => void
}
@ -27,130 +27,85 @@ const SummonGrid = (props: Props) => {
// Constants
const numSummons: number = 4
const { t } = useTranslation('common')
// Cookies
const [cookies, _] = useCookies(['account'])
const headers = (cookies.account != null) ? {
headers: {
'Authorization': `Bearer ${cookies.account.access_token}`
}
} : {}
const cookie = getCookie("account")
const accountData: AccountCookie = cookie
? JSON.parse(cookie as string)
: null
const headers = accountData
? { headers: { Authorization: `Bearer ${accountData.token}` } }
: {}
// Localization
const { t } = useTranslation("common")
// Set up state for view management
const { party, grid } = useSnapshot(appState)
const [slug, setSlug] = useState()
const [found, setFound] = useState(false)
const [loading, setLoading] = useState(true)
const [firstLoadComplete, setFirstLoadComplete] = useState(false)
// Create a temporary state to store previous weapon uncap value
const [previousUncapValues, setPreviousUncapValues] = useState<{[key: number]: number}>({})
// Fetch data from the server
useEffect(() => {
const shortcode = (props.slug) ? props.slug : slug
if (shortcode) fetchGrid(shortcode)
else appState.party.editable = true
}, [slug, props.slug])
const [previousUncapValues, setPreviousUncapValues] = useState<{
[key: number]: number
}>({})
// Set the editable flag only on first load
useEffect(() => {
if (!loading && !firstLoadComplete) {
// If user is logged in and matches
if ((cookies.account && party.user && cookies.account.user_id === party.user.id) || props.new)
if (
(accountData && party.user && accountData.userId === party.user.id) ||
props.new
)
appState.party.editable = true
else
appState.party.editable = false
setFirstLoadComplete(true)
}
}, [props.new, cookies, party, loading, firstLoadComplete])
else appState.party.editable = false
}, [props.new, accountData, party])
// Initialize an array of current uncap values for each summon
useEffect(() => {
let initialPreviousUncapValues: {[key: number]: number} = {}
let initialPreviousUncapValues: { [key: number]: number } = {}
if (appState.grid.summons.mainSummon)
initialPreviousUncapValues[-1] = appState.grid.summons.mainSummon.uncap_level
initialPreviousUncapValues[-1] =
appState.grid.summons.mainSummon.uncap_level
if (appState.grid.summons.friendSummon)
initialPreviousUncapValues[6] = appState.grid.summons.friendSummon.uncap_level
initialPreviousUncapValues[6] =
appState.grid.summons.friendSummon.uncap_level
Object.values(appState.grid.summons.allSummons).map(o => initialPreviousUncapValues[o.position] = o.uncap_level)
Object.values(appState.grid.summons.allSummons).map(
(o) => (initialPreviousUncapValues[o.position] = o.uncap_level)
)
setPreviousUncapValues(initialPreviousUncapValues)
}, [appState.grid.summons.mainSummon, appState.grid.summons.friendSummon, appState.grid.summons.allSummons])
// Methods: Fetching an object from the server
async function fetchGrid(shortcode: string) {
return api.endpoints.parties.getOneWithObject({ id: shortcode, object: 'summons', params: headers })
.then(response => processResult(response))
.catch(error => processError(error))
}
function processResult(response: AxiosResponse) {
// Store the response
const party: Party = response.data.party
// Store the important party and state-keeping values
appState.party.id = party.id
appState.party.user = party.user
appState.party.favorited = party.favorited
appState.party.created_at = party.created_at
appState.party.updated_at = party.updated_at
setFound(true)
setLoading(false)
// Populate the weapons in state
populateSummons(party.summons)
}
function processError(error: any) {
if (error.response != null) {
if (error.response.status == 404) {
setFound(false)
setLoading(false)
}
} else {
console.error(error)
}
}
function populateSummons(list: Array<GridSummon>) {
list.forEach((gridObject: GridSummon) => {
if (gridObject.main)
appState.grid.summons.mainSummon = gridObject
else if (gridObject.friend)
appState.grid.summons.friendSummon = gridObject
else if (!gridObject.main && !gridObject.friend && gridObject.position != null)
appState.grid.summons.allSummons[gridObject.position] = gridObject
})
}
}, [
appState.grid.summons.mainSummon,
appState.grid.summons.friendSummon,
appState.grid.summons.allSummons,
])
// Methods: Adding an object from search
function receiveSummonFromSearch(object: Character | Weapon | Summon, position: number) {
function receiveSummonFromSearch(
object: Character | Weapon | Summon,
position: number
) {
const summon = object as Summon
if (!party.id) {
props.createParty()
.then(response => {
props.createParty().then((response) => {
const party = response.data.party
appState.party.id = party.id
setSlug(party.shortcode)
if (props.pushHistory) props.pushHistory(`/p/${party.shortcode}`)
saveSummon(party.id, summon, position)
.then(response => storeGridSummon(response.data.grid_summon))
saveSummon(party.id, summon, position).then((response) =>
storeGridSummon(response.data.grid_summon)
)
})
} else {
if (party.editable)
saveSummon(party.id, summon, position)
.then(response => storeGridSummon(response.data.grid_summon))
saveSummon(party.id, summon, position).then((response) =>
storeGridSummon(response.data.grid_summon)
)
}
}
@ -159,25 +114,26 @@ const SummonGrid = (props: Props) => {
if (summon.uncap.ulb) uncapLevel = 5
else if (summon.uncap.flb) uncapLevel = 4
return await api.endpoints.summons.create({
'summon': {
'party_id': partyId,
'summon_id': summon.id,
'position': position,
'main': (position == -1),
'friend': (position == 6),
'uncap_level': uncapLevel
}
}, headers)
return await api.endpoints.summons.create(
{
summon: {
party_id: partyId,
summon_id: summon.id,
position: position,
main: position == -1,
friend: position == 6,
uncap_level: uncapLevel,
},
},
headers
)
}
function storeGridSummon(gridSummon: GridSummon) {
if (gridSummon.position == -1)
appState.grid.summons.mainSummon = gridSummon
if (gridSummon.position == -1) appState.grid.summons.mainSummon = gridSummon
else if (gridSummon.position == 6)
appState.grid.summons.friendSummon = gridSummon
else
appState.grid.summons.allSummons[gridSummon.position] = gridSummon
else appState.grid.summons.allSummons[gridSummon.position] = gridSummon
}
// Methods: Updating uncap level
@ -187,8 +143,9 @@ const SummonGrid = (props: Props) => {
try {
if (uncapLevel != previousUncapValues[position])
await api.updateUncap('summon', id, uncapLevel)
.then(response => { storeGridSummon(response.data.grid_summon) })
await api.updateUncap("summon", id, uncapLevel).then((response) => {
storeGridSummon(response.data.grid_summon)
})
} catch (error) {
console.error(error)
@ -196,13 +153,17 @@ const SummonGrid = (props: Props) => {
updateUncapLevel(position, previousUncapValues[position])
// Remove optimistic key
let newPreviousValues = {...previousUncapValues}
let newPreviousValues = { ...previousUncapValues }
delete newPreviousValues[position]
setPreviousUncapValues(newPreviousValues)
}
}
function initiateUncapUpdate(id: string, position: number, uncapLevel: number) {
function initiateUncapUpdate(
id: string,
position: number,
uncapLevel: number
) {
memoizeAction(id, position, uncapLevel)
// Optimistically update UI
@ -212,13 +173,16 @@ const SummonGrid = (props: Props) => {
const memoizeAction = useCallback(
(id: string, position: number, uncapLevel: number) => {
debouncedAction(id, position, uncapLevel)
}, [props, previousUncapValues]
},
[props, previousUncapValues]
)
const debouncedAction = useMemo(() =>
const debouncedAction = useMemo(
() =>
debounce((id, position, number) => {
saveUncap(id, position, number)
}, 500), [props, saveUncap]
}, 500),
[props, saveUncap]
)
const updateUncapLevel = (position: number, uncapLevel: number) => {
@ -226,17 +190,21 @@ const SummonGrid = (props: Props) => {
appState.grid.summons.mainSummon.uncap_level = uncapLevel
else if (appState.grid.summons.friendSummon && position == 6)
appState.grid.summons.friendSummon.uncap_level = uncapLevel
else
appState.grid.summons.allSummons[position].uncap_level = uncapLevel
else appState.grid.summons.allSummons[position].uncap_level = uncapLevel
}
function storePreviousUncapValue(position: number) {
// Save the current value in case of an unexpected result
let newPreviousValues = {...previousUncapValues}
let newPreviousValues = { ...previousUncapValues }
if (appState.grid.summons.mainSummon && position == -1) newPreviousValues[position] = appState.grid.summons.mainSummon.uncap_level
else if (appState.grid.summons.friendSummon && position == 6) newPreviousValues[position] = appState.grid.summons.friendSummon.uncap_level
else newPreviousValues[position] = appState.grid.summons.allSummons[position].uncap_level
if (appState.grid.summons.mainSummon && position == -1)
newPreviousValues[position] = appState.grid.summons.mainSummon.uncap_level
else if (appState.grid.summons.friendSummon && position == 6)
newPreviousValues[position] =
appState.grid.summons.friendSummon.uncap_level
else
newPreviousValues[position] =
appState.grid.summons.allSummons[position].uncap_level
setPreviousUncapValues(newPreviousValues)
}
@ -244,7 +212,7 @@ const SummonGrid = (props: Props) => {
// Render: JSX components
const mainSummonElement = (
<div className="LabeledUnit">
<div className="Label">{t('summons.main')}</div>
<div className="Label">{t("summons.main")}</div>
<SummonUnit
gridSummon={grid.summons.mainSummon}
editable={party.editable}
@ -259,7 +227,7 @@ const SummonGrid = (props: Props) => {
const friendSummonElement = (
<div className="LabeledUnit">
<div className="Label">{t('summons.friend')}</div>
<div className="Label">{t("summons.friend")}</div>
<SummonUnit
gridSummon={grid.summons.friendSummon}
editable={party.editable}
@ -273,10 +241,11 @@ const SummonGrid = (props: Props) => {
)
const summonGridElement = (
<div id="LabeledGrid">
<div className="Label">{t('summons.summons')}</div>
<div className="Label">{t("summons.summons")}</div>
<ul id="grid_summons">
{Array.from(Array(numSummons)).map((x, i) => {
return (<li key={`grid_unit_${i}`} >
return (
<li key={`grid_unit_${i}`}>
<SummonUnit
gridSummon={grid.summons.allSummons[i]}
editable={party.editable}
@ -285,7 +254,8 @@ const SummonGrid = (props: Props) => {
updateObject={receiveSummonFromSearch}
updateUncap={initiateUncapUpdate}
/>
</li>)
</li>
)
})}
</ul>
</div>
@ -303,12 +273,12 @@ const SummonGrid = (props: Props) => {
return (
<div>
<div id="SummonGrid">
{ mainSummonElement }
{ friendSummonElement }
{ summonGridElement }
{mainSummonElement}
{friendSummonElement}
{summonGridElement}
</div>
{ subAuraSummonElement }
{subAuraSummonElement}
</div>
)
}

View file

@ -1,23 +1,23 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useCookies } from 'react-cookie'
import { useSnapshot } from 'valtio'
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { getCookie } from "cookies-next"
import { useSnapshot } from "valtio"
import { AxiosResponse } from 'axios'
import debounce from 'lodash.debounce'
import { AxiosResponse } from "axios"
import debounce from "lodash.debounce"
import WeaponUnit from '~components/WeaponUnit'
import ExtraWeapons from '~components/ExtraWeapons'
import WeaponUnit from "~components/WeaponUnit"
import ExtraWeapons from "~components/ExtraWeapons"
import api from '~utils/api'
import { appState } from '~utils/appState'
import api from "~utils/api"
import { appState } from "~utils/appState"
import './index.scss'
import "./index.scss"
// Props
interface Props {
new: boolean
slug?: string
weapons?: GridWeapon[]
createParty: (extra: boolean) => Promise<AxiosResponse<any, any>>
pushHistory?: (path: string) => void
}
@ -27,125 +27,73 @@ const WeaponGrid = (props: Props) => {
const numWeapons: number = 9
// Cookies
const [cookies] = useCookies(['account'])
const headers = (cookies.account != null) ? {
headers: {
'Authorization': `Bearer ${cookies.account.access_token}`
}
} : {}
const cookie = getCookie("account")
const accountData: AccountCookie = cookie
? JSON.parse(cookie as string)
: null
const headers = accountData
? { headers: { Authorization: `Bearer ${accountData.token}` } }
: {}
// Set up state for view management
const { party, grid } = useSnapshot(appState)
const [slug, setSlug] = useState()
const [found, setFound] = useState(false)
const [loading, setLoading] = useState(true)
const [firstLoadComplete, setFirstLoadComplete] = useState(false)
// Create a temporary state to store previous weapon uncap values
const [previousUncapValues, setPreviousUncapValues] = useState<{[key: number]: number}>({})
// Fetch data from the server
useEffect(() => {
const shortcode = (props.slug) ? props.slug : slug
if (shortcode) fetchGrid(shortcode)
else appState.party.editable = true
}, [slug, props.slug])
const [previousUncapValues, setPreviousUncapValues] = useState<{
[key: number]: number
}>({})
// Set the editable flag only on first load
useEffect(() => {
if (!loading && !firstLoadComplete) {
// If user is logged in and matches
if ((cookies.account && party.user && cookies.account.user_id === party.user.id) || props.new)
if (
(accountData && party.user && accountData.userId === party.user.id) ||
props.new
)
appState.party.editable = true
else
appState.party.editable = false
setFirstLoadComplete(true)
}
}, [props.new, cookies, party, loading, firstLoadComplete])
else appState.party.editable = false
}, [props.new, accountData, party])
// Initialize an array of current uncap values for each weapon
useEffect(() => {
let initialPreviousUncapValues: {[key: number]: number} = {}
let initialPreviousUncapValues: { [key: number]: number } = {}
if (appState.grid.weapons.mainWeapon)
initialPreviousUncapValues[-1] = appState.grid.weapons.mainWeapon.uncap_level
initialPreviousUncapValues[-1] =
appState.grid.weapons.mainWeapon.uncap_level
Object.values(appState.grid.weapons.allWeapons).map(o => initialPreviousUncapValues[o.position] = o.uncap_level)
Object.values(appState.grid.weapons.allWeapons).map(
(o) => (initialPreviousUncapValues[o.position] = o.uncap_level)
)
setPreviousUncapValues(initialPreviousUncapValues)
}, [appState.grid.weapons.mainWeapon, appState.grid.weapons.allWeapons])
// Methods: Fetching an object from the server
async function fetchGrid(shortcode: string) {
return api.endpoints.parties.getOneWithObject({ id: shortcode, object: 'weapons', params: headers })
.then(response => processResult(response))
.catch(error => processError(error))
}
function processResult(response: AxiosResponse) {
// Store the response
const party: Party = response.data.party
// Store the important party and state-keeping values
appState.party.id = party.id
appState.party.extra = party.extra
appState.party.user = party.user
appState.party.favorited = party.favorited
appState.party.created_at = party.created_at
appState.party.updated_at = party.updated_at
setFound(true)
setLoading(false)
// Populate the weapons in state
populateWeapons(party.weapons)
}
function processError(error: any) {
if (error.response != null) {
if (error.response.status == 404) {
setFound(false)
setLoading(false)
}
} else {
console.error(error)
}
}
function populateWeapons(list: Array<GridWeapon>) {
list.forEach((gridObject: GridWeapon) => {
if (gridObject.mainhand) {
appState.grid.weapons.mainWeapon = gridObject
appState.party.element = gridObject.object.element
} else if (!gridObject.mainhand && gridObject.position != null) {
appState.grid.weapons.allWeapons[gridObject.position] = gridObject
}
})
}
// Methods: Adding an object from search
function receiveWeaponFromSearch(object: Character | Weapon | Summon, position: number) {
function receiveWeaponFromSearch(
object: Character | Weapon | Summon,
position: number
) {
const weapon = object as Weapon
if (position == 1)
appState.party.element = weapon.element
if (position == 1) appState.party.element = weapon.element
if (!party.id) {
props.createParty(party.extra)
.then(response => {
props.createParty(party.extra).then((response) => {
const party = response.data.party
appState.party.id = party.id
setSlug(party.shortcode)
if (props.pushHistory) props.pushHistory(`/p/${party.shortcode}`)
saveWeapon(party.id, weapon, position)
.then(response => storeGridWeapon(response.data.grid_weapon))
saveWeapon(party.id, weapon, position).then((response) =>
storeGridWeapon(response.data.grid_weapon)
)
})
} else {
saveWeapon(party.id, weapon, position)
.then(response => storeGridWeapon(response.data.grid_weapon))
saveWeapon(party.id, weapon, position).then((response) =>
storeGridWeapon(response.data.grid_weapon)
)
}
}
@ -154,15 +102,18 @@ const WeaponGrid = (props: Props) => {
if (weapon.uncap.ulb) uncapLevel = 5
else if (weapon.uncap.flb) uncapLevel = 4
return await api.endpoints.weapons.create({
'weapon': {
'party_id': partyId,
'weapon_id': weapon.id,
'position': position,
'mainhand': (position == -1),
'uncap_level': uncapLevel
}
}, headers)
return await api.endpoints.weapons.create(
{
weapon: {
party_id: partyId,
weapon_id: weapon.id,
position: position,
mainhand: position == -1,
uncap_level: uncapLevel,
},
},
headers
)
}
function storeGridWeapon(gridWeapon: GridWeapon) {
@ -182,8 +133,9 @@ const WeaponGrid = (props: Props) => {
try {
if (uncapLevel != previousUncapValues[position])
await api.updateUncap('weapon', id, uncapLevel)
.then(response => { storeGridWeapon(response.data.grid_weapon) })
await api.updateUncap("weapon", id, uncapLevel).then((response) => {
storeGridWeapon(response.data.grid_weapon)
})
} catch (error) {
console.error(error)
@ -191,13 +143,17 @@ const WeaponGrid = (props: Props) => {
updateUncapLevel(position, previousUncapValues[position])
// Remove optimistic key
let newPreviousValues = {...previousUncapValues}
let newPreviousValues = { ...previousUncapValues }
delete newPreviousValues[position]
setPreviousUncapValues(newPreviousValues)
}
}
function initiateUncapUpdate(id: string, position: number, uncapLevel: number) {
function initiateUncapUpdate(
id: string,
position: number,
uncapLevel: number
) {
memoizeAction(id, position, uncapLevel)
// Optimistically update UI
@ -207,27 +163,31 @@ const WeaponGrid = (props: Props) => {
const memoizeAction = useCallback(
(id: string, position: number, uncapLevel: number) => {
debouncedAction(id, position, uncapLevel)
}, [props, previousUncapValues]
},
[props, previousUncapValues]
)
const debouncedAction = useMemo(() =>
const debouncedAction = useMemo(
() =>
debounce((id, position, number) => {
saveUncap(id, position, number)
}, 500), [props, saveUncap]
}, 500),
[props, saveUncap]
)
const updateUncapLevel = (position: number, uncapLevel: number) => {
if (appState.grid.weapons.mainWeapon && position == -1)
appState.grid.weapons.mainWeapon.uncap_level = uncapLevel
else
appState.grid.weapons.allWeapons[position].uncap_level = uncapLevel
else appState.grid.weapons.allWeapons[position].uncap_level = uncapLevel
}
function storePreviousUncapValue(position: number) {
// Save the current value in case of an unexpected result
let newPreviousValues = {...previousUncapValues}
newPreviousValues[position] = (appState.grid.weapons.mainWeapon && position == -1) ?
appState.grid.weapons.mainWeapon.uncap_level : appState.grid.weapons.allWeapons[position].uncap_level
let newPreviousValues = { ...previousUncapValues }
newPreviousValues[position] =
appState.grid.weapons.mainWeapon && position == -1
? appState.grid.weapons.mainWeapon.uncap_level
: appState.grid.weapons.allWeapons[position].uncap_level
setPreviousUncapValues(newPreviousValues)
}
@ -244,10 +204,9 @@ const WeaponGrid = (props: Props) => {
/>
)
const weaponGridElement = (
Array.from(Array(numWeapons)).map((x, i) => {
const weaponGridElement = Array.from(Array(numWeapons)).map((x, i) => {
return (
<li key={`grid_unit_${i}`} >
<li key={`grid_unit_${i}`}>
<WeaponUnit
gridWeapon={appState.grid.weapons.allWeapons[i]}
editable={party.editable}
@ -259,7 +218,6 @@ const WeaponGrid = (props: Props) => {
</li>
)
})
)
const extraGridElement = (
<ExtraWeapons
@ -274,11 +232,13 @@ const WeaponGrid = (props: Props) => {
return (
<div id="WeaponGrid">
<div id="MainGrid">
{ mainhandElement }
<ul className="grid_weapons">{ weaponGridElement }</ul>
{mainhandElement}
<ul className="grid_weapons">{weaponGridElement}</ul>
</div>
{ (() => { return (party.extra) ? extraGridElement : '' })() }
{(() => {
return party.extra ? extraGridElement : ""
})()}
</div>
)
}