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

Dashboard #1871

Merged
merged 6 commits into from
Jan 23, 2025
Merged
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
44 changes: 44 additions & 0 deletions apps/web/app/[language]/dashboard/dashboard.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
.intro {
margin: 16px;
}

.table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
border: none;
}

.table > thead > tr > th {
padding: 12px 16px;
background-color: var(--color-background-light);
border-top: 1px solid var(--color-border-dark);
border-bottom: 1px solid var(--color-border-dark);
font-weight: 500;
position: sticky;
top: var(--table-sticky-top, 48px);
height: 58px;
}
[data-table-overflow] > .table > thead > tr > th {
position: static;
}

.table > tbody > tr > td {
padding: 16px;
}

.table > tbody > tr + tr > td {
border-top: 1px solid var(--color-border-dark);
}

.emptyState {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48px 16px;
background-color: var(--color-background-light);
border-radius: 2px;
gap: 24px;
margin: 16px;
}
172 changes: 172 additions & 0 deletions apps/web/app/[language]/dashboard/dashboard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
'use client';

import { Gw2AccountName } from '@/components/Gw2Api/Gw2AccountName';
import { Gw2Accounts } from '@/components/Gw2Api/Gw2Accounts';
import type { Gw2Account } from '@/components/Gw2Api/types';
import { type FC, Suspense, useCallback, useEffect, useState } from 'react';
import styles from './dashboard.module.css';
import { Button } from '@gw2treasures/ui/components/Form/Button';
import { Headline } from '@gw2treasures/ui/components/Headline/Headline';
import { useInventoryItemTotal } from '@/components/Inventory/use-inventory';
import { Skeleton } from '@/components/Skeleton/Skeleton';
import { Scope } from '@gw2me/client';
import { useSubscription } from '@/components/Gw2Api/Gw2AccountSubscriptionProvider';
import { CurrencyValue } from '@/components/Currency/CurrencyValue';
import { DropDown } from '@gw2treasures/ui/components/DropDown/DropDown';
import { MenuList } from '@gw2treasures/ui/components/Layout/MenuList';
import { SearchItemDialog, type SearchItemDialogSubmitHandler } from '@/components/Item/SearchItemDialog';
import { ItemLink } from '@/components/Item/ItemLink';
import { SearchCurrencyDialog, type SearchCurrencyDialogSubmitHandler } from '@/components/Currency/SearchCurrencyDialog';
import { CurrencyLink } from '@/components/Currency/CurrencyLink';
import { FormatNumber } from '@/components/Format/FormatNumber';
import { encodeColumns, type Column } from './helper';
import { Notice } from '@gw2treasures/ui/components/Notice/Notice';
import { State, EmptyState } from './state';
import { TableWrapper } from '@gw2treasures/ui/components/Table/TableWrapper';
import { AchievementLink } from '@/components/Achievement/AchievementLink';
import { AccountAchievementProgressCell } from '@/components/Achievement/AccountAchievementProgress';

const requiredScopes = [Scope.GW2_Account, Scope.GW2_Characters, Scope.GW2_Inventories, Scope.GW2_Unlocks, Scope.GW2_Tradingpost, Scope.GW2_Wallet, Scope.GW2_Progression];

export interface DashboardProps {
initialColumns?: Column[]
}

export const Dashboard: FC<DashboardProps> = ({ initialColumns = [] }) => {
const [columns, setColumns] = useState<Column[]>(initialColumns);

useEffect(() => {
window.history.replaceState(null, '', '?columns=' + encodeColumns(columns));
}, [columns]);

return (
<div>
<div className={styles.intro}>
<Notice icon="eye">Preview: The dashboard is still a work in progress!</Notice>
<Headline id="inventory" actions={[
(<Button key="c" onClick={() => setColumns([])} icon="delete">Clear Columns</Button>),
(<AddColumnButton key="+" onAddColumn={(column) => setColumns([...columns, column])}/>),
]}
>
Dashboard
</Headline>
</div>
<TableWrapper className={styles.overflow}>
<table className={styles.table}>
<thead>
<tr>
<th align="left">Account</th>
{columns.map((column) => (
<th key={`${column.type}-${column.id}`} align={column.type !== 'achievement' ? 'right' : 'left'}>
{(column.type === 'item' && column.item) ? (
<ItemLink item={column.item}/>
) : (column.type === 'currency' && column.currency) ? (
<CurrencyLink currency={column.currency}/>
) : (column.type === 'achievement' && column.achievement) ? (
<AchievementLink achievement={column.achievement}/>
) : (
<>[{column.type}: {column.id}]</>
)}
</th>
))}
</tr>
</thead>
<Gw2Accounts requiredScopes={requiredScopes} loading={null} authorizationMessage={null} loginMessage={null}>
{(accounts) => (
<tbody>
{accounts.map((account) => <AccountRow key={account.id} account={account} columns={columns}/>)}
</tbody>
)}
</Gw2Accounts>
</table>
</TableWrapper>
<Suspense fallback={<EmptyState icon="loading">Loading...</EmptyState>}>
<State requiredScopes={requiredScopes}/>
</Suspense>
</div>
);
};

const AddColumnButton: FC<{ onAddColumn: (column: Column) => void }> = ({ onAddColumn }) => {
const [searchItem, setSearchItem] = useState(false);
const [searchCurrency, setSearchCurrency] = useState(false);

const handleAddItem: SearchItemDialogSubmitHandler = useCallback((item) => {
setSearchItem(false);
if(item) {
onAddColumn({ type: 'item', id: item.id, item });
}
}, [onAddColumn]);

const handleAddCurrency: SearchCurrencyDialogSubmitHandler = useCallback((currency) => {
setSearchCurrency(false);
if(currency) {
onAddColumn({ type: 'currency', id: currency.id, currency });
}
}, [onAddColumn]);

return (
<>
<DropDown button={<Button icon="add">Add column</Button>}>
<MenuList>
<Button appearance="menu" icon="item" onClick={() => setSearchItem(true)}>Add item</Button>
<Button appearance="menu" icon="coins" onClick={() => setSearchCurrency(true)}>Add currency</Button>
</MenuList>
</DropDown>
<SearchItemDialog open={searchItem} onSubmit={handleAddItem}/>
<SearchCurrencyDialog open={searchCurrency} onSubmit={handleAddCurrency}/>
</>
);
};

interface AccountRow {
account: Gw2Account,
columns: Column[],
}

const AccountRow: FC<AccountRow> = ({ account, columns }) => {
return (
<tr>
<td><Gw2AccountName account={account}/></td>
{columns.map((column) => column.type === 'item' ? (
<AccountItemCell key={`${column.type}-${column.id}`} account={account} id={column.id}/>
) : column.type === 'currency' ? (
<AccountCurrencyCell key={`${column.type}-${column.id}`} account={account} id={column.id}/>
) : column.type === 'achievement' ? (
<AccountAchievementProgressCell key={`${column.type}-${column.id}`} accountId={account.id} achievement={column.achievement!}/>
) : <td/>)}
</tr>
);
};

interface AccountCellProps {
account: Gw2Account,
id: number,
}

const AccountItemCell: FC<AccountCellProps> = ({ account, id }) => {
const total = useInventoryItemTotal(account.id, id);

return (
<td align="right">{total.loading ? <Skeleton/> : total.error ? 'error' : <FormatNumber value={total.count}/>}</td>
);
};

const AccountCurrencyCell: FC<AccountCellProps> = ({ account, id }) => {
const wallet = useSubscription('wallet', account.id);
const currency = !wallet.loading && !wallet.error
? wallet.data.find((currency) => currency.id === id)
: undefined;

return (
<td align="right">
{wallet.loading ? (
<Skeleton/>
) : wallet.error ? (
<span style={{ color: 'var(--color-error)' }}>Error loading wallet.</span>
) : (
<CurrencyValue currencyId={id} value={currency?.value ?? 0}/>
)}
</td>
);
};
53 changes: 53 additions & 0 deletions apps/web/app/[language]/dashboard/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { WithIcon } from '@/lib/with';
import type { Achievement, Currency, Item } from '@gw2treasures/database';
import type { LocalizedEntity } from '@/lib/localizedName';
import { isDefined } from '@gw2treasures/helper/is';

const columnTypeMap = {
i: 'item',
c: 'currency',
a: 'achievement',
} as const;

export function encodeColumns(columns: Column[]): string {
return columns.map(({ type, id }) => `${type[0]}${id}`).join(',');
}

export function decodeColumns(columns: string | string[] | null | undefined): Column[] {
if(!columns || columns.length === 0) {
return [];
}

return (Array.isArray(columns) ? columns : [columns])
.flatMap((c) => c.split(','))
.map(decodeColumn)
.filter(isDefined);
}

function decodeColumn(column: string): Column | undefined {
if(column.length < 2) {
return undefined;
}

const type = columnTypeMap[column[0] as keyof typeof columnTypeMap];
if(!type) {
return undefined;
}

const id = parseInt(column.substring(1));
if(isNaN(id) || id < 1) {
return undefined;
}

return { type, id };
}

export type Column = {
id: number;
} & ({
type: 'item', item?: WithIcon<Pick<Item, 'id' | 'rarity' | keyof LocalizedEntity>>
} | {
type: 'currency', currency?: WithIcon<Pick<Currency, 'id' | keyof LocalizedEntity>>
} | {
type: 'achievement', achievement?: WithIcon<Pick<Achievement, 'id' | keyof LocalizedEntity | 'flags' | 'prerequisitesIds'>>
});
75 changes: 75 additions & 0 deletions apps/web/app/[language]/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { PageProps } from '@/lib/next';
import { Dashboard } from './dashboard';
import { decodeColumns } from './helper';
import { db } from '@/lib/prisma';
import { linkProperties, linkPropertiesWithoutRarity } from '@/lib/linkProperties';
import { groupBy, groupById } from '@gw2treasures/helper/group-by';

export default async function DashboardPage({ searchParams }: PageProps) {
const { columns } = await searchParams;
const initialColumns = decodeColumns(columns);
const columnsByType = groupBy(initialColumns, 'type');

// load data
const [items, currencies, achievements] = await Promise.all([
groupById(await loadItems(columnsByType.get('item')?.map(({ id }) => id))),
groupById(await loadCurrencies(columnsByType.get('currency')?.map(({ id }) => id))),
groupById(await loadAchievements(columnsByType.get('achievement')?.map(({ id }) => id))),
]);

// append data to initial columns
for(const column of initialColumns) {
switch(column.type) {
case 'item':
column.item = items.get(column.id);
break;
case 'currency':
column.currency = currencies.get(column.id);
break;
case 'achievement':
column.achievement = achievements.get(column.id);
break;
}
}

return (
<Dashboard initialColumns={initialColumns}/>
);
}

function loadItems(ids: number[] | undefined) {
if(!ids || ids.length === 0) {
return [];
}

return db.item.findMany({
where: { id: { in: ids }},
select: linkProperties
});
}

function loadCurrencies(ids: number[] | undefined) {
if(!ids || ids.length === 0) {
return [];
}

return db.currency.findMany({
where: { id: { in: ids }},
select: linkPropertiesWithoutRarity
});
}

function loadAchievements(ids: number[] | undefined) {
if(!ids || ids.length === 0) {
return [];
}

return db.achievement.findMany({
where: { id: { in: ids }},
select: { ...linkPropertiesWithoutRarity, flags: true, prerequisitesIds: true }
});
}

export const metadata = {
title: 'Dashboard'
};
Loading
Loading