hensei-web/pages/p/[party].tsx
Justin Edmund 19c852c13b
Hotfix to disable page tabs (#354)
* Rich text editor and support for tagging objects (#340)

* Preliminary work around making an Element type

* Disabled Youtube code for now

* Clean description with DOMPurify

* Update GranblueElement with slug

* Add new api endpoint for searching all resources

* Add new variables and themes

* Remove fixed height on html tag for now

* Update README.md

We renamed the folders for character images from `chara-` to `character-`

* Add no results string

* Add tiptap and associated packages

* Update .gitignore

* Update components that use character images

* Add Editor component

This commit adds the bulk of the code for our new rich-text editor. The Editor component will be used to edit and display rich text via Tiptap.

* Add mention components

This adds the code required for us to mention objects in rich text fields like team descriptions.

The mentionSuggestion util fetches data from the server and serves it to MentionList for the user to select, then inserts it into the Editor as a token.

* Implements Editor in edit team and team footer

This implements the Editor component in EditPartyModal and PartyFooter. In PartyFooter, it is read-only.

* Remove min-width on tokens

* Add rudimentary conversion for old descriptions

Old descriptions just translate as a blob of text, so we try to insert some paragraphs and newlines to keep things presentable and lessen the load if users decide to update

* Add support for displaying jobs in MentionList

* Handle numbers and value=0 better

* Keep description reactive

This shouldn't work? The snapshot should be the reactive one? I don't fucking know

* Send locale to api with search query

* Delete getLocale.tsx

We didn't actually use this

* Fix build errors

* Override peer dependencies for tiptap mentions

They haven't fixed the suggestion plugin, so we have to use a beta version

* Fix background-color on CharacterRep

* Tiptap updates (#343)

* Reinstantiate editor on changes

We can't dynamically update the content, so we have to recreate the Editor whenever something changes (page loads and updates)

* Fix import

@tiptap/core is different than @tiptap/react, who knew

* Added several Tiptap components

* Added a Remix icon that isn't in remixicon-react

* Add colors for highlights

* Add ToolbarButton component

This is to standardize adding Toolbar icons so it wasn't a miserable mess in the Editor file

* Add extensions and implement ToolbarButton

* Remove unused code

* Use party prop and add keys

We always want to use the party in props until the transformer work is done and our source of truth is more reliable.

Also, we are using keys to ensure that the component reloads on new page.

* Component cleanup

* Always use props.party

* Ensure content gets reset when edits are committed

Here, we do some tactical bandaid fixes to ensure that when the user saves data to the server, the editor will show the freshest data in both editable and read-only mode.

In the Editor, its as easy as calling the setContent command in a useEffect hook when the content changes.

In the party, we are saving party in a state and passing it down to the components via props. This is because the party prop we get from pages is only from the first time the server loaded data, so any edits are not reflected. The app state should have the latest updates, but due to reasons I don't completely understand, it is showing the old state first and then the one we want, causing the Editor to get stuck on old data.

By storing the party in a state, we can populate the state from the server when the component mounts, then update it whenever the user saves data since all party data is saved in that component.

* Fix build errors

* Fix icon path

* Remove duplicate binding

* Fix styles

* Update transcendence components to work with CSS modules (#350)

* Update transcendence components to use CSS modules

* Fix summon transcendence

Summon transcendence was doing something wonky. This adapts the updateUncap endpoint method to make it a little bit clearer whats going on.

* Add toolbar localizations

* Allow translation of Heading icons

* Show localized placeholder for team name

* Add placeholder extension

* Add placeholder to party description

* Ensure name modification works right

Needed a null check? for some reason?

* Small fix for some modals on mobile

This fixes the slide up animation and the end point so that modals are actually visible on mobile. Ones that scroll still don't work great.

* Fix TableField components on mobile

* Put viewport meta tag in _app

* Some fixes for scrollable dialogs on mobile

This is 100% not going to scale to devices that are not my iPhone 14 Pro Max, but I can't get env variables working in CSS and something is better than nothing for right now.

* Disable tab pages
2023-07-06 22:28:41 -07:00

229 lines
5.7 KiB
TypeScript

import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import Party from '~components/party/Party'
import ErrorSection from '~components/ErrorSection'
import PartyHead from '~components/party/PartyHead'
import api from '~utils/api'
import elementEmoji from '~utils/elementEmoji'
import fetchLatestVersion from '~utils/fetchLatestVersion'
import { setHeaders } from '~utils/userToken'
import { appState } from '~utils/appState'
import { groupWeaponKeys } from '~utils/groupWeaponKeys'
import { GridType } from '~utils/enums'
import type { NextApiRequest, NextApiResponse } from 'next'
import type { PageContextObj, ResponseStatus } from '~types'
import type { AxiosError } from 'axios'
interface Props {
context?: PageContextObj
version: AppUpdate
error: boolean
status?: ResponseStatus
}
const PartyRoute: React.FC<Props> = ({
context,
version,
error,
status,
}: Props) => {
// Set up state to save selected tab and
// update when router changes
const router = useRouter()
useEffect(() => {
const parts = router.asPath.split('/')
const tab = parts[parts.length - 1]
switch (tab) {
case 'characters':
setSelectedTab(GridType.Character)
break
case 'weapons':
setSelectedTab(GridType.Weapon)
break
case 'summons':
setSelectedTab(GridType.Summon)
break
}
}, [])
const getCurrentTab = () => {
const parts = router.asPath.split('/')
const tab = parts[parts.length - 1]
switch (tab) {
case 'characters':
return GridType.Character
case 'weapons':
return GridType.Weapon
case 'summons':
return GridType.Summon
default:
return GridType.Weapon
}
}
const [selectedTab, setSelectedTab] = useState<GridType>(getCurrentTab())
const handleTabChange = (value: string) => {
const path = [
// Enable when using Next.js Router
// 'p',
router.asPath.split('/').filter((el) => el != '')[1],
value,
].join('/')
switch (value) {
case 'characters':
setSelectedTab(GridType.Character)
break
case 'weapons':
setSelectedTab(GridType.Weapon)
break
case 'summons':
setSelectedTab(GridType.Summon)
break
}
// if (router.asPath !== '/new' && router.asPath !== '/')
// router.replace(path, undefined, { shallow: true })
}
// Set the initial data from props
useEffect(() => {
if (context && !error) {
appState.raidGroups = context.raidGroups
appState.jobs = context.jobs ? context.jobs : []
appState.jobSkills = context.jobSkills ? context.jobSkills : []
appState.weaponKeys = context.weaponKeys
}
if (status && error) {
appState.status = status
}
appState.version = version
}, [])
// Methods: Page component rendering
function pageHead() {
if (context && context.party && context.meta)
return <PartyHead party={context.party} meta={context.meta} />
}
function pageError() {
if (status) return <ErrorSection status={status} />
else return <div />
}
if (context) {
return (
<React.Fragment key={router.asPath}>
{pageHead()}
<Party
team={context.party}
selectedTab={selectedTab}
raidGroups={context.raidGroups}
handleTabChanged={handleTabChange}
/>
</React.Fragment>
)
} else return pageError()
}
export const getServerSidePaths = async () => {
return {
paths: [
// Object variant:
{ params: { party: 'string' } },
],
fallback: true,
}
}
// prettier-ignore
export const getServerSideProps = async ({ req, res, locale, query }: { req: NextApiRequest, res: NextApiResponse, locale: string, query: { [index: string]: string } }) => {
// Set headers for server-side requests
setHeaders(req, res)
// Fetch latest version
const version = await fetchLatestVersion()
try {
// Fetch and organize raids
let raidGroups: RaidGroup[] = await api
.raidGroups()
.then((response) => response.data)
// Fetch jobs and job skills
let jobs = await api.endpoints.jobs
.getAll()
.then((response) => response.data)
let jobSkills = await api.allJobSkills()
.then((response) => response.data)
// Fetch and organize weapon keys
let weaponKeys = await api.endpoints.weapon_keys
.getAll()
.then((response) => groupWeaponKeys(response.data))
// Fetch the party
let party: Party | undefined = undefined
if (query.party) {
let response = await api.endpoints.parties.getOne({
id: query.party,
})
party = response.data.party
} else {
console.error('No party code')
}
// Consolidate data into context object
const context: PageContextObj = {
party: party,
jobs: jobs,
jobSkills: jobSkills,
raidGroups: raidGroups,
weaponKeys: weaponKeys,
meta: {
element: elementEmoji(party),
},
}
// Pass to the page component as props
return {
props: {
context: context,
version: version,
error: false,
...(await serverSideTranslations(locale, ['common'])),
},
}
} catch (error) {
// Extract the underlying Axios error
const axiosError = error as AxiosError
const response = axiosError.response
// Pass to the page component as props
return {
props: {
context: null,
error: true,
version: version,
status: {
code: response?.status,
text: response?.statusText,
},
...(await serverSideTranslations(locale, ['common'])),
},
}
}
}
export default PartyRoute