@ant-design/icons#SwapOutlined TypeScript Examples
The following examples show how to use
@ant-design/icons#SwapOutlined.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Members.tsx From posthog-foss with MIT License | 4 votes |
function LevelComponent(member: OrganizationMemberType): JSX.Element | null {
const { user } = useValues(userLogic)
const { currentOrganization } = useValues(organizationLogic)
const { changeMemberAccessLevel } = useActions(membersLogic)
const myMembershipLevel = currentOrganization ? currentOrganization.membership_level : null
if (!user) {
return null
}
function generateHandleClick(listLevel: OrganizationMembershipLevel): (event: React.MouseEvent) => void {
return function handleClick(event: React.MouseEvent) {
event.preventDefault()
if (!user) {
throw Error
}
if (listLevel === OrganizationMembershipLevel.Owner) {
Modal.confirm({
centered: true,
title: `Transfer organization ownership to ${member.user.first_name}?`,
content: `You will no longer be the owner of ${user.organization?.name}. After the transfer you will become an administrator.`,
icon: <SwapOutlined />,
okType: 'danger',
okText: 'Transfer Ownership',
onOk() {
changeMemberAccessLevel(member, listLevel)
},
})
} else {
changeMemberAccessLevel(member, listLevel)
}
}
}
const levelButton = (
<Button
data-attr="change-membership-level"
icon={member.level === OrganizationMembershipLevel.Owner ? <CrownFilled /> : undefined}
>
{membershipLevelToName.get(member.level) ?? `unknown (${member.level})`}
</Button>
)
const allowedLevels = organizationMembershipLevelIntegers.filter(
(listLevel) => !getReasonForAccessLevelChangeProhibition(myMembershipLevel, user, member, listLevel)
)
const disallowedReason = getReasonForAccessLevelChangeProhibition(myMembershipLevel, user, member, allowedLevels)
return disallowedReason ? (
<Tooltip title={disallowedReason}>{levelButton}</Tooltip>
) : (
<Dropdown
overlay={
<Menu>
{allowedLevels.map((listLevel) => (
<Menu.Item key={`${member.user.uuid}-level-${listLevel}`}>
<a href="#" onClick={generateHandleClick(listLevel)} data-test-level={listLevel}>
{listLevel === OrganizationMembershipLevel.Owner ? (
<>
<CrownFilled style={{ marginRight: '0.5rem' }} />
Transfer organization ownership
</>
) : listLevel > member.level ? (
<>
<UpOutlined style={{ marginRight: '0.5rem' }} />
Upgrade to {membershipLevelToName.get(listLevel)}
</>
) : (
<>
<DownOutlined style={{ marginRight: '0.5rem' }} />
Downgrade to {membershipLevelToName.get(listLevel)}
</>
)}
</a>
</Menu.Item>
))}
</Menu>
}
>
{levelButton}
</Dropdown>
)
}
Example #2
Source File: Icon.tsx From html2sketch with MIT License | 4 votes |
IconSymbol: FC = () => {
return (
<Row>
{/*<CaretUpOutlined*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/1.CaretUpOutlined'}*/}
{/*/>*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/2.MailOutlined'}*/}
{/*/>*/}
{/*<StepBackwardOutlined*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/2.StepBackwardOutlined'}*/}
{/*/>*/}
{/*<StepForwardOutlined*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/2.StepBackwardOutlined'}*/}
{/*/>*/}
<StepForwardOutlined />
<ShrinkOutlined />
<ArrowsAltOutlined />
<DownOutlined />
<UpOutlined />
<LeftOutlined />
<RightOutlined />
<CaretUpOutlined />
<CaretDownOutlined />
<CaretLeftOutlined />
<CaretRightOutlined />
<VerticalAlignTopOutlined />
<RollbackOutlined />
<FastBackwardOutlined />
<FastForwardOutlined />
<DoubleRightOutlined />
<DoubleLeftOutlined />
<VerticalLeftOutlined />
<VerticalRightOutlined />
<VerticalAlignMiddleOutlined />
<VerticalAlignBottomOutlined />
<ForwardOutlined />
<BackwardOutlined />
<EnterOutlined />
<RetweetOutlined />
<SwapOutlined />
<SwapLeftOutlined />
<SwapRightOutlined />
<ArrowUpOutlined />
<ArrowDownOutlined />
<ArrowLeftOutlined />
<ArrowRightOutlined />
<LoginOutlined />
<LogoutOutlined />
<MenuFoldOutlined />
<MenuUnfoldOutlined />
<BorderBottomOutlined />
<BorderHorizontalOutlined />
<BorderInnerOutlined />
<BorderOuterOutlined />
<BorderLeftOutlined />
<BorderRightOutlined />
<BorderTopOutlined />
<BorderVerticleOutlined />
<PicCenterOutlined />
<PicLeftOutlined />
<PicRightOutlined />
<RadiusBottomleftOutlined />
<RadiusBottomrightOutlined />
<RadiusUpleftOutlined />
<RadiusUprightOutlined />
<FullscreenOutlined />
<FullscreenExitOutlined />
<QuestionOutlined />
<PauseOutlined />
<MinusOutlined />
<PauseCircleOutlined />
<InfoOutlined />
<CloseOutlined />
<ExclamationOutlined />
<CheckOutlined />
<WarningOutlined />
<IssuesCloseOutlined />
<StopOutlined />
<EditOutlined />
<CopyOutlined />
<ScissorOutlined />
<DeleteOutlined />
<SnippetsOutlined />
<DiffOutlined />
<HighlightOutlined />
<AlignCenterOutlined />
<AlignLeftOutlined />
<AlignRightOutlined />
<BgColorsOutlined />
<BoldOutlined />
<ItalicOutlined />
<UnderlineOutlined />
<StrikethroughOutlined />
<RedoOutlined />
<UndoOutlined />
<ZoomInOutlined />
<ZoomOutOutlined />
<FontColorsOutlined />
<FontSizeOutlined />
<LineHeightOutlined />
<SortAscendingOutlined />
<SortDescendingOutlined />
<DragOutlined />
<OrderedListOutlined />
<UnorderedListOutlined />
<RadiusSettingOutlined />
<ColumnWidthOutlined />
<ColumnHeightOutlined />
<AreaChartOutlined />
<PieChartOutlined />
<BarChartOutlined />
<DotChartOutlined />
<LineChartOutlined />
<RadarChartOutlined />
<HeatMapOutlined />
<FallOutlined />
<RiseOutlined />
<StockOutlined />
<BoxPlotOutlined />
<FundOutlined />
<SlidersOutlined />
<AndroidOutlined />
<AppleOutlined />
<WindowsOutlined />
<IeOutlined />
<ChromeOutlined />
<GithubOutlined />
<AliwangwangOutlined />
<DingdingOutlined />
<WeiboSquareOutlined />
<WeiboCircleOutlined />
<TaobaoCircleOutlined />
<Html5Outlined />
<WeiboOutlined />
<TwitterOutlined />
<WechatOutlined />
<AlipayCircleOutlined />
<TaobaoOutlined />
<SkypeOutlined />
<FacebookOutlined />
<CodepenOutlined />
<CodeSandboxOutlined />
<AmazonOutlined />
<GoogleOutlined />
<AlipayOutlined />
<AntDesignOutlined />
<AntCloudOutlined />
<ZhihuOutlined />
<SlackOutlined />
<SlackSquareOutlined />
<BehanceSquareOutlined />
<DribbbleOutlined />
<DribbbleSquareOutlined />
<InstagramOutlined />
<YuqueOutlined />
<AlibabaOutlined />
<YahooOutlined />
<RedditOutlined />
<SketchOutlined />
<AccountBookOutlined />
<AlertOutlined />
<ApartmentOutlined />
<ApiOutlined />
<QqOutlined />
<MediumWorkmarkOutlined />
<GitlabOutlined />
<MediumOutlined />
<GooglePlusOutlined />
<AppstoreAddOutlined />
<AppstoreOutlined />
<AudioOutlined />
<AudioMutedOutlined />
<AuditOutlined />
<BankOutlined />
<BarcodeOutlined />
<BarsOutlined />
<BellOutlined />
<BlockOutlined />
<BookOutlined />
<BorderOutlined />
<BranchesOutlined />
<BuildOutlined />
<BulbOutlined />
<CalculatorOutlined />
<CalendarOutlined />
<CameraOutlined />
<CarOutlined />
<CarryOutOutlined />
<CiCircleOutlined />
<CiOutlined />
<CloudOutlined />
<ClearOutlined />
<ClusterOutlined />
<CodeOutlined />
<CoffeeOutlined />
<CompassOutlined />
<CompressOutlined />
<ContactsOutlined />
<ContainerOutlined />
<ControlOutlined />
<CopyrightCircleOutlined />
<CopyrightOutlined />
<CreditCardOutlined />
<CrownOutlined />
<CustomerServiceOutlined />
<DashboardOutlined />
<DatabaseOutlined />
<DeleteColumnOutlined />
<DeleteRowOutlined />
<DisconnectOutlined />
<DislikeOutlined />
<DollarCircleOutlined />
<DollarOutlined />
<DownloadOutlined />
<EllipsisOutlined />
<EnvironmentOutlined />
<EuroCircleOutlined />
<EuroOutlined />
<ExceptionOutlined />
<ExpandAltOutlined />
<ExpandOutlined />
<ExperimentOutlined />
<ExportOutlined />
<EyeOutlined />
<FieldBinaryOutlined />
<FieldNumberOutlined />
<FieldStringOutlined />
<DesktopOutlined />
<DingtalkOutlined />
<FileAddOutlined />
<FileDoneOutlined />
<FileExcelOutlined />
<FileExclamationOutlined />
<FileOutlined />
<FileImageOutlined />
<FileJpgOutlined />
<FileMarkdownOutlined />
<FilePdfOutlined />
<FilePptOutlined />
<FileProtectOutlined />
<FileSearchOutlined />
<FileSyncOutlined />
<FileTextOutlined />
<FileUnknownOutlined />
<FileWordOutlined />
<FilterOutlined />
<FireOutlined />
<FlagOutlined />
<FolderAddOutlined />
<FolderOutlined />
<FolderOpenOutlined />
<ForkOutlined />
<FormatPainterOutlined />
<FrownOutlined />
<FunctionOutlined />
<FunnelPlotOutlined />
<GatewayOutlined />
<GifOutlined />
<GiftOutlined />
<GlobalOutlined />
<GoldOutlined />
<GroupOutlined />
<HddOutlined />
<HeartOutlined />
<HistoryOutlined />
<HomeOutlined />
<HourglassOutlined />
<IdcardOutlined />
<ImportOutlined />
<InboxOutlined />
<InsertRowAboveOutlined />
<InsertRowBelowOutlined />
<InsertRowLeftOutlined />
<InsertRowRightOutlined />
<InsuranceOutlined />
<InteractionOutlined />
<KeyOutlined />
<LaptopOutlined />
<LayoutOutlined />
<LikeOutlined />
<LineOutlined />
<LinkOutlined />
<Loading3QuartersOutlined />
<LoadingOutlined />
<LockOutlined />
<MailOutlined />
<ManOutlined />
<MedicineBoxOutlined />
<MehOutlined />
<MenuOutlined />
<MergeCellsOutlined />
<MessageOutlined />
<MobileOutlined />
<MoneyCollectOutlined />
<MonitorOutlined />
<MoreOutlined />
<NodeCollapseOutlined />
<NodeExpandOutlined />
<NodeIndexOutlined />
<NotificationOutlined />
<NumberOutlined />
<PaperClipOutlined />
<PartitionOutlined />
<PayCircleOutlined />
<PercentageOutlined />
<PhoneOutlined />
<PictureOutlined />
<PoundCircleOutlined />
<PoundOutlined />
<PoweroffOutlined />
<PrinterOutlined />
<ProfileOutlined />
<ProjectOutlined />
<PropertySafetyOutlined />
<PullRequestOutlined />
<PushpinOutlined />
<QrcodeOutlined />
<ReadOutlined />
<ReconciliationOutlined />
<RedEnvelopeOutlined />
<ReloadOutlined />
<RestOutlined />
<RobotOutlined />
<RocketOutlined />
<SafetyCertificateOutlined />
<SafetyOutlined />
<ScanOutlined />
<ScheduleOutlined />
<SearchOutlined />
<SecurityScanOutlined />
<SelectOutlined />
<SendOutlined />
<SettingOutlined />
<ShakeOutlined />
<ShareAltOutlined />
<ShopOutlined />
<ShoppingCartOutlined />
<ShoppingOutlined />
<SisternodeOutlined />
<SkinOutlined />
<SmileOutlined />
<SolutionOutlined />
<SoundOutlined />
<SplitCellsOutlined />
<StarOutlined />
<SubnodeOutlined />
<SyncOutlined />
<TableOutlined />
<TabletOutlined />
<TagOutlined />
<TagsOutlined />
<TeamOutlined />
<ThunderboltOutlined />
<ToTopOutlined />
<ToolOutlined />
<TrademarkCircleOutlined />
<TrademarkOutlined />
<TransactionOutlined />
<TrophyOutlined />
<UngroupOutlined />
<UnlockOutlined />
<UploadOutlined />
<UsbOutlined />
<UserAddOutlined />
<UserDeleteOutlined />
<UserOutlined />
<UserSwitchOutlined />
<UsergroupAddOutlined />
<UsergroupDeleteOutlined />
<VideoCameraOutlined />
<WalletOutlined />
<WifiOutlined />
<BorderlessTableOutlined />
<WomanOutlined />
<BehanceOutlined />
<DropboxOutlined />
<DeploymentUnitOutlined />
<UpCircleOutlined />
<DownCircleOutlined />
<LeftCircleOutlined />
<RightCircleOutlined />
<UpSquareOutlined />
<DownSquareOutlined />
<LeftSquareOutlined />
<RightSquareOutlined />
<PlayCircleOutlined />
<QuestionCircleOutlined />
<PlusCircleOutlined />
<PlusSquareOutlined />
<MinusSquareOutlined />
<MinusCircleOutlined />
<InfoCircleOutlined />
<ExclamationCircleOutlined />
<CloseCircleOutlined />
<CloseSquareOutlined />
<CheckCircleOutlined />
<CheckSquareOutlined />
<ClockCircleOutlined />
<FormOutlined />
<DashOutlined />
<SmallDashOutlined />
<YoutubeOutlined />
<CodepenCircleOutlined />
<AliyunOutlined />
<PlusOutlined />
<LinkedinOutlined />
<AimOutlined />
<BugOutlined />
<CloudDownloadOutlined />
<CloudServerOutlined />
<CloudSyncOutlined />
<CloudUploadOutlined />
<CommentOutlined />
<ConsoleSqlOutlined />
<EyeInvisibleOutlined />
<FileGifOutlined />
<DeliveredProcedureOutlined />
<FieldTimeOutlined />
<FileZipOutlined />
<FolderViewOutlined />
<FundProjectionScreenOutlined />
<FundViewOutlined />
<MacCommandOutlined />
<PlaySquareOutlined />
<OneToOneOutlined />
<RotateLeftOutlined />
<RotateRightOutlined />
<SaveOutlined />
<SwitcherOutlined />
<TranslationOutlined />
<VerifiedOutlined />
<VideoCameraAddOutlined />
<WhatsAppOutlined />
{/*</Col>*/}
</Row>
);
}
Example #3
Source File: ObjectAttrStruct.tsx From next-basics with GNU General Public License v3.0 | 4 votes |
export function LegacyObjectAttrStructForm(
props: LegacyObjectAttrStructProps
): React.ReactElement {
const [value, setValue] = React.useState<Partial<StructValueType>>({
default: "",
struct_define: [],
});
const [addStructMode, setAddStructMode] = React.useState("new");
const [addStructModalVisible, setAddStructModalVisible] =
React.useState(false);
const [importStructModalVisible, setImportStructModalVisible] =
React.useState(false);
const [currentStruct, setCurrentStruct] = React.useState<StructDefine>(
{} as StructDefine
);
const [cmdbObjectList, setCmdbObjectList] = React.useState<
Partial<CmdbModels.ModelCmdbObject>[]
>([]);
const [selectedObjectId, setSelectedObjectId] = React.useState("");
const [curValueType, setCurValueType] = React.useState("");
const [selectedObjectAttrKeys, setSelectedObjectAttrKeys] = React.useState(
[]
);
const [loadingObject, setLoadingObject] = React.useState(false);
const memoizeAttrList = React.useMemo(() => {
if (selectedObjectId.length) {
return cmdbObjectList
.filter((object) => object.objectId === selectedObjectId)[0]
?.attrList.filter(
(attr) => !["struct", "structs"].includes(attr.value.type)
);
} else {
return [];
}
}, [cmdbObjectList, selectedObjectId]);
const handleValueChange = (value: Partial<StructValueType>) => {
setValue(value);
props.onChange && props.onChange(value);
};
const { getFieldDecorator } = props.form;
const handleDeleteStruct = (struct: StructDefine) => {
Modal.confirm({
title: i18n.t(`${NS_FORMS}:${K.NOTICE}`),
content: (
<>
{i18n.t(`${NS_FORMS}:${K.DELETE_STRUCTURE_ITEM_PREFIX}`)}
<Tag color="red">{struct.name}</Tag>
{i18n.t(`${NS_FORMS}:${K.DELETE_STRUCTURE_ITEM_POSTFIX}`)}
</>
),
onOk() {
const structs = value.struct_define.filter(
(item) => item.id !== struct.id
);
handleValueChange({ ...value, struct_define: structs });
},
});
};
const loadCmdbObjectList = async () => {
setCmdbObjectList((await CmdbObjectApi_getObjectAll({})).data);
setLoadingObject(false);
};
const getOptionBtns = (record: any): React.ReactNode => (
<div className="struct-option-btn-group" style={{ display: "flex" }}>
{addStructMode === "new" && (
<Button
type="link"
icon={<EditOutlined />}
onClick={(e) => {
setCurrentStruct(record);
setCurValueType(record.type);
setAddStructModalVisible(true);
}}
/>
)}
<Button
type="link"
danger
icon={<DeleteOutlined />}
onClick={(e) => {
handleDeleteStruct(record);
}}
/>
</div>
);
const DragHandle = SortableHandle(() => (
<SwapOutlined className={styles.iconRotate} />
));
const SortableItem = SortableElement((props: any) => <tr {...props} />);
const SortableBody = SortableContainer((props: any) => <tbody {...props} />);
const onSortEnd = ({ oldIndex, newIndex }: SortEnd) => {
const dataSource = value?.struct_define;
if (oldIndex !== newIndex) {
const tempData = [].concat(dataSource);
const temp = tempData[oldIndex];
tempData[oldIndex] = tempData[newIndex];
tempData[newIndex] = temp;
handleValueChange({
...value,
struct_define: tempData.filter((el) => !!el),
});
}
};
const DraggableContainer = (props: any) => (
<SortableBody
useDragHandle
disableAutoscroll
helperClass={styles["row-dragging"]}
onSortEnd={onSortEnd}
{...props}
/>
);
const DraggableBodyRow = ({ className, style, ...restProps }: any) => {
const dataSource = value?.struct_define;
// function findIndex base on Table rowKey props and should always be a right array index
const index = dataSource.findIndex(
(x) => x?.id === restProps["data-row-key"]
);
return <SortableItem index={index} {...restProps} />;
};
const structColumns = [
{
title: i18n.t(`${NS_FORMS}:${K.STRUCTURE_ITEM_ID}`),
dataIndex: "id",
key: "id",
},
{
title: i18n.t(`${NS_FORMS}:${K.STRUCTURE_ITEM_NAME}`),
dataIndex: "name",
key: "name",
},
{
title: i18n.t(`${NS_FORMS}:${K.TYPE}`),
dataIndex: "type",
key: "type",
render: (text: string, record: any) =>
valueTypeList.filter((type) => type.key === text)[0].text,
},
{
title: i18n.t(`${NS_FORMS}:${K.HANDEL}`),
key: "action",
render: (text: string, record: any) => getOptionBtns(record),
},
{
title: "排序",
dataIndex: "sort",
width: 70,
className: styles["drag-visible"],
render: () => <DragHandle />,
},
];
const structWithEnumColumns = [
{
title: i18n.t(`${NS_FORMS}:${K.STRUCTURE_ITEM_ID}`),
dataIndex: "id",
key: "id",
},
{
title: i18n.t(`${NS_FORMS}:${K.STRUCTURE_ITEM_NAME}`),
dataIndex: "name",
key: "name",
},
{
title: i18n.t(`${NS_FORMS}:${K.TYPE}`),
dataIndex: "type",
key: "type",
render: (text: string, record: any) =>
valueTypeList.filter((type) => type.key === text)[0].text,
},
{
title: i18n.t(`${NS_FORMS}:${K.ENUM_REGEX_JSON}`),
dataIndex: "regex",
key: "regex",
render: (text: any, record: { regex: any[]; type: string }) => {
if (
Array.isArray(record.regex) &&
["enums", "enum"].includes(record.type)
) {
return record.regex.join(",") || "";
} else if (record.type === "ip") {
return IPRegex;
}
return record.regex || "";
},
},
{
title: i18n.t(`${NS_FORMS}:${K.HANDEL}`),
key: "action",
render: (text: any, record: any) => getOptionBtns(record),
},
{
title: "排序",
dataIndex: "sort",
width: 70,
className: styles["drag-visible"],
render: () => <DragHandle />,
},
];
React.useEffect(() => {
!isNil(props.value) && setValue(props.value);
}, [props.value]);
React.useEffect(() => {
if (addStructMode !== "new") {
loadCmdbObjectList();
}
}, [addStructMode]);
const handleModeChange = (e: RadioChangeEvent) => {
setAddStructMode(e.target.value);
handleValueChange({ ...value, struct_define: [] });
e.target.value !== "new" && setLoadingObject(true);
};
const handleAddStructConfirm = () => {
//istanbul ignore next
props.form.validateFields(async (err, data) => {
if (err) {
return;
}
const new_struct_define = [...value.struct_define];
if (isEmpty(currentStruct)) {
new_struct_define.push({ ...data, isNew: true });
} else {
const currentStructId = value.struct_define.findIndex(
(item) => item.id === currentStruct.id
);
if (currentStructId !== -1) {
new_struct_define[currentStructId] = {
...data,
isNew: new_struct_define[currentStructId].isNew,
};
}
}
handleValueChange({
...value,
struct_define: new_struct_define,
});
setAddStructModalVisible(false);
setCurValueType("");
props.form.resetFields();
});
};
const rowSelection = {
onChange: (
selectedRowKeys: string[] | number[],
selectedRows: StructDefine[]
) => {
setSelectedObjectAttrKeys(selectedRowKeys);
},
selectedRowKeys: selectedObjectAttrKeys,
};
const handleObjectChange = (e: string) => {
setSelectedObjectId(e);
setSelectedObjectAttrKeys(
cmdbObjectList
.filter((object) => object.objectId === e)[0]
?.attrList.filter(
(attr) => !["struct", "structs"].includes(attr.value.type)
)
.map((attr, index) => attr.id)
);
};
return (
<div>
{i18n.t(`${NS_FORMS}:${K.STRUCTURE_BODY_DEFINATION}`)}
<div>
<Row>
<Radio.Group value={addStructMode} onChange={handleModeChange}>
<Radio value="new">
{i18n.t(`${NS_FORMS}:${K.NEW_DEFINATION}`)}
</Radio>
<Radio value="import">{i18n.t(`${NS_FORMS}:${K.IFEM}`)}</Radio>
</Radio.Group>
</Row>
<Row style={{ marginTop: 8 }}>
{addStructMode === "new" ? (
<Button
icon={<PlusOutlined />}
onClick={() => {
setCurrentStruct({} as StructDefine);
setAddStructModalVisible(true);
}}
>
{i18n.t(`${NS_FORMS}:${K.ADD_STRUCTURE_ITEM}`)}
</Button>
) : (
<Button
icon={<PlusOutlined />}
onClick={() => {
setImportStructModalVisible(true);
}}
loading={loadingObject}
>
{i18n.t(`${NS_FORMS}:${K.SELECT_MODEL}`)}
</Button>
)}
</Row>
</div>
<div style={{ marginTop: 15 }}>
<Table
columns={
(value?.struct_define?.some((item) => regexType.includes(item.type))
? structWithEnumColumns
: structColumns) as ColumnsType<StructDefine>
}
dataSource={value?.struct_define}
pagination={false}
rowKey="id"
components={{
body: {
wrapper: DraggableContainer,
row: DraggableBodyRow,
},
}}
/>
</div>
<Modal
title={
isEmpty(currentStruct)
? i18n.t(`${NS_FORMS}:${K.TITLE_ADD_STRUCTURE_ITEM}`)
: i18n.t(`${NS_FORMS}:${K.TITLE_EDIT_STRUCTURE_ITEM}`)
}
visible={addStructModalVisible}
onOk={handleAddStructConfirm}
onCancel={() => {
setCurValueType("");
props.form.resetFields();
setAddStructModalVisible(false);
}}
>
<Form
labelCol={{ span: currentLang === "zh" ? 6 : 10 }}
wrapperCol={{ span: 16 }}
>
<Form.Item label={i18n.t(`${NS_FORMS}:${K.STRUCTURE_ITEM_ID}`)}>
{getFieldDecorator("id", {
initialValue: isEmpty(currentStruct) ? "" : currentStruct.id,
rules: [
{
required: true,
message: i18n.t(`${NS_FORMS}:${K.INPUT_STRUCTURE_ITEM_ID}`),
},
{
pattern: /^[a-zA-Z][a-zA-Z_0-9]{0,31}$/gi,
message: i18n.t(`${NS_FORMS}:${K.STRUCTURE_ITEM_ID_LIMIT}`),
},
{
validator: (rule, curValue, cb) => {
const structIdArr =
value.struct_define?.map((r) => r.id) || [];
if (
currentStruct.id !== curValue &&
structIdArr.includes(curValue)
) {
cb(
i18n.t(`${NS_FORMS}:${K.DUPLICATE_STRUCTURE_ITEM_ID}`, {
id: curValue,
})
);
}
cb();
},
},
],
})(<Input autoFocus />)}
</Form.Item>
<Form.Item label={i18n.t(`${NS_FORMS}:${K.STRUCTURE_ITEM_NAME}`)}>
{getFieldDecorator("name", {
initialValue: isEmpty(currentStruct) ? "" : currentStruct.name,
rules: [
{
required: true,
message: i18n.t(`${NS_FORMS}:${K.INPUT_STRUCTURE_ITEM_NAME}`),
},
],
})(<Input />)}
</Form.Item>
<Form.Item label={i18n.t(`${NS_FORMS}:${K.TYPE}`)}>
{getFieldDecorator("type", {
initialValue: isEmpty(currentStruct) ? "" : currentStruct.type,
rules: [
{
required: true,
message: i18n.t(`${NS_FORMS}:${K.ENTER_TYPE}`),
},
],
})(
<Select
onChange={(value) => setCurValueType(value as string)}
style={{ width: "100%" }}
disabled={!isEmpty(currentStruct) && !currentStruct?.isNew}
>
{valueTypeList
.filter(
(type) => type.key !== "struct" && type.key !== "structs"
)
.map((item) => (
<Option key={item.key} value={item.key}>
{item.text}
</Option>
))}
</Select>
)}
</Form.Item>
{(curValueType === "enum" || curValueType === "enums") && (
<Form.Item label={i18n.t(`${NS_FORMS}:${K.ENUMERATION_VALUE}`)}>
{getFieldDecorator("regex", {
initialValue:
isEmpty(currentStruct) || isNil(currentStruct.regex)
? []
: currentStruct.regex,
})(
<Select
mode="tags"
style={{ width: "100%" }}
placeholder={i18n.t(
`${NS_FORMS}:${K.PLEASE_INPUT_ENUMERATED_VALUE}`
)}
/>
)}
</Form.Item>
)}
{(curValueType === "str" ||
curValueType === "int" ||
curValueType === "arr" ||
curValueType === "json") && (
<Form.Item
label={
curValueType === "json"
? "JSON Schema:"
: i18n.t(`${NS_FORMS}:${K.REGULAR}`)
}
>
{getFieldDecorator("regex", {
initialValue: isEmpty(currentStruct) ? "" : currentStruct.regex,
})(
<Input
placeholder={i18n.t(`${NS_FORMS}:${K.THIS_IS_NOT_MANDATORY}`)}
/>
)}
</Form.Item>
)}
{curValueType === "ip" && (
<Form.Item label={i18n.t(`${NS_FORMS}:${K.REGULAR}`)}>
<Input.TextArea
value={IPRegex}
style={{ wordBreak: "break-all" }}
disabled={true}
autoSize={{ minRows: 4 }}
resize={false}
/>
</Form.Item>
)}
</Form>
</Modal>
<Modal
title={i18n.t(`${NS_FORMS}:${K.CITE_MODEL}`)}
visible={importStructModalVisible}
onOk={() => {
handleValueChange({
...value,
struct_define: selectedObjectAttrKeys.map((id) => {
const selectedRow = memoizeAttrList.filter(
(attr) => attr.id === id
)[0];
return {
id: selectedRow.id,
name: selectedRow.name,
type: selectedRow.value.type,
regex: selectedRow.value.regex,
};
}),
});
setSelectedObjectId("");
setImportStructModalVisible(false);
}}
onCancel={() => {
setSelectedObjectId("");
setImportStructModalVisible(false);
}}
width={800}
>
<Select
showSearch
placeholder={i18n.t(
`${NS_FORMS}:${K.SELECT_ONE_CMDB_RESOURCE_MODEL}`
)}
filterOption={(input, option) =>
option.props.children.toLowerCase().indexOf(input.toLowerCase()) >=
0
}
onChange={handleObjectChange}
value={selectedObjectId}
style={{ width: "100%" }}
>
{cmdbObjectList.map(
(object: Partial<CmdbModels.ModelCmdbObject>, index) => (
<Option key={index} value={object.objectId}>
{object.name}
</Option>
)
)}
</Select>
{selectedObjectId.length > 0 && (
<div style={{ marginTop: 15 }}>
{i18n.t(`${NS_FORMS}:${K.SELECT_ATTRIBUTE}`)}
<Table
columns={objectAttrColumns}
dataSource={memoizeAttrList}
rowSelection={rowSelection as any}
pagination={false}
rowKey={"id"}
/>
</div>
)}
</Modal>
</div>
);
}
Example #4
Source File: CodecPage.tsx From yakit with GNU Affero General Public License v3.0 | 4 votes |
CodecPage: React.FC<CodecPageProp> = (props) => {
const [text, setText] = useState("")
const [result, setResult] = useState("")
const [loading, setLoading] = useState(true)
const [leftWidth, setLeftWidth] = useState<boolean>(false)
const [rightWidth, setRightWidth] = useState<boolean>(false)
const [leftLine, setLeftLine] = useState<boolean>(true)
const [rightLine, setRightLine] = useState<boolean>(false)
const [codecType, setCodecType] = useState<CodecType>();
const [params, setParams] = useState<YakExecutorParam[]>([]);
const [codecPlugin, setCodecPlugin] = useState<CodecType[]>([]);
const [pluginLoading, setPluginLoading] = useState<boolean>(false)
const [pluginVisible, setPluginVisible] = useState<boolean>(false)
let timer: any = null
const codec = (t: string, params?: YakExecutorParam[], isYakScript?: boolean) => {
if (!t) {
failed("BUG: 空的解码类型")
return
}
if (!text && !isYakScript) {
failed("左侧编辑器内容为空,请输入内容后重试!")
return
}
ipcRenderer
.invoke("Codec", {Type: t, Text: text, Params: params || [], ScriptName: isYakScript ? t : ""})
.then((res) => {
onHandledResult(res?.Result || "")
})
.catch((err) => {
onHandleError(`${err}`)
})
}
const onHandledResult = (data: string) => {
setResult(data)
}
const onHandleError = (err: string) => {
if (err) failed(`CODEC 解码失败:${err}`)
}
useEffect(() => {
setLoading(true)
setTimeout(() => setLoading(false), 300)
}, [])
const renderCodecTypes = useMemoizedFn((items: CodecType[], notAutoExec?: boolean, isYakScript?: boolean) => {
return (
items.map((item) => {
if ((item.subTypes || []).length > 0) {
return (
<Dropdown
key={item.verbose}
overlay={
<Menu activeKey={codecType?.key}>
{item.subTypes?.map((subItem) => {
return (
<Menu.Item
key={`${subItem.key}`}
onClick={() => {
setCodecType(subItem)
if (!notAutoExec) {
codec(subItem.key || "", [], isYakScript)
}
}}>
<span>
{subItem.verbose}
</span>
</Menu.Item>
)
})}
</Menu>
}
placement='bottomLeft'
>
<Button
type={((item?.subTypes || []).filter(i => {
return i.key === codecType?.key
})).length > 0 ? "primary" : undefined}
>
{item.verbose}
<DownOutlined/>
</Button>
</Dropdown>
)
} else {
return (
<Button
key={item.key}
type={codecType?.key === item.key ? "primary" : undefined}
onClick={() => {
setCodecType(item);
if (!notAutoExec) {
codec(item.key || "", [], isYakScript)
}
}}
style={{marginRight: 8}}
>
{item.verbose}
</Button>
)
}
})
)
})
const search = useMemoizedFn((keyword?: string) => {
setPluginLoading(true)
queryYakScriptList(
"codec",
(i: YakScript[], total) => {
setCodecPlugin([{
subTypes: i.map(script => {
return {
key: script.ScriptName,
help: script.Help,
verbose: script.ScriptName,
isYakScript: true
}
}), key: "from-yakit-codec-plugin", verbose: "CODEC 社区插件"
}])
},
() => setTimeout(() => setPluginLoading(false), 300),
10,
undefined,
keyword
)
})
useEffect(() => {
search()
}, [])
return (
<AutoSpin spinning={loading}>
<PageHeader
title={"Codec"} className={"codec-pageheader-title"}
subTitle={<>
{codecType && <Tag color={"geekblue"}>当前类型:{codecType?.verbose}</Tag>}
{codecType && (codecType?.params || []).length <= 0 &&
<Button type={"primary"} size={"small"} onClick={e => {
codec(codecType?.key || "", [], codecType?.isYakScript)
}}>立即执行</Button>}
</>}
/>
<div className={"codec-function-bar"}>
<Space direction={"vertical"} style={{width: "100%"}}>
<Space>
{renderCodecTypes(CodecMenu)}
</Space>
<Space>
{renderCodecTypes(EncAmpDecMenu, true)}
{/* {renderCodecTypes(codecPlugin, false, true)} */}
<Popover
overlayClassName="codec-plugin-lib"
trigger="hover"
placement="bottomLeft"
visible={pluginVisible}
onVisibleChange={setPluginVisible}
content={
<div style={{width: 250}}>
<Input placeholder="模糊搜索插件名" allowClear onChange={event => {
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(() => {
search(event.target.value)
}, 500);
}}></Input>
<List
loading={pluginLoading}
size="small"
dataSource={codecPlugin[0]?.subTypes || []}
rowKey={row => row.key || ""}
renderItem={item => <List.Item>
<div style={{width: "100%", padding: "5px 7px"}} onClick={() => {
setCodecType(item)
codec(item.key || "", [], true)
setPluginVisible(false)
}}>
{item.key || ""}
</div>
</List.Item>}
/>
</div>
}>
<Button
type={(codecPlugin[0]?.subTypes || []).filter(item => codecType?.key === item.key).length !== 0 ? 'primary' : 'default'}>CODEC
社区插件 <DownOutlined style={{fontSize: 10}}/></Button>
</Popover>
</Space>
{codecType && codecType?.params && codecType.params.length > 0 && <Row
style={{width: "100%"}}
gutter={20}
>
<Col span={codecType?.help ? 18 : 24}>
<Divider>设置参数</Divider>
<YakScriptParamsSetter
primaryParamsOnly={true} styleSize={"small"}
Params={(codecType?.params || [])}
onParamsConfirm={finalParams => {
setParams([...finalParams])
codec(codecType?.key || "", finalParams, codecType?.isYakScript)
}}
hideClearButton={true}
submitVerbose={"执行"}
/>
</Col>
{codecType?.help && <Col span={6} style={{paddingTop: 30}}>
<Alert type={"info"} message={codecType?.help}/>
</Col>}
</Row>}
</Space>
</div>
<div className={"codec-content"}>
<Row wrap={false} justify='space-between' style={{flexGrow: 1}}>
<Col flex={leftWidth ? "0 1 80%" : rightWidth ? "0 1 18%" : "0 1 49%"}>
<AutoCard
className='codec-card-body'
headStyle={{height: 28, minHeight: 28, padding: 0}}
bodyStyle={{padding: 0}}
extra={
<>
<Button
size={"small"}
type={leftLine ? "primary" : "link"}
icon={<LineConversionIcon/>}
onClick={() => setLeftLine(!leftLine)}
/>
<Button
size={"small"}
type={leftWidth ? "primary" : "link"}
icon={<ArrowsAltOutlined/>}
onClick={() => {
setLeftWidth(!leftWidth)
setRightWidth(false)
}}
/>
</>
}
>
<div className='editor-body'>
<YakEditor value={text} noWordWrap={!leftLine} setValue={setText}/>
</div>
</AutoCard>
</Col>
<Col flex='0 1 2%'>
<div className={"exchange-btn"}>
<SwapOutlined
className={"exchange-icon"}
onClick={() => {
const left = text
const right = result
setText(right)
setResult(left)
}}
/>
</div>
</Col>
<Col flex={rightWidth ? "0 1 80%" : leftWidth ? "0 1 18%" : "0 1 49%"}>
<AutoCard
className='codec-card-body'
headStyle={{height: 28, minHeight: 28, padding: 0}}
bodyStyle={{padding: 0}}
extra={
<>
<Button
size={"small"}
type={rightLine ? "primary" : "link"}
icon={<LineConversionIcon/>}
onClick={() => setRightLine(!rightLine)}
/>
<Button
size={"small"}
type={rightWidth ? "primary" : "link"}
icon={<ArrowsAltOutlined/>}
onClick={() => {
setRightWidth(!rightWidth)
setLeftWidth(false)
}}
/>
</>
}
>
<div className='editor-body'>
<YakEditor value={result} noWordWrap={!rightLine} setValue={setResult} readOnly={true}
type={"http"}/>
</div>
</AutoCard>
</Col>
</Row>
</div>
</AutoSpin>
)
}