admin(ui): fix up SearchableSelect.tsx

This commit is contained in:
Matthew Penner 2021-02-15 18:48:10 -07:00
parent f790404845
commit 3971c4499d
7 changed files with 157 additions and 58 deletions

View File

@ -3,6 +3,7 @@
namespace Pterodactyl\Transformers\Api\Application;
use Pterodactyl\Models\Node;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class NodeTransformer extends BaseTransformer
@ -12,7 +13,7 @@ class NodeTransformer extends BaseTransformer
*
* @var array
*/
protected $availableIncludes = ['allocations', 'location', 'servers'];
protected $availableIncludes = ['allocations', 'database_host', 'location', 'mounts', 'servers'];
/**
* Return the resource name for the JSONAPI output.
@ -44,10 +45,11 @@ class NodeTransformer extends BaseTransformer
}
/**
* Return the nodes associated with this location.
* Return the allocations associated with this node.
*
* @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException
*/
public function includeAllocations(Node $node)
@ -66,10 +68,39 @@ class NodeTransformer extends BaseTransformer
}
/**
* Return the nodes associated with this location.
* Return the database host associated with this node.
*
* @return \League\Fractal\Resource\Item|\League\Fractal\Resource\NullResource
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException
*/
public function includeDatabaseHost(Node $node)
{
if (!$this->authorize(AdminAcl::RESOURCE_DATABASE_HOSTS)) {
return $this->null();
}
$node->loadMissing('databaseHost');
$databaseHost = $node->getRelation('databaseHost');
if (is_null($databaseHost)) {
return new NullResource();
}
return $this->item(
$node->getRelation('databaseHost'),
$this->makeTransformer(DatabaseHostTransformer::class),
'databaseHost'
);
}
/**
* Return the location associated with this node.
*
* @return \League\Fractal\Resource\Item|\League\Fractal\Resource\NullResource
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException
*/
public function includeLocation(Node $node)
@ -88,10 +119,34 @@ class NodeTransformer extends BaseTransformer
}
/**
* Return the nodes associated with this location.
* Return the mounts associated with this node.
*
* @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException
*/
public function includeMounts(Node $node)
{
if (!$this->authorize(AdminAcl::RESOURCE_MOUNTS)) {
return $this->null();
}
$node->loadMissing('mounts');
return $this->collection(
$node->getRelation('mounts'),
$this->makeTransformer(MountTransformer::class),
'mount'
);
}
/**
* Return the servers associated with this node.
*
* @return \League\Fractal\Resource\Collection|\League\Fractal\Resource\NullResource
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException
*/
public function includeServers(Node $node)

View File

@ -1,6 +1,7 @@
import http, { FractalResponseData, getPaginationSet, PaginatedResult } from '@/api/http';
import { createContext, useContext } from 'react';
import useSWR from 'swr';
import { Database, rawDataToDatabase } from '@/api/admin/databases/getDatabases';
import { Location, rawDataToLocation } from '@/api/admin/locations/getLocations';
export interface Node {
@ -10,6 +11,7 @@ export interface Node {
name: string;
description: string | null;
locationId: number;
databaseHostId: number | null;
fqdn: string;
listenPortHTTP: number;
publicPortHTTP: number;
@ -28,6 +30,7 @@ export interface Node {
updatedAt: Date;
relations: {
databaseHost: Database | undefined;
location: Location | undefined;
};
}
@ -39,6 +42,7 @@ export const rawDataToNode = ({ attributes }: FractalResponseData): Node => ({
name: attributes.name,
description: attributes.description,
locationId: attributes.location_id,
databaseHostId: attributes.database_host_id,
fqdn: attributes.fqdn,
listenPortHTTP: attributes.listen_port_http,
publicPortHTTP: attributes.public_port_http,
@ -57,6 +61,7 @@ export const rawDataToNode = ({ attributes }: FractalResponseData): Node => ({
updatedAt: new Date(attributes.updated_at),
relations: {
databaseHost: attributes.relationships?.databaseHost !== undefined ? rawDataToDatabase(attributes.relationships.databaseHost as FractalResponseData) : undefined,
location: attributes.relationships?.location !== undefined ? rawDataToLocation(attributes.relationships.location as FractalResponseData) : undefined,
},
});

View File

@ -1,11 +1,10 @@
import React, { useState } from 'react';
import SearchableSelect from '@/components/elements/SearchableSelect';
import SearchableSelect, { Option } from '@/components/elements/SearchableSelect';
import searchDatabases from '@/api/admin/databases/searchDatabases';
import { Database } from '@/api/admin/databases/getDatabases';
import tw from 'twin.macro';
export default () => {
const [ database, setDatabase ] = useState<Database | null>(null);
export default ({ selected }: { selected?: Database | null }) => {
const [ database, setDatabase ] = useState<Database | null>(selected || null);
const [ databases, setDatabases ] = useState<Database[]>([]);
const onSearch = (query: string): Promise<void> => {
@ -21,47 +20,26 @@ export default () => {
setDatabase(database);
};
const getSelectedText = (database: Database | null): string => {
return database?.name || '';
};
return (
<SearchableSelect
id="database"
name="Database"
items={databases}
selected={database}
setItems={setDatabases}
onSearch={onSearch}
onSelect={onSelect}
getSelectedText={getSelectedText}
nullable
>
{databases.map(d => (
d.id === database?.id ?
<li key={d.id} id={'listbox-item-' + d.id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={(e) => {
e.stopPropagation();
// selectItem(d);
}}
>
<div css={tw`flex items-center`}>
<span css={tw`block font-medium truncate`}>
{d.name}
</span>
</div>
<span css={tw`absolute inset-y-0 right-0 flex items-center pr-4`}>
<svg css={tw`h-5 w-5 text-primary-400`} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path clipRule="evenodd" fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"/>
</svg>
</span>
</li>
:
<li key={d.id} id={'listbox-item-' + d.id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={(e) => {
e.stopPropagation();
// selectItem(d);
}}
>
<div css={tw`flex items-center`}>
<span css={tw`block font-normal truncate`}>
{d.name}
</span>
</div>
</li>
<Option key={d.id} id={d.id} item={d} active={d.id === database?.id}>
{d.name}
</Option>
))}
</SearchableSelect>
);

View File

@ -13,10 +13,10 @@ const Dropdown = styled.div<{ expanded: boolean }>`
${props => !props.expanded && tw`hidden`};
`;
export default ({ defaultLocation }: { defaultLocation: Location }) => {
export default ({ defaultLocation }: { defaultLocation: Location | null }) => {
const [ loading, setLoading ] = useState(false);
const [ expanded, setExpanded ] = useState(false);
const [ location, setLocation ] = useState<Location>(defaultLocation);
const [ location, setLocation ] = useState<Location | null>(defaultLocation);
const [ locations, setLocations ] = useState<Location[]>([]);
const [ inputText, setInputText ] = useState('');
@ -48,7 +48,7 @@ export default ({ defaultLocation }: { defaultLocation: Location }) => {
};
useEffect(() => {
setInputText(location.short);
setInputText(location?.short || '');
setExpanded(false);
}, [ location ]);
@ -58,7 +58,7 @@ export default ({ defaultLocation }: { defaultLocation: Location }) => {
return;
}
setInputText(location.short);
setInputText(location?.short || '');
setExpanded(false);
};
@ -100,7 +100,7 @@ export default ({ defaultLocation }: { defaultLocation: Location }) => {
:
<ul tabIndex={-1} role="listbox" aria-labelledby="listbox-label" aria-activedescendant="listbox-item-3" css={tw`max-h-56 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm`}>
{locations.map(l => (
l.id === location.id ?
l.id === location?.id ?
<li key={l.id} id={'listbox-item-' + l.id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={(e) => {
e.stopPropagation();
selectLocation(l);

View File

@ -48,7 +48,7 @@ const NodeEditContainer = () => {
useEffect(() => {
clearFlashes('node');
getNode(Number(match.params?.id))
getNode(Number(match.params?.id), [ 'database_host', 'location' ])
.then(node => setNode(node))
.catch(error => {
console.error(error);

View File

@ -1,3 +1,4 @@
import DatabaseSelect from '@/components/admin/nodes/DatabaseSelect';
import React from 'react';
import AdminBox from '@/components/admin/AdminBox';
import tw from 'twin.macro';
@ -17,6 +18,7 @@ interface Values {
name: string;
description: string;
locationId: number;
databaseHostId: number | null;
fqdn: string;
listenPortHTTP: number;
publicPortHTTP: number;
@ -57,6 +59,7 @@ export default () => {
name: node.name,
description: node.description || '',
locationId: node.locationId,
databaseHostId: node.databaseHostId,
fqdn: node.fqdn,
listenPortHTTP: node.listenPortHTTP,
publicPortHTTP: node.publicPortHTTP,
@ -95,7 +98,11 @@ export default () => {
</div>
<div css={tw`mb-6`}>
<LocationSelect defaultLocation={{ id: 1, short: 'local', long: '', createdAt: new Date(), updatedAt: new Date() }}/>
<LocationSelect defaultLocation={node?.relations.location || null}/>
</div>
<div css={tw`mb-6`}>
<DatabaseSelect selected={node?.relations.databaseHost}/>
</div>
<div css={tw`mb-6`}>

View File

@ -1,31 +1,35 @@
import React, { useEffect, useState } from 'react';
import React, { ReactElement, useEffect, useState } from 'react';
import { debounce } from 'debounce';
import styled from 'styled-components/macro';
import tw from 'twin.macro';
import Input from '@/components/elements/Input';
import Label from '@/components/elements/Label';
import InputSpinner from '@/components/elements/InputSpinner';
import { debounce } from 'debounce';
const Dropdown = styled.div<{ expanded: boolean }>`
${tw`absolute mt-1 w-full rounded-md bg-neutral-900 shadow-lg z-10`};
${props => !props.expanded && tw`hidden`};
`;
interface Props<T> {
interface SearchableSelectProps<T> {
id: string;
name: string;
nullable: boolean;
selected: T | null;
items: T[];
setItems: (items: T[]) => void;
onSearch: (query: string) => Promise<void>;
onSelect: (item: T) => void;
getSelectedText: (item: T | null) => string;
children: React.ReactNode;
}
function SearchableSelect<T> ({ id, name, items, setItems, onSearch, children }: Props<T>) {
function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, onSelect, getSelectedText, children }: SearchableSelectProps<T>) {
const [ loading, setLoading ] = useState(false);
const [ expanded, setExpanded ] = useState(false);
@ -51,15 +55,10 @@ function SearchableSelect<T> ({ id, name, items, setItems, onSearch, children }:
onSearch(query).then(() => setLoading(false));
}, 250);
/* const selectItem = (item: any) => {
onSelect(item);
}; */
useEffect(() => {
// setInputText(location.short);
setInputText(getSelectedText(selected) || '');
setExpanded(false);
}, [ ]);
// }, [ location ]);
}, [ selected ]);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
@ -67,7 +66,7 @@ function SearchableSelect<T> ({ id, name, items, setItems, onSearch, children }:
return;
}
// setInputText(location.short);
setInputText(getSelectedText(selected) || '');
setExpanded(false);
};
@ -77,6 +76,16 @@ function SearchableSelect<T> ({ id, name, items, setItems, onSearch, children }:
};
}, [ expanded ]);
const onClick = (item: T) => (e: React.MouseEvent) => {
e.preventDefault();
onSelect(item);
};
// This shit is really stupid but works, so is it really stupid?
const c = React.Children.map(children, child => React.cloneElement(child as ReactElement, {
onClick: onClick.bind(child),
}));
return (
<div>
<Label htmlFor={id}>{name}</Label>
@ -108,7 +117,7 @@ function SearchableSelect<T> ({ id, name, items, setItems, onSearch, children }:
</div>
:
<ul tabIndex={-1} css={tw`max-h-56 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm`}>
{children}
{c}
</ul>
}
</Dropdown>
@ -117,4 +126,49 @@ function SearchableSelect<T> ({ id, name, items, setItems, onSearch, children }:
);
}
interface OptionProps<T> {
id: string | number;
item: T;
active: boolean;
onClick?: (item: T) => (e: React.MouseEvent) => void;
children: React.ReactNode;
}
export function Option<T> ({ id, item, active, onClick, children }: OptionProps<T>) {
if (onClick === undefined) {
// eslint-disable-next-line @typescript-eslint/no-empty-function
onClick = () => () => {};
}
if (active) {
return (
<li id={'select-item-' + id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={onClick(item)}>
<div css={tw`flex items-center`}>
<span css={tw`block font-medium truncate`}>
{children}
</span>
</div>
<span css={tw`absolute inset-y-0 right-0 flex items-center pr-4`}>
<svg css={tw`h-5 w-5 text-primary-400`} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path clipRule="evenodd" fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"/>
</svg>
</span>
</li>
);
}
return (
<li id={'select-item-' + id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={onClick(item)}>
<div css={tw`flex items-center`}>
<span css={tw`block font-normal truncate`}>
{children}
</span>
</div>
</li>
);
}
export default SearchableSelect;