feat(permission): implement new server / channel permission menus

This commit is contained in:
Paul Makles 2022-02-27 23:44:29 +00:00
parent 3632b6b351
commit 041c039827
17 changed files with 587 additions and 311 deletions

2
.env
View file

@ -1,2 +1,2 @@
VITE_API_URL=https://api.revolt.chat VITE_API_URL=http://local.revolt.chat:8000
VITE_THEMES_URL=https://themes.revolt.chat VITE_THEMES_URL=https://themes.revolt.chat

View file

@ -126,6 +126,7 @@
"localforage": "^1.9.0", "localforage": "^1.9.0",
"lodash.defaultsdeep": "^4.6.1", "lodash.defaultsdeep": "^4.6.1",
"lodash.isequal": "^4.5.0", "lodash.isequal": "^4.5.0",
"long": "^5.2.0",
"markdown-it": "^12.0.6", "markdown-it": "^12.0.6",
"markdown-it-emoji": "^2.0.0", "markdown-it-emoji": "^2.0.0",
"markdown-it-sub": "^1.0.0", "markdown-it-sub": "^1.0.0",

View file

@ -2,14 +2,12 @@ import { Check } from "@styled-icons/boxicons-regular";
import { Cog } from "@styled-icons/boxicons-solid"; import { Cog } from "@styled-icons/boxicons-solid";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { ServerPermission } from "revolt.js/dist/api/permissions"; import { Permission } from "revolt.js/dist/api/permissions";
import { Server } from "revolt.js/dist/maps/Servers"; import { Server } from "revolt.js/dist/maps/Servers";
import styled, { css } from "styled-components/macro"; import styled, { css } from "styled-components/macro";
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import { isTouchscreenDevice } from "../../lib/isTouchscreenDevice";
import IconButton from "../ui/IconButton"; import IconButton from "../ui/IconButton";
import Tooltip from "./Tooltip"; import Tooltip from "./Tooltip";
@ -125,7 +123,7 @@ export default observer(({ server }: Props) => {
</Tooltip> </Tooltip>
) : undefined} ) : undefined}
<div className="title">{server.name}</div> <div className="title">{server.name}</div>
{(server.permission & ServerPermission.ManageServer) > 0 && ( {server.havePermission("ManageServer") && (
<Link to={`/server/${server._id}/settings`}> <Link to={`/server/${server._id}/settings`}>
<IconButton> <IconButton>
<Cog size={20} /> <Cog size={20} />

View file

@ -1,7 +1,7 @@
import { Send, ShieldX, HappyBeaming, Box } from "@styled-icons/boxicons-solid"; import { Send, ShieldX, HappyBeaming, Box } from "@styled-icons/boxicons-solid";
import Axios, { CancelTokenSource } from "axios"; import Axios, { CancelTokenSource } from "axios";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { ChannelPermission } from "revolt.js/dist/api/permissions"; import { Permission } from "revolt.js/dist/api/permissions";
import { Channel } from "revolt.js/dist/maps/Channels"; import { Channel } from "revolt.js/dist/maps/Channels";
import styled, { css } from "styled-components/macro"; import styled, { css } from "styled-components/macro";
import { ulid } from "ulid"; import { ulid } from "ulid";
@ -125,6 +125,7 @@ const FileAction = styled.div`
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
}
`; `;
// For sed replacement // For sed replacement
@ -147,7 +148,7 @@ export default observer(({ channel }: Props) => {
const renderer = getRenderer(channel); const renderer = getRenderer(channel);
if (!(channel.permission & ChannelPermission.SendMessage)) { if (!(channel.permission & Permission.SendMessage)) {
return ( return (
<Base> <Base>
<Blocked> <Blocked>
@ -475,7 +476,7 @@ export default observer(({ channel }: Props) => {
setReplies={setReplies} setReplies={setReplies}
/> />
<Base> <Base>
{channel.permission & ChannelPermission.UploadFiles ? ( {channel.permission & Permission.UploadFiles ? (
<FileAction> <FileAction>
<FileUploader <FileUploader
size={24} size={24}

View file

@ -7,7 +7,7 @@ import {
Notification, Notification,
} from "@styled-icons/boxicons-solid"; } from "@styled-icons/boxicons-solid";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { ChannelPermission } from "revolt.js"; import { Permission } from "revolt.js";
import { Message as MessageObject } from "revolt.js/dist/maps/Messages"; import { Message as MessageObject } from "revolt.js/dist/maps/Messages";
import styled from "styled-components"; import styled from "styled-components";
@ -131,8 +131,7 @@ export const MessageOverlayBar = observer(({ message, queued }: Props) => {
)} )}
{isAuthor || {isAuthor ||
(message.channel && (message.channel &&
message.channel.permission & message.channel.permission & Permission.ManageMessages) ? (
ChannelPermission.ManageMessages) ? (
<Tooltip content="Delete"> <Tooltip content="Delete">
<Entry <Entry
onClick={(e) => onClick={(e) =>

View file

@ -4,12 +4,14 @@ import { useContext } from "preact/hooks";
import { import {
ClientStatus, ClientStatus,
StatusContext, StatusContext,
useClient,
} from "../../../context/revoltjs/RevoltClient"; } from "../../../context/revoltjs/RevoltClient";
import Banner from "../../ui/Banner"; import Banner from "../../ui/Banner";
export default function ConnectionStatus() { export default function ConnectionStatus() {
const status = useContext(StatusContext); const status = useContext(StatusContext);
const client = useClient();
if (status === ClientStatus.OFFLINE) { if (status === ClientStatus.OFFLINE) {
return ( return (
@ -20,7 +22,8 @@ export default function ConnectionStatus() {
} else if (status === ClientStatus.DISCONNECTED) { } else if (status === ClientStatus.DISCONNECTED) {
return ( return (
<Banner> <Banner>
<Text id="app.special.status.disconnected" /> <Text id="app.special.status.disconnected" /> <br />
<a onClick={() => client.websocket.connect()}>Reconnect</a>
</Banner> </Banner>
); );
} else if (status === ClientStatus.CONNECTING) { } else if (status === ClientStatus.CONNECTING) {

View file

@ -0,0 +1,79 @@
import { Check, Square, X } from "@styled-icons/boxicons-regular";
import styled, { css } from "styled-components";
type State = "Allow" | "Neutral" | "Deny";
const SwitchContainer = styled.div.attrs({
role: "radiogroup",
"aria-orientiation": "horizontal",
})`
flex-shrink: 0;
display: flex;
margin: 4px 16px;
overflow: hidden;
border-radius: var(--border-radius);
background: var(--secondary-background);
border: 2px solid var(--tertiary-background);
`;
const Switch = styled.div.attrs({
role: "radio",
})<{ state: State; selected: boolean }>`
padding: 4px;
cursor: pointer;
transition: 0.2s ease all;
color: ${(props) =>
props.state === "Allow"
? "var(--success)"
: props.state === "Deny"
? "var(--error)"
: "var(--tertiary-foreground)"};
${(props) =>
props.selected &&
css`
color: white;
background: ${props.state === "Allow"
? "var(--success)"
: props.state === "Deny"
? "var(--error)"
: "var(--primary-background)"};
`}
&:hover {
filter: brightness(0.8);
}
`;
interface Props {
state: State;
onChange: (state: State) => void;
}
export function OverrideSwitch({ state, onChange }: Props) {
return (
<SwitchContainer>
<Switch
onClick={() => onChange("Deny")}
state="Deny"
selected={state === "Deny"}>
<X size={24} />
</Switch>
<Switch
onClick={() => onChange("Neutral")}
state="Neutral"
selected={state === "Neutral"}>
<Square size={24} />
</Switch>
<Switch
onClick={() => onChange("Allow")}
state="Allow"
selected={state === "Allow"}>
<Check size={24} />
</Switch>
</SwitchContainer>
);
}

View file

@ -0,0 +1,33 @@
import { OverrideField } from "revolt-api/types/_common";
import { Permission } from "revolt.js";
import { PermissionSelect } from "./PermissionSelect";
interface Props {
value: OverrideField | number;
onChange: (v: OverrideField | number) => void;
filter?: (keyof typeof Permission)[];
}
export function PermissionList({ value, onChange, filter }: Props) {
return (
<>
{(Object.keys(Permission) as (keyof typeof Permission)[])
.filter(
(key) =>
key !== "GrantAllSafe" &&
(!filter || filter.includes(key)),
)
.map((x) => (
<PermissionSelect
id={x}
key={x}
permission={Permission[x]}
value={value}
onChange={onChange}
/>
))}
</>
);
}

View file

@ -0,0 +1,124 @@
import Long from "long";
import { OverrideField } from "revolt-api/types/_common";
import { Permission } from "revolt.js";
import styled from "styled-components";
import { Text } from "preact-i18n";
import { useMemo } from "preact/hooks";
import Checkbox from "../../ui/Checkbox";
import { OverrideSwitch } from "./OverrideSwitch";
interface PermissionSelectProps {
id: keyof typeof Permission;
permission: number;
value: OverrideField | number;
onChange: (value: OverrideField | number) => void;
}
type State = "Allow" | "Neutral" | "Deny";
const PermissionEntry = styled.label`
width: 100%;
margin: 8px 0;
display: flex;
font-size: 1.1em;
align-items: center;
.title {
flex-grow: 1;
display: flex;
flex-direction: column;
}
.description {
font-size: 0.8em;
color: var(--secondary-foreground);
}
`;
export function PermissionSelect({
id,
permission,
value,
onChange,
}: PermissionSelectProps) {
const state: State = useMemo(() => {
if (typeof value === "object") {
if (Long.fromNumber(value.d).and(permission).eq(permission)) {
return "Deny";
}
if (Long.fromNumber(value.a).and(permission).eq(permission)) {
return "Allow";
}
return "Neutral";
} else {
if (Long.fromNumber(value).and(permission).eq(permission)) {
return "Allow";
}
return "Neutral";
}
}, [value]);
function onSwitch(state: State) {
if (typeof value !== "object") throw "!";
// Convert to Long so we can do bitwise ops.
let allow = Long.fromNumber(value.a);
let deny = Long.fromNumber(value.d);
// Clear the current permission value.
if (allow.and(permission).eq(permission)) {
allow = allow.xor(permission);
}
if (deny.and(permission).eq(permission)) {
deny = deny.xor(permission);
}
// Apply the current permission state.
if (state === "Allow") {
allow = allow.or(permission);
}
if (state === "Deny") {
deny = deny.or(permission);
}
// Invoke state change.
onChange({
a: allow.toNumber(),
d: deny.toNumber(),
});
}
return (
<PermissionEntry>
<span class="title">
<Text id={`permissions.server.${id}.t`}>{id}</Text>
<span class="description">
<Text id={`permissions.server.${id}.d`} />
</span>
</span>
{typeof value === "object" ? (
<OverrideSwitch state={state} onChange={onSwitch} />
) : (
<Checkbox
checked={state === "Allow"}
onChange={() =>
onChange(
Long.fromNumber(value, false)
.xor(permission)
.toNumber(),
)
}
/>
)}
</PermissionEntry>
);
}

View file

@ -0,0 +1,35 @@
import { Role } from "revolt-api/types/Servers";
import Checkbox from "../../ui/Checkbox";
export type RoleOrDefault = (
| Role
| {
name: string;
permissions: number;
colour?: string;
hoist?: boolean;
rank?: number;
}
) & { id: string };
interface Props {
selected: string;
onSelect: (id: string) => void;
roles: RoleOrDefault[];
}
export function RoleSelection({ selected, onSelect, roles }: Props) {
return (
<>
{roles.map((x) => (
<Checkbox
checked={x.id === selected}
onChange={() => onSelect(x.id)}>
{x.name}
</Checkbox>
))}
</>
);
}

View file

@ -0,0 +1,22 @@
import Tip from "../../../components/ui/Tip";
import Button from "../../ui/Button";
interface Props {
save: () => void;
}
export function UnsavedChanges({ save }: Props) {
return (
<Tip hideSeparator>
<span
style={{
display: "flex",
alignItems: "center",
gap: "8px",
}}>
You have unsaved changes!
<Button onClick={save}>Save</Button>
</span>
</Tip>
);
}

View file

@ -89,7 +89,7 @@ export interface CheckboxProps {
disabled?: boolean; disabled?: boolean;
contrast?: boolean; contrast?: boolean;
className?: string; className?: string;
children: Children; children?: Children;
description?: Children; description?: Children;
onChange: (state: boolean) => void; onChange: (state: boolean) => void;
} }

View file

@ -14,11 +14,7 @@ import { Cog, UserVoice } from "@styled-icons/boxicons-solid";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { Attachment } from "revolt-api/types/Autumn"; import { Attachment } from "revolt-api/types/Autumn";
import { Presence, RelationshipStatus } from "revolt-api/types/Users"; import { Presence, RelationshipStatus } from "revolt-api/types/Users";
import { import { Permission, UserPermission } from "revolt.js/dist/api/permissions";
ChannelPermission,
ServerPermission,
UserPermission,
} from "revolt.js/dist/api/permissions";
import { Channel } from "revolt.js/dist/maps/Channels"; import { Channel } from "revolt.js/dist/maps/Channels";
import { Message } from "revolt.js/dist/maps/Messages"; import { Message } from "revolt.js/dist/maps/Messages";
import { Server } from "revolt.js/dist/maps/Servers"; import { Server } from "revolt.js/dist/maps/Servers";
@ -505,9 +501,8 @@ export default function ContextMenus() {
if (server_list) { if (server_list) {
const server = client.servers.get(server_list)!; const server = client.servers.get(server_list)!;
const permissions = server.permission;
if (server) { if (server) {
if (permissions & ServerPermission.ManageChannels) { if (server.havePermission("ManageChannel")) {
generateAction({ generateAction({
action: "create_category", action: "create_category",
target: server, target: server,
@ -517,7 +512,8 @@ export default function ContextMenus() {
target: server, target: server,
}); });
} }
if (permissions & ServerPermission.ManageServer)
if (server.havePermission("ManageServer"))
generateAction({ generateAction({
action: "open_server_settings", action: "open_server_settings",
id: server_list, id: server_list,
@ -673,9 +669,7 @@ export default function ContextMenus() {
userId !== uid && userId !== uid &&
uid !== server.owner uid !== server.owner
) { ) {
if ( if (serverPermissions & Permission.KickMembers)
serverPermissions & ServerPermission.KickMembers
)
generateAction( generateAction(
{ {
action: "kick_member", action: "kick_member",
@ -688,7 +682,7 @@ export default function ContextMenus() {
"var(--error)", // the only relevant part really "var(--error)", // the only relevant part really
); );
if (serverPermissions & ServerPermission.BanMembers) if (serverPermissions & Permission.BanMembers)
generateAction( generateAction(
{ {
action: "ban_member", action: "ban_member",
@ -718,8 +712,7 @@ export default function ContextMenus() {
if (message && !queued) { if (message && !queued) {
const sendPermission = const sendPermission =
message.channel && message.channel &&
message.channel.permission & message.channel.permission & Permission.SendMessage;
ChannelPermission.SendMessage;
if (sendPermission) { if (sendPermission) {
generateAction({ generateAction({
@ -759,8 +752,7 @@ export default function ContextMenus() {
if ( if (
message.author_id === userId || message.author_id === userId ||
channelPermissions & channelPermissions & Permission.ManageMessages
ChannelPermission.ManageMessages
) { ) {
generateAction({ generateAction({
action: "delete_message", action: "delete_message",
@ -903,7 +895,7 @@ export default function ContextMenus() {
case "VoiceChannel": case "VoiceChannel":
if ( if (
channelPermissions & channelPermissions &
ChannelPermission.InviteOthers Permission.InviteOthers
) { ) {
generateAction({ generateAction({
action: "create_invite", action: "create_invite",
@ -913,7 +905,7 @@ export default function ContextMenus() {
if ( if (
serverPermissions & serverPermissions &
ServerPermission.ManageServer Permission.ManageServer
) )
generateAction( generateAction(
{ {
@ -926,7 +918,7 @@ export default function ContextMenus() {
if ( if (
serverPermissions & serverPermissions &
ServerPermission.ManageChannels Permission.ManageChannel
) )
generateAction({ generateAction({
action: "delete_channel", action: "delete_channel",
@ -958,20 +950,15 @@ export default function ContextMenus() {
); );
if ( if (
serverPermissions & serverPermissions & Permission.ChangeNickname ||
ServerPermission.ChangeNickname || serverPermissions & Permission.ChangeAvatar
serverPermissions &
ServerPermission.ChangeAvatar
) )
generateAction( generateAction(
{ action: "edit_identity", target: server }, { action: "edit_identity", target: server },
"edit_identity", "edit_identity",
); );
if ( if (serverPermissions & Permission.ManageServer)
serverPermissions &
ServerPermission.ManageServer
)
generateAction( generateAction(
{ {
action: "open_server_settings", action: "open_server_settings",

View file

@ -1,5 +1,5 @@
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { ServerPermission } from "revolt.js"; import { Permission } from "revolt.js";
import { Route } from "revolt.js/dist/api/routes"; import { Route } from "revolt.js/dist/api/routes";
import styled from "styled-components/macro"; import styled from "styled-components/macro";
@ -74,8 +74,7 @@ export default function InviteBot() {
{[...client.servers.values()] {[...client.servers.values()]
.filter( .filter(
(x) => (x) =>
x.permission & x.permission & Permission.ManageServer,
ServerPermission.ManageServer,
) )
.map((server) => ( .map((server) => (
<option value={server._id} key={server._id}> <option value={server._id} key={server._id}>

View file

@ -1,23 +1,114 @@
import isEqual from "lodash.isequal";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { import { OverrideField } from "revolt-api/types/_common";
ChannelPermission,
DEFAULT_PERMISSION_DM,
} from "revolt.js/dist/api/permissions";
import { Channel } from "revolt.js/dist/maps/Channels"; import { Channel } from "revolt.js/dist/maps/Channels";
import { useEffect, useState } from "preact/hooks"; import { useLayoutEffect, useState } from "preact/hooks";
import Button from "../../../components/ui/Button"; import { PermissionList } from "../../../components/settings/roles/PermissionList";
import Checkbox from "../../../components/ui/Checkbox"; import {
import Tip from "../../../components/ui/Tip"; RoleOrDefault,
RoleSelection,
} from "../../../components/settings/roles/RoleSelection";
import { UnsavedChanges } from "../../../components/settings/roles/UnsavedChanges";
import { useRoles } from "../server/Roles";
interface Props { interface Props {
channel: Channel; channel: Channel;
} }
// ! FIXME: bad code :)
export default observer(({ channel }: Props) => { export default observer(({ channel }: Props) => {
// Consolidate all permissions that we can change right now.
const currentRoles =
channel.channel_type === "Group"
? ([
{
id: "default",
name: "Default",
permissions: channel.permissions,
},
] as RoleOrDefault[])
: (useRoles(channel.server!).map((role) => {
return {
...role,
permissions: (role.id === "default"
? channel.default_permissions
: channel.role_permissions?.[role.id]) ?? {
a: 0,
d: 0,
},
};
}) as RoleOrDefault[]);
// Keep track of whatever role we're editing right now.
const [selected, setSelected] = useState("default"); const [selected, setSelected] = useState("default");
const [value, setValue] = useState<OverrideField | number | undefined>(
undefined,
);
const currentPermission = currentRoles.find(
(x) => x.id === selected,
)!.permissions;
const currentValue = value ?? currentPermission;
// If a role gets deleted, unselect it immediately.
useLayoutEffect(() => {
if (!channel?.server?.roles) return;
if (!channel.server.roles[selected]) {
setSelected("default");
}
}, [channel.server?.roles]);
// Upload new role information to server.
function save() {
channel.setPermissions(
selected,
typeof currentValue === "number"
? currentValue
: {
allow: currentValue.a,
deny: currentValue.d,
},
);
}
return (
<div style={{ height: "100%", overflowY: "scroll" }}>
<h1>Select Role</h1>
<RoleSelection
selected={selected}
onSelect={(id) => {
setValue(undefined);
setSelected(id);
}}
roles={currentRoles}
/>
{!isEqual(currentPermission, currentValue) && (
<>
<hr />
<UnsavedChanges save={save} />
</>
)}
<hr />
<h1>Edit Permissions</h1>
<PermissionList
value={currentValue}
onChange={setValue}
filter={[
"ViewChannel",
"ReadMessageHistory",
"SendMessage",
"ManageMessages",
"ManageWebhooks",
"InviteOthers",
"SendEmbeds",
"UploadFiles",
"Masquerade",
]}
/>
</div>
);
/*const [selected, setSelected] = useState("default");
type R = { name: string; permissions: number }; type R = { name: string; permissions: number };
const roles: { [key: string]: R } = {}; const roles: { [key: string]: R } = {};
@ -98,5 +189,5 @@ export default observer(({ channel }: Props) => {
click here to save permissions for role click here to save permissions for role
</Button> </Button>
</div> </div>
); );*/
}); });

View file

@ -1,21 +1,8 @@
import { Plus } from "@styled-icons/boxicons-regular";
import isEqual from "lodash.isequal"; import isEqual from "lodash.isequal";
import { observer } from "mobx-react-lite"; import { observer } from "mobx-react-lite";
import { ChannelPermission, ServerPermission } from "revolt.js";
import { Server } from "revolt.js/dist/maps/Servers"; import { Server } from "revolt.js/dist/maps/Servers";
import styles from "./Panes.module.scss"; import { useLayoutEffect, useMemo, useState } from "preact/hooks";
import { Text } from "preact-i18n";
import {
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "preact/hooks";
import { useIntermediate } from "../../../context/intermediate/Intermediate";
import { AppContext } from "../../../context/revoltjs/RevoltClient";
import Button from "../../../components/ui/Button"; import Button from "../../../components/ui/Button";
import Checkbox from "../../../components/ui/Checkbox"; import Checkbox from "../../../components/ui/Checkbox";
@ -23,154 +10,108 @@ import ColourSwatches from "../../../components/ui/ColourSwatches";
import InputBox from "../../../components/ui/InputBox"; import InputBox from "../../../components/ui/InputBox";
import Overline from "../../../components/ui/Overline"; import Overline from "../../../components/ui/Overline";
import ButtonItem from "../../../components/navigation/items/ButtonItem"; import { PermissionList } from "../../../components/settings/roles/PermissionList";
import {
RoleOrDefault,
RoleSelection,
} from "../../../components/settings/roles/RoleSelection";
import { UnsavedChanges } from "../../../components/settings/roles/UnsavedChanges";
interface Props { interface Props {
server: Server; server: Server;
} }
const I32ToU32 = (arr: number[]) => arr.map((x) => x >>> 0); export function useRoles(server: Server) {
return useMemo(
// ! FIXME: bad code :) () =>
export const Roles = observer(({ server }: Props) => { [
const client = useContext(AppContext); // Pull in known server roles.
const [role, setRole] = useState("default"); ...server.orderedRoles,
const { openScreen } = useIntermediate(); // Include the default server permissions.
const roles = server.roles || {}; {
id: "default",
if (role !== "default" && typeof roles[role] === "undefined") { name: "Default",
useEffect(() => setRole("default"), [role]); permissions: server.default_permissions,
return null;
}
const clientPermissions = client.servers.get(server._id)!.permission;
const {
name: roleName,
colour: roleColour,
hoist: roleHoist,
rank: roleRank,
permissions,
} = roles[role] ?? {};
const getPermissions = useCallback(
(id: string) => {
return I32ToU32(
id === "default"
? server.default_permissions
: roles[id].permissions,
);
}, },
[roles, server], ] as RoleOrDefault[],
[server.roles, server.default_permissions],
); );
}
const [perm, setPerm] = useState(getPermissions(role)); export const Roles = observer(({ server }: Props) => {
const [name, setName] = useState(roleName); // Consolidate all permissions that we can change right now.
const [hoist, setHoist] = useState(roleHoist); const currentRoles = useRoles(server);
const [rank, setRank] = useState(roleRank);
const [colour, setColour] = useState(roleColour);
useEffect( // Keep track of whatever role we're editing right now.
() => setPerm(getPermissions(role)), const [selected, setSelected] = useState("default");
[getPermissions, role, permissions], const [value, setValue] = useState<Partial<RoleOrDefault>>({});
const currentRole = currentRoles.find((x) => x.id === selected)!;
const currentRoleValue = { ...currentRole, ...value };
// If a role gets deleted, unselect it immediately.
useLayoutEffect(() => {
if (!server.roles) return;
if (!server.roles[selected]) {
setSelected("default");
}
}, [server.roles]);
// Calculate permissions we have access to on this server.
const current = server.permission;
// Upload new role information to server.
function save() {
const { permissions: permsCurrent, ...current } = currentRole;
const { permissions: permsValue, ...value } = currentRoleValue;
if (!isEqual(permsCurrent, permsValue)) {
server.setPermissions(
selected,
typeof permsValue === "number"
? permsValue
: {
allow: permsValue.a,
deny: permsValue.d,
},
); );
useEffect(() => setName(roleName), [role, roleName]);
useEffect(() => setHoist(roleHoist), [role, roleHoist]);
useEffect(() => setRank(roleRank), [role, roleRank]);
useEffect(() => setColour(roleColour), [role, roleColour]);
const modified =
!isEqual(perm, getPermissions(role)) ||
!isEqual(name, roleName) ||
!isEqual(colour, roleColour) ||
!isEqual(hoist, roleHoist) ||
!isEqual(rank, roleRank);
const save = () => {
if (!isEqual(perm, getPermissions(role))) {
server.setPermissions(role, {
server: perm[0],
channel: perm[1],
});
} }
if ( if (!isEqual(current, value)) {
!isEqual(name, roleName) || server.editRole(selected, value);
!isEqual(colour, roleColour) || }
!isEqual(hoist, roleHoist) ||
!isEqual(rank, roleRank)
) {
server.editRole(role, { name, colour, hoist, rank });
} }
};
const deleteRole = () => { // Delete the role from this server.
setRole("default"); function deleteRole() {
server.deleteRole(role); setSelected("default");
}; server.deleteRole(selected);
}
return ( return (
<div className={styles.roles}> <div style={{ height: "100%", overflowY: "scroll" }}>
<div className={styles.list}> <h1>Select Role</h1>
<div className={styles.title}> <RoleSelection
<h1> selected={selected}
<Text id="app.settings.server_pages.roles.title" /> onSelect={(id) => {
</h1> setValue({});
<Plus setSelected(id);
size={22} }}
onClick={() => roles={currentRoles}
openScreen({
id: "special_input",
type: "create_role",
server,
callback: (id) => setRole(id),
})
}
/> />
</div> {selected !== "default" && (
{["default", ...Object.keys(roles)].map((id) =>
id === "default" ? (
<ButtonItem
active={role === "default"}
onClick={() => setRole("default")}>
<Text id="app.settings.permissions.default_role" />
</ButtonItem>
) : (
<ButtonItem
key={id}
active={role === id}
onClick={() => setRole(id)}
style={{
color: roles[id].colour,
}}>
{roles[id].name}
</ButtonItem>
),
)}
</div>
<div className={styles.permissions}>
<div className={styles.title}>
<h2>
{role === "default" ? (
<Text id="app.settings.permissions.default_role" />
) : (
roles[role].name
)}
</h2>
<Button contrast disabled={!modified} onClick={save}>
Save
</Button>
</div>
{role !== "default" && (
<> <>
<hr />
<h1>Edit Role</h1>
<section> <section>
<Overline type="subtle">Role Name</Overline> <Overline type="subtle">Role Name</Overline>
<p> <p>
<InputBox <InputBox
value={name} value={currentRoleValue.name}
onChange={(e) => onChange={(e) =>
setName(e.currentTarget.value) setValue({
...value,
name: e.currentTarget.value,
})
} }
contrast contrast
/> />
@ -180,8 +121,10 @@ export const Roles = observer(({ server }: Props) => {
<Overline type="subtle">Role Colour</Overline> <Overline type="subtle">Role Colour</Overline>
<p> <p>
<ColourSwatches <ColourSwatches
value={colour ?? "gray"} value={currentRoleValue.colour ?? "gray"}
onChange={(value) => setColour(value)} onChange={(colour) =>
setValue({ ...value, colour })
}
/> />
</p> </p>
</section> </section>
@ -189,93 +132,27 @@ export const Roles = observer(({ server }: Props) => {
<Overline type="subtle">Role Options</Overline> <Overline type="subtle">Role Options</Overline>
<p> <p>
<Checkbox <Checkbox
checked={hoist ?? false} checked={currentRoleValue.hoist ?? false}
onChange={(v) => setHoist(v)} onChange={(hoist) =>
setValue({ ...value, hoist })
}
description="Display this role above others."> description="Display this role above others.">
Hoist Role Hoist Role
</Checkbox> </Checkbox>
</p> </p>
</section> </section>
</>
)}
<section>
<Overline type="subtle">
<Text id="app.settings.permissions.server" />
</Overline>
{Object.keys(ServerPermission).map((key) => {
if (key === "View") return;
const value =
ServerPermission[
key as keyof typeof ServerPermission
];
return (
<Checkbox
key={key}
checked={(perm[0] & value) > 0}
onChange={() =>
setPerm([perm[0] ^ value, perm[1]])
}
disabled={!(clientPermissions & value)}
description={
<Text id={`permissions.server.${key}.d`} />
}>
<Text id={`permissions.server.${key}.t`} />
</Checkbox>
);
})}
</section>
<section>
<Overline type="subtle">
<Text id="app.settings.permissions.channel" />
</Overline>
{Object.keys(ChannelPermission).map((key) => {
if (key === "ManageChannel") return;
const value =
ChannelPermission[
key as keyof typeof ChannelPermission
];
return (
<Checkbox
key={key}
checked={((perm[1] >>> 0) & value) > 0}
onChange={() =>
setPerm([perm[0], perm[1] ^ value])
}
disabled={
key === "View" ||
!(clientPermissions & value)
}
description={
<Text id={`permissions.channel.${key}.d`} />
}>
<Text id={`permissions.channel.${key}.t`} />
</Checkbox>
);
})}
</section>
<div className={styles.actions}>
<Button contrast disabled={!modified} onClick={save}>
Save
</Button>
{role !== "default" && (
<Button contrast error onClick={deleteRole}>
Delete
</Button>
)}
</div>
{role !== "default" && (
<>
<section> <section>
<Overline type="subtle"> <Overline type="subtle">
Experimental Role Ranking Experimental Role Ranking
</Overline> </Overline>
<p> <p>
<InputBox <InputBox
value={rank ?? 0} value={currentRoleValue.rank ?? 0}
onChange={(e) => onChange={(e) =>
setRank(parseInt(e.currentTarget.value)) setValue({
...value,
rank: parseInt(e.currentTarget.value),
})
} }
contrast contrast
/> />
@ -283,7 +160,29 @@ export const Roles = observer(({ server }: Props) => {
</section> </section>
</> </>
)} )}
</div> {!isEqual(currentRole, currentRoleValue) && (
<>
<hr />
<UnsavedChanges save={save} />
</>
)}
<hr />
<h1>Edit Permissions</h1>
<PermissionList
value={currentRoleValue.permissions}
onChange={(permissions) =>
setValue({ ...value, permissions } as RoleOrDefault)
}
/>
{selected !== "default" && (
<>
<hr />
<h1>Danger Zone</h1>
<Button contrast error onClick={deleteRole}>
Delete Role
</Button>
</>
)}
</div> </div>
); );
}); });

View file

@ -3656,6 +3656,11 @@ lodash@4.17.21, lodash@^4.17.11, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
long@^5.2.0:
version "5.2.0"
resolved "https://registry.yarnpkg.com/long/-/long-5.2.0.tgz#2696dadf4b4da2ce3f6f6b89186085d94d52fd61"
integrity sha512-9RTUNjK60eJbx3uz+TEGF7fUr29ZDxR5QzXcyDpeSfeH28S9ycINflOgOlppit5U+4kNTe83KQnMEerw7GmE8w==
loose-envify@^1.2.0, loose-envify@^1.3.1, loose-envify@^1.4.0: loose-envify@^1.2.0, loose-envify@^1.3.1, loose-envify@^1.4.0:
version "1.4.0" version "1.4.0"
resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf"