add-privileged-users-in-room (#9596)

This commit is contained in:
Marco Bartelt 2022-12-08 12:40:31 +01:00 committed by GitHub
parent 982c83d2a8
commit 95ac957fa4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 927 additions and 3 deletions

View file

@ -0,0 +1,248 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { useState, ReactNode, ChangeEvent, KeyboardEvent, useRef, ReactElement } from 'react';
import classNames from 'classnames';
import Autocompleter from "../../autocomplete/AutocompleteProvider";
import { Key } from '../../Keyboard';
import { ICompletion } from '../../autocomplete/Autocompleter';
import AccessibleButton from '../../components/views/elements/AccessibleButton';
import { Icon as PillRemoveIcon } from '../../../res/img/icon-pill-remove.svg';
import { Icon as SearchIcon } from '../../../res/img/element-icons/roomlist/search.svg';
import useFocus from "../../hooks/useFocus";
interface AutocompleteInputProps {
provider: Autocompleter;
placeholder: string;
selection: ICompletion[];
onSelectionChange: (selection: ICompletion[]) => void;
maxSuggestions?: number;
renderSuggestion?: (s: ICompletion) => ReactElement;
renderSelection?: (m: ICompletion) => ReactElement;
additionalFilter?: (suggestion: ICompletion) => boolean;
}
export const AutocompleteInput: React.FC<AutocompleteInputProps> = ({
provider,
renderSuggestion,
renderSelection,
maxSuggestions = 5,
placeholder,
onSelectionChange,
selection,
additionalFilter,
}) => {
const [query, setQuery] = useState<string>('');
const [suggestions, setSuggestions] = useState<ICompletion[]>([]);
const [isFocused, onFocusChangeHandlerFunctions] = useFocus();
const editorContainerRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<HTMLInputElement>(null);
const focusEditor = () => {
editorRef?.current?.focus();
};
const onQueryChange = async (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value.trim();
setQuery(value);
let matches = await provider.getCompletions(
query,
{ start: query.length, end: query.length },
true,
maxSuggestions,
);
if (additionalFilter) {
matches = matches.filter(additionalFilter);
}
setSuggestions(matches);
};
const onClickInputArea = () => {
focusEditor();
};
const onKeyDown = (e: KeyboardEvent) => {
const hasModifiers = e.ctrlKey || e.shiftKey || e.metaKey;
// when the field is empty and the user hits backspace remove the right-most target
if (!query && selection.length > 0 && e.key === Key.BACKSPACE && !hasModifiers) {
removeSelection(selection[selection.length - 1]);
}
};
const toggleSelection = (completion: ICompletion) => {
const newSelection = [...selection];
const index = selection.findIndex(selection => selection.completionId === completion.completionId);
if (index >= 0) {
newSelection.splice(index, 1);
} else {
newSelection.push(completion);
}
onSelectionChange(newSelection);
focusEditor();
};
const removeSelection = (completion: ICompletion) => {
const newSelection = [...selection];
const index = selection.findIndex(selection => selection.completionId === completion.completionId);
if (index >= 0) {
newSelection.splice(index, 1);
onSelectionChange(newSelection);
}
};
const hasPlaceholder = (): boolean => selection.length === 0 && query.length === 0;
return (
<div className="mx_AutocompleteInput">
<div
ref={editorContainerRef}
className={classNames({
'mx_AutocompleteInput_editor': true,
'mx_AutocompleteInput_editor--focused': isFocused,
'mx_AutocompleteInput_editor--has-suggestions': suggestions.length > 0,
})}
onClick={onClickInputArea}
data-testid="autocomplete-editor"
>
<SearchIcon className="mx_AutocompleteInput_search_icon" width={16} height={16} />
{
selection.map(item => (
<SelectionItem
key={item.completionId}
item={item}
onClick={removeSelection}
render={renderSelection}
/>
))
}
<input
ref={editorRef}
type="text"
onKeyDown={onKeyDown}
onChange={onQueryChange}
value={query}
autoComplete="off"
placeholder={hasPlaceholder() ? placeholder : undefined}
data-testid="autocomplete-input"
{...onFocusChangeHandlerFunctions}
/>
</div>
{
(isFocused && suggestions.length) ? (
<div
className="mx_AutocompleteInput_matches"
style={{ top: editorContainerRef.current?.clientHeight }}
data-testid="autocomplete-matches"
>
{
suggestions.map((item) => (
<SuggestionItem
key={item.completionId}
item={item}
selection={selection}
onClick={toggleSelection}
render={renderSuggestion}
/>
))
}
</div>
) : null
}
</div>
);
};
type SelectionItemProps = {
item: ICompletion;
onClick: (completion: ICompletion) => void;
render?: (completion: ICompletion) => ReactElement;
};
const SelectionItem: React.FC<SelectionItemProps> = ({ item, onClick, render }) => {
const withContainer = (children: ReactNode): ReactElement => (
<span
className='mx_AutocompleteInput_editor_selection'
data-testid={`autocomplete-selection-item-${item.completionId}`}
>
<span className='mx_AutocompleteInput_editor_selection_pill'>
{ children }
</span>
<AccessibleButton
className='mx_AutocompleteInput_editor_selection_remove_button'
onClick={() => onClick(item)}
data-testid={`autocomplete-selection-remove-button-${item.completionId}`}
>
<PillRemoveIcon width={8} height={8} />
</AccessibleButton>
</span>
);
if (render) {
return withContainer(render(item));
}
return withContainer(
<span className='mx_AutocompleteInput_editor_selection_text'>{ item.completion }</span>,
);
};
type SuggestionItemProps = {
item: ICompletion;
selection: ICompletion[];
onClick: (completion: ICompletion) => void;
render?: (completion: ICompletion) => ReactElement;
};
const SuggestionItem: React.FC<SuggestionItemProps> = ({ item, selection, onClick, render }) => {
const isSelected = selection.some(selection => selection.completionId === item.completionId);
const classes = classNames({
'mx_AutocompleteInput_suggestion': true,
'mx_AutocompleteInput_suggestion--selected': isSelected,
});
const withContainer = (children: ReactNode): ReactElement => (
<div
className={classes}
// `onClick` cannot be used here as it would lead to focus loss and closing the suggestion list.
onMouseDown={(event) => {
event.preventDefault();
onClick(item);
}}
data-testid={`autocomplete-suggestion-item-${item.completionId}`}
>
{ children }
</div>
);
if (render) {
return withContainer(render(item));
}
return withContainer(
<>
<span className='mx_AutocompleteInput_suggestion_title'>{ item.completion }</span>
<span className='mx_AutocompleteInput_suggestion_description'>{ item.completionId }</span>
</>,
);
};

View file

@ -174,7 +174,15 @@ export default class PowerSelector extends React.Component<IProps, IState> {
});
options.push({ value: CUSTOM_VALUE, text: _t("Custom level") });
const optionsElements = options.map((op) => {
return <option value={op.value} key={op.value}>{ op.text }</option>;
return (
<option
value={op.value}
key={op.value}
data-testid={`power-level-option-${op.value}`}
>
{ op.text }
</option>
);
});
picker = (
@ -184,6 +192,7 @@ export default class PowerSelector extends React.Component<IProps, IState> {
onChange={this.onSelectChange}
value={String(this.state.selectValue)}
disabled={this.props.disabled}
data-testid='power-level-select-element'
>
{ optionsElements }
</Field>

View file

@ -0,0 +1,132 @@
/*
Copyright 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { FormEvent, useCallback, useContext, useRef, useState } from 'react';
import { Room } from 'matrix-js-sdk/src/models/room';
import { EventType } from "matrix-js-sdk/src/@types/event";
import { _t } from "../../../languageHandler";
import { ICompletion } from '../../../autocomplete/Autocompleter';
import UserProvider from "../../../autocomplete/UserProvider";
import { AutocompleteInput } from "../../structures/AutocompleteInput";
import PowerSelector from "../elements/PowerSelector";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import AccessibleButton from "../elements/AccessibleButton";
import Modal from "../../../Modal";
import ErrorDialog from "../dialogs/ErrorDialog";
import SettingsFieldset from "./SettingsFieldset";
interface AddPrivilegedUsersProps {
room: Room;
defaultUserLevel: number;
}
export const AddPrivilegedUsers: React.FC<AddPrivilegedUsersProps> = ({ room, defaultUserLevel }) => {
const client = useContext(MatrixClientContext);
const userProvider = useRef(new UserProvider(room));
const [isLoading, setIsLoading] = useState<boolean>(false);
const [powerLevel, setPowerLevel] = useState<number>(defaultUserLevel);
const [selectedUsers, setSelectedUsers] = useState<ICompletion[]>([]);
const hasLowerOrEqualLevelThanDefaultLevelFilter = useCallback(
(user: ICompletion) => hasLowerOrEqualLevelThanDefaultLevel(room, user, defaultUserLevel),
[room, defaultUserLevel],
);
const onSubmit = async (event: FormEvent) => {
event.preventDefault();
setIsLoading(true);
const userIds = getUserIdsFromCompletions(selectedUsers);
const powerLevelEvent = room.currentState.getStateEvents(EventType.RoomPowerLevels, "");
// `RoomPowerLevels` event should exist, but technically it is not guaranteed.
if (powerLevelEvent === null) {
Modal.createDialog(ErrorDialog, {
title: _t("Error"),
description: _t("Failed to change power level"),
});
return;
}
try {
await client.setPowerLevel(room.roomId, userIds, powerLevel, powerLevelEvent);
setSelectedUsers([]);
setPowerLevel(defaultUserLevel);
} catch (error) {
Modal.createDialog(ErrorDialog, {
title: _t("Error"),
description: _t("Failed to change power level"),
});
} finally {
setIsLoading(false);
}
};
return (
<form style={{ display: 'flex' }} onSubmit={onSubmit}>
<SettingsFieldset
legend={_t('Add privileged users')}
description={_t('Give one or multiple users in this room more privileges')}
style={{ flexGrow: 1 }}
>
<AutocompleteInput
provider={userProvider.current}
placeholder={_t("Search users in this room…")}
onSelectionChange={setSelectedUsers}
selection={selectedUsers}
additionalFilter={hasLowerOrEqualLevelThanDefaultLevelFilter}
/>
<PowerSelector value={powerLevel} onChange={setPowerLevel} />
<AccessibleButton
type='submit'
element='button'
kind='primary'
disabled={!selectedUsers.length || isLoading}
onClick={null}
data-testid='add-privileged-users-submit-button'
>
{ _t('Apply') }
</AccessibleButton>
</SettingsFieldset>
</form>
);
};
export const hasLowerOrEqualLevelThanDefaultLevel = (
room: Room,
user: ICompletion,
defaultUserLevel: number,
) => {
if (user.completionId === undefined) {
return false;
}
const member = room.getMember(user.completionId);
if (member === null) {
return false;
}
return member.powerLevel <= defaultUserLevel;
};
export const getUserIdsFromCompletions = (completions: ICompletion[]) => {
const completionsWithId = completions.filter(completion => completion.completionId !== undefined);
// undefined completionId's are filtered out above but TypeScript does not seem to understand.
return completionsWithId.map(completion => completion.completionId!);
};

View file

@ -33,6 +33,7 @@ import SettingsStore from "../../../../../settings/SettingsStore";
import { VoiceBroadcastInfoEventType } from '../../../../../voice-broadcast';
import { ElementCall } from "../../../../../models/Call";
import SdkConfig, { DEFAULTS } from "../../../../../SdkConfig";
import { AddPrivilegedUsers } from "../../AddPrivilegedUsers";
interface IEventShowOpts {
isState?: boolean;
@ -470,6 +471,11 @@ export default class RolesRoomSettingsTab extends React.Component<IProps> {
<div className="mx_SettingsTab mx_RolesRoomSettingsTab">
<div className="mx_SettingsTab_heading">{ _t("Roles & Permissions") }</div>
{ privilegedUsersSection }
{
(canChangeLevels && room !== null) && (
<AddPrivilegedUsers room={room} defaultUserLevel={defaultUserLevel} />
)
}
{ mutedUsersSection }
{ bannedUsersSection }
<SettingsFieldset