Files
casdoor/web/src/common/select/OrganizationSelect.js

87 lines
2.8 KiB
JavaScript
Raw Normal View History

2023-05-27 19:02:54 +08:00
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// 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 from "react";
import {Select} from "antd";
import i18next from "i18next";
import * as OrganizationBackend from "../../backend/OrganizationBackend";
import * as Setting from "../../Setting";
import * as Conf from "../../Conf";
2023-05-27 19:02:54 +08:00
function OrganizationSelect(props) {
const {onChange, initValue, style, onSelect, withAll, className} = props;
2023-05-27 19:02:54 +08:00
const [organizations, setOrganizations] = React.useState([]);
const [value, setValue] = React.useState(initValue);
2023-05-27 19:02:54 +08:00
React.useEffect(() => {
if (props.organizations === undefined) {
getOrganizations();
}
window.addEventListener(Conf.StorageOrganizationsChangedEvent, getOrganizations);
return function() {
window.removeEventListener(Conf.StorageOrganizationsChangedEvent, getOrganizations);
};
}, [value]);
2023-05-27 19:02:54 +08:00
const getOrganizations = () => {
OrganizationBackend.getOrganizationNames("admin")
.then((res) => {
if (res.status === "ok") {
setOrganizations(res.data);
const selectedValueExist = res.data.filter(organization => organization.name === value).length > 0;
if (initValue === undefined || !selectedValueExist) {
handleOnChange(getOrganizationItems().length > 0 ? getOrganizationItems()[0].value : "");
}
2023-05-27 19:02:54 +08:00
}
});
};
const handleOnChange = (value) => {
setValue(value);
onChange?.(value);
};
const getOrganizationItems = () => {
const items = [];
organizations.forEach((organization) => items.push(Setting.getOption(organization.displayName, organization.name)));
if (withAll) {
items.unshift({
label: i18next.t(`organization:${Conf.DefaultOrganization}`),
value: Conf.DefaultOrganization,
});
}
return items;
};
2023-05-27 19:02:54 +08:00
return (
<Select
options={getOrganizationItems()}
2023-05-27 19:02:54 +08:00
virtual={false}
placeholder={i18next.t("login:Please select an organization")}
value={value}
onChange={handleOnChange}
filterOption={(input, option) => (option?.label ?? "").toLowerCase().includes(input.toLowerCase())}
style={style}
onSelect={onSelect}
className={className}
2023-05-27 19:02:54 +08:00
>
</Select>
);
}
export default OrganizationSelect;