antd#Popover JavaScript Examples
The following examples show how to use
antd#Popover.
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: utils.js From the-eye-knows-the-garbage with MIT License | 7 votes |
renderForeignKey = (text, VerboseNameMap) => {
console.log(text);
console.log(VerboseNameMap);
let items = [];
for (let key in text) {
if (key !== 'ty_options_display_txt') {
let one = <Descriptions.Item label={VerboseNameMap[key]}>{text[key]}</Descriptions.Item>;
items.push(one);
}
}
return <Space>
<span>{text.ty_options_display_txt}</span>
<Popover trigger="click" content={<Descriptions>
{items}
</Descriptions>} title="外键数据">
<InfoCircleTwoTone size="small" />
</Popover>
</Space>;
}
Example #2
Source File: PopUpList.jsx From node-project-manager with Apache License 2.0 | 6 votes |
PopUpList = ({ tech }) => {
const [users, setUsers] = useState([]);
const usersUseTechs = useCallback(async () => {
const data = await Http.get("/api/techs/projectsUsersTechs/" + tech.id);
setUsers(data);
}, [tech]);
useEffect(() => {
// Wait for loading data user
//setLoading(true);
usersUseTechs();
//setLoading(false);
return () => setUsers([]);
}, [usersUseTechs]);
return (
<div>
{users.map((user) => {
user.icon = require("../../img/" + user.avatar);
return (
<Popover content={contentPopOver(user)} key={user.id}>
<Avatar src={user.icon} />
</Popover>
);
})}
</div>
);
}
Example #3
Source File: index.js From scalable-form-platform with MIT License | 6 votes |
render() {
const {children, visible, visibleChangeHandler, popupContainer} = this.props;
return (
<Popover
title=""
content={this.renderPopoverContent()}
visible={visible}
onVisibleChange={visibleChangeHandler}
trigger="click"
placement="bottomLeft"
overlayClassName="app-xform-builder-base-config-popover"
getPopupContainer={popupContainer}
>
{children}
</Popover>
);
}
Example #4
Source File: git.jsx From juno with Apache License 2.0 | 6 votes |
renderPush() {
let { source, metadata = '', operation, user_name } = this.props.data;
let commitData = JSON.parse(metadata);
let { user_avatar, commits = [], ref, project } = commitData;
let commit = null;
if (ref) {
let refSplices = ref.split('/');
ref = refSplices[refSplices.length - 1];
}
if (commits.length > 0) commit = commits[0];
return (
<span>
<UserInfo avatar={user_avatar} name={user_name ? user_name : user_name} /> 退送到仓库{' '}
<a href={project.git_http_url}>{project.name}</a>
<Tag color="blue" style={{ marginLeft: '10px' }}>
<Icon type="branches" />
{ref}
</Tag>
<div className={styles.cmLine}>
{commit ? (
<Popover content={commit.message}>
<a target="_blank" href={commit.url}>
{commit.id.substr(0, 8)}
</a>{' '}
{commit.message.substr(0, CommitMessageLen)}
{commit.message.length > CommitMessageLen ? '...' : ''}
</Popover>
) : (
'...'
)}
</div>
</span>
);
}
Example #5
Source File: index.js From gobench with Apache License 2.0 | 6 votes |
render() {
return (
<div>
<h5 className="mb-3">
<strong>Basic</strong>
</h5>
<div className="mb-5">
<Popover content={content} title="Title" className="mr-3 mb-3">
<Button type="primary">Default Popover</Button>
</Popover>
<Popover
placement="topLeft"
title="Title"
content={content}
arrowPointAtCenter
className="mr-3 mb-3"
>
<Button>Arrow points to center</Button>
</Popover>
</div>
</div>
)
}
Example #6
Source File: index.js From egoshop with Apache License 2.0 | 6 votes |
render() {
return (
<Popover
content={(
this.popoverContent()
)}
placement='bottom'
>
<Icon
type="smile-o"
style={{
fontSize:24,
color:'#999'
}}
/>
</Popover>
)
}
Example #7
Source File: index.js From camel-store-admin with Apache License 2.0 | 6 votes |
render() {
const { className, count, popupAlign, popupVisible, onPopupVisibleChange, bell } = this.props;
const noticeButtonClass = classNames(className, styles.noticeButton);
const notificationBox = this.getNotificationBox();
const NoticeBellIcon = bell || <Icon type="bell" className={styles.icon} />;
const trigger = (
<span className={noticeButtonClass}>
<Badge count={count} style={{ boxShadow: 'none' }} className={styles.badge}>
{NoticeBellIcon}
</Badge>
</span>
);
if (!notificationBox) {
return trigger;
}
const popoverProps = {};
if ('popupVisible' in this.props) {
popoverProps.visible = popupVisible;
}
return (
<Popover
placement="bottomRight"
content={notificationBox}
popupClassName={styles.popover}
trigger="click"
arrowPointAtCenter
popupAlign={popupAlign}
onVisibleChange={onPopupVisibleChange}
{...popoverProps}
>
{trigger}
</Popover>
);
}
Example #8
Source File: filter.js From ant-simple-pro with MIT License | 6 votes |
Filter = memo(function Filter({ tablecolumns, filterColunsFunc, className }) {
const onChange = (checkedValue) => {
const filterColunsData = tablecolumns.filter((item) => checkedValue.includes(item.key));
filterColunsFunc(filterColunsData)
}
const filterComponent = (
<>
<Checkbox.Group onChange={onChange} defaultValue={tablecolumns.map((item) => item.key)}>
<ul>
{
tablecolumns.length ? tablecolumns.map((item, index) => (
<li key={index}><Checkbox value={item.key}><span style={{ paddingLeft: '6px' }}>{item.title}</span></Checkbox></li>
)) : null
}
</ul>
</Checkbox.Group>
</>
);
return (
<>
<Popover placement="bottom" content={filterComponent}>
<Tooltip title='过滤' placement="left">
<FilterOutlined className={className} />
</Tooltip>
</Popover>
</>
)
})
Example #9
Source File: search_filters_popover.js From art-dashboard-ui with Apache License 2.0 | 6 votes |
render() {
return (
<Popover content={this.getPopoverContent()} title="Applied Filters" placement="leftBottom" className="right"
onClick={this.props.handleFilterBuildParamsButton}>
<Button
size="medium"
className="right"
style={{
marginBottom: "20px",
background: "#316DC1",
color: "white"}}
onClick={this.props.handleFilterBuildParamsButton}
icon={<FilterTwoTone/>}>Advanced Filters
</Button>
<Button/>
</Popover>
);
}
Example #10
Source File: utils.js From the-eye-knows-the-garbage with MIT License | 6 votes |
renderManyToMany = (text) => {
const color_arr = [
'green',
'cyan',
'blue',
'geekblue',
'purple',
'magenta',
'red',
'volcano',
'orange',
'gold',
'lime',
];
const child = [];
let items = [];
console.log(text);
for (let key in text) {
let value = text[key];
let one = <Descriptions.Item>
<Tag color={'blue'}>{value.ty_options_display_txt}</Tag>
</Descriptions.Item>;
items.push(one);
}
text.forEach((value, index, arr) => {
if (index < 15) {
child.push(<Col xs={24} sm={12} md={12} lg={8} xl={6} style={{paddingRight: 4, paddingTop: 4}}>
<Tag
color={color_arr[index % 10]}>
<Ellipsis style={{overflow: 'visible'}} tooltip
length={25}>{value.ty_options_display_txt}</Ellipsis>
</Tag>
</Col>);
} else if (index === 15) {
child.push(<Popover trigger="click" content={<Descriptions>
{items}
</Descriptions>} title="多对多数据">
<Col span={3} style={{paddingTop: 4}}>
<Tag
color={color_arr[index % 10]}>...
</Tag>
</Col>
</Popover>);
}
});
return <Row col={12}>{child}</Row>;
}
Example #11
Source File: arrow-point-at-center.jsx From virtuoso-design-system with MIT License | 6 votes |
storiesOf('antd/popover', module).add('arrow-point-at-center', () =>
<>
<Popover placement="topLeft" title="Title" content={content}>
<Button>Align edge / 边缘对齐</Button>
</Popover>
<Popover placement="topLeft" title="Title" content={content} arrowPointAtCenter>
<Button>Arrow points to center / 箭头指向中心</Button>
</Popover>
</>,
{ docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>The arrow points to the center of the target element, which set <code>arrowPointAtCenter</code>.</p></>) } });
Example #12
Source File: AdvancedProfile.js From acy-dex-interface with MIT License | 5 votes |
customDot = (dot, { status }) =>
status === 'process' ? (
<Popover placement="topLeft" arrowPointAtCenter content={popoverContent}>
{dot}
</Popover>
) : (
dot
)
Example #13
Source File: Event.js From website with MIT License | 5 votes |
EventItem = ({
city = 'Em todo o estado',
status = 'F',
title,
description,
event,
hideAuthor = false
}) => {
const { author } = event;
const statusMessages = messages(status);
return (
<Timeline.Item
className={status}
dot={statusMessages.icon}
color={statusMessages.color}
>
<div className='city'>
{city}
{event?.region?.initial && ` - ${event?.region?.initial}`}
{author && !hideAuthor && author?.name && (
<Popover
content={
<div style={{ textAlign: 'center' }}>
Evento criado por {author?.name}. <br />
<a>Clique aqui</a> para fazer parte de nossa equipe de
colaboradores.
</div>
}
>
<span className='info'>
<NotificationOutlined />
<span>{author.name}</span>
</span>
</Popover>
)}
</div>
<div className='meta'>
<Popover content={<span style={{ textAlign: 'center' }}>{title}</span>}>
<span className='label'>{title} - </span>
</Popover>
<span className='status'>{statusMessages.message} - </span>
{(event.from_date !== null || event.to_date !== null) && (
<Popover
content={<span>Período de vigência do evento em questão.</span>}
>
<span className='info'>
<ClockCircleOutlined />
<span>
{event.undefined_ends_date && 'A partir de '}
{event.from_date && formatDate(event.from_date)}
{event.to_date && ` - ${formatDate(event.to_date)}`}
</span>
</span>
</Popover>
)}
{event?.source?.source && (
<span className='info'>
<LinkOutlined />
<span>Fonte: {event.source.source}</span>
</span>
)}
</div>
<Text>{description}</Text>
{event.source?.link && (
<a href={event.source.link} target='__blank' alt={event.source.source}>
Ver mais
</a>
)}
</Timeline.Item>
);
}
Example #14
Source File: git.jsx From juno with Apache License 2.0 | 5 votes |
renderPipeline() {
const { metadata, app_name } = this.props.data;
let data = JSON.parse(metadata);
if (!data) return '';
const {
user = { name, avatar_url },
commit = { id, messag, url },
object_attributes = { status, duration, created_at, finished_at },
project,
} = data;
return (
<span>
<UserInfo avatar={user.avatar_url} name={user.name} /> 的提交{' '}
<a href={commit.url} target="_blank">
<Icon type="number" />
{commit.id.substr(0, 8)}
</a>{' '}
触发了 Git Pipeline{' '}
{object_attributes.status ? (
<Popover
content={`耗时: ${object_attributes.duration}s | 开始: ${object_attributes.created_at} | 结束: ${object_attributes.finished_at}`}
>
{object_attributes.status === 'success' ? (
<Tag color="green">success</Tag>
) : (
<Tag color="red">{object_attributes.status}</Tag>
)}
</Popover>
) : (
''
)}
<div className={styles.cmLine}>
<span>
<Popover content={commit.message}>
{commit.message.substr(0, CommitMessageLen)}
{commit.message.length > CommitMessageLen ? '...' : ''}
</Popover>
</span>
</div>
</span>
);
}
Example #15
Source File: SiderMenu.js From camel-store-admin with Apache License 2.0 | 5 votes |
render() {
const { location, superadmin, storelist, shopurl, getstoreSelect, collapsed, onCollapse, fixSiderbar, theme, storeicon, storename, config } = this.props;
const { openKeys, visible } = this.state;
const defaultProps = collapsed ? {} : { openKeys };
const siderClassName = classNames(styles.sider, {
[styles.fixSiderbar]: fixSiderbar,
[styles.fixSiderbar2]: config && config.store_type === 'cloud', // 云店不要显示切换门店菜单
[styles.light]: theme === 'light',
});
const allstore = storelist.map(item => (
<Option key={item.id + `#` + item.url} label={item.url}>
{item.name}
</Option>
));
let shopvalue = getLocalStorage('shopid') === shopurl ? shopurl : getLocalStorage('shopid')
const content = (
<Select
getPopupContainer={triggerNode => triggerNode.parentNode.parentNode}
style={{ width: 150, marginRight: 20 }}
value={shopvalue}
onChange={e => getstoreSelect(e)}>
{superadmin && (location.pathname === "/dashboard" || location.pathname.includes("/setting/storelist"))
? <Option key="all" label="所有门店汇总">所有门店汇总</Option> : null}
{allstore}
</Select>
)
return (
<Sider
trigger={null}
collapsible
collapsed={collapsed}
breakpoint="lg"
onCollapse={onCollapse}
width={256}
theme={theme}
className={siderClassName}
>
<div className={styles.logo} id="logo">
<Link to="/">
{/*<img src={storeicon} alt="logo" style={collapsed ? {} : {display:'none'}}/>*/}
<img src={storeicon.square_logo && storeicon.square_logo.file} alt="logo" style={{borderRadius: '50%', margin: '0 5px'}}/>
<h1
style={{
maxWidth: 170,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{storename}管理后台
</h1>
</Link>
</div>
{
config && config.store_type === 'camel' && (
<div className={styles.logo} id="logo" style={{ height: '53px', borderTop: '1px solid #eee' }}>
<Popover placement="right" title="切换门店"
visible={visible}
onVisibleChange={(e) => this.setState({ visible: collapsed ? e : visible })}
content={content}>
<Icon type="hdd" style={collapsed ? {marginLeft:15, cursor:'pointer'} : {marginLeft:10, marginRight:10}}/>
</Popover>
{content}
</div>
)
}
<BaseMenu
{...this.props}
mode="inline"
handleOpenChange={this.handleOpenChange}
onOpenChange={this.handleOpenChange}
style={{ padding: '16px 0', width: '100%', overflowX: 'hidden' }}
{...defaultProps}
/>
</Sider>
);
}
Example #16
Source File: ColorPicker.jsx From ui with MIT License | 5 votes |
ColorPicker = (props) => {
const { color, zIndex, onColorChange } = props;
const [colorPicked, setColorPicked] = useState(color);
const [visible, setVisible] = useState(false);
const onTemporaryColorChange = (newColor) => {
const { hex } = newColor;
setColorPicked(hex);
};
const onFinalColorChange = (newColor) => {
const { hex } = newColor;
setColorPicked(hex);
onColorChange(hex);
};
const pickerComponent = () => (
<SketchPicker
color={colorPicked}
onChange={onTemporaryColorChange}
onChangeComplete={onFinalColorChange}
/>
);
return (
<div style={{ zIndex }}>
<Popover
content={pickerComponent()}
placement='bottom'
trigger='click'
visible={visible}
onVisibleChange={(newVisible) => setVisible(newVisible)}
destroyTooltipOnHide
zIndex={zIndex}
>
<Button
size='small'
shape='circle'
style={{ backgroundColor: colorPicked }}
onClick={(e) => {
e.stopPropagation();
setVisible(true);
}}
>
<Tooltip placement='bottom' title='Change color' mouseEnterDelay={0} mouseLeaveDelay={0}>
<span> </span>
</Tooltip>
</Button>
</Popover>
</div>
);
}
Example #17
Source File: File.js From getlink-next with MIT License | 5 votes |
export default function File({
loading,
list,
handleRemove,
}) {
const { isAdmin, user } = useContext(Context);
const columns = useMemo(() => [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Date',
dataIndex: 'createdAt',
key: 'createdAt',
render: createdAt => new Date(createdAt).toLocaleString(),
},
{
title: '',
key: 'op',
width: 220,
fixed: 'right',
render: (text, record) => (
<div>
<Popover
content={(
<img
alt="loading"
style={{ width: 150, height: 150 }}
src={cdnQrcode(record.key, 'file', isAdmin)}
/>
)}>
<Button style={{ marginLeft: 10 }}>
<QrcodeOutlined />
</Button>
</Popover>
{user && (
<Popconfirm
title="Are you sure to delete this ?"
onConfirm={() => handleRemove(record.objectId)}
>
<Button style={{ marginLeft: 10 }} type="danger">
<DeleteOutlined />
</Button>
</Popconfirm>
)}
<CopyToClipboard text={cdnUrl(record.key, 'file', isAdmin)}
onCopy={() => message.success('Copied successfully')}>
<Button style={{ marginLeft: 10 }} type="primary">Copy</Button>
</CopyToClipboard>
</div>
),
},
], [handleRemove]);
return (
<Table
loading={loading}
dataSource={list}
columns={columns}
pagination={false}
/>
);
}
Example #18
Source File: basic.jsx From virtuoso-design-system with MIT License | 5 votes |
storiesOf('antd/popover', module).add('basic', () =>
<Popover content={content} title="Title">
<Button type="primary">Hover me</Button>
</Popover>,
{ docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>The most basic example. The size of the floating layer depends on the contents region.</p></>) } });
Example #19
Source File: deck.js From pretty-derby with GNU General Public License v3.0 | 5 votes |
RecommendDecks = (props) => {
// const [recommendDecks,setRecommendDecks] = useState(res.data||[])
const { t } = useTranslation();
const [recommendDecks, setRecommendDecks] = useState([]);
const [playerId, setPlayerId] = useState("");
const searchDeck = async () => {
if (playerId !== props.player.id) {
const formData = props.player ? { playerId: props.player.id } : {};
const res = await axios.post("https://urarawin.com/api/sqlite/searchDeck", formData);
setRecommendDecks(res.data || []);
setPlayerId(props.player.id);
}
};
// const deleteDeck = async (deck) => {
// const res = await axios.post("https://urarawin.com/api/sqlite/deleteDeck", deck)
// searchDeck()
// }
return (
<Popover
width={"100%"}
onVisibleChange={searchDeck}
overlayStyle={{ maxHeight: 800, overflow: "auto" }}
content={recommendDecks.map((deck) => (
<div key={deck.id} className="w-full grid grid-cols-8">
<div className="col-span-full">
{deck.tags && deck.tags.map((tag) => <Tag key={tag}>{tag}</Tag>)}
</div>
{deck.imgUrls.map((imgUrl) => (
<div className="col-span-1" key={imgUrl}>
<img src={CDN_SERVER + imgUrl} alt={imgUrl} width={"100"} />
</div>
))}
<div className="col-span-1">
<Button type="primary" onClick={() => props.loadDeck(deck)}>
{t("读取卡组")}
</Button>
</div>
</div>
))}
>
<Button size="sm" buttonType="outline">
{t("推荐卡组")}
</Button>
</Popover>
);
}
Example #20
Source File: FeedbackResults.js From video-journal-for-teams-fe with MIT License | 4 votes |
ResultsModal = () => {
const [showModal, setShowModal] = useState(false);
const [values, setValues] = useState(null);
const { team_id } = useParams();
const dispatch = useDispatch();
const history = useHistory();
const handleOpen = () => {
setShowModal(true);
};
const handleOk = () => {
if (values) {
const updates = { name: values };
axios
.put(``, updates)
.then((res) => {
dispatch(fetchTeamById(team_id));
setShowModal(!showModal);
})
.catch((err) => console.log(err));
}
};
const handleCancel = () => {
setShowModal(false);
};
const handleChange = (e) => {
setValues(e.target.value);
};
return (
<div>
<Button
type="primary"
style={{ color: "white", border: "none", fontSize: "1rem", textAlign: "left", backgroundColor: "#6954EA" }}
onClick={handleOpen}>
See your results
</Button>
<Modal
title="Your Results"
visible={showModal}
onOk={handleOk}
onCancel={handleCancel}
okButtonProps={{ style: { backgroundColor: "#6954EA", color: "white", border: "none" } }}>
Overall Performance : Some Score
<Popover content="Some extra explination of what this means!">
<Button
style={{
color: "#6954EA",
border: "hidden",
fontSize: "1rem",
textAlign: "left",
borderStyle: "none",
backgroundColor: "transparent",
boxShadow: "none",
}}>
<InfoCircleTwoTone />
</Button>
</Popover>
<br />
Delivery and Presentation : Some Score
<Popover content="Some extra explination of what this means!">
<Button
style={{
color: "#6954EA",
border: "hidden",
fontSize: "1rem",
textAlign: "left",
borderStyle: "none",
backgroundColor: "transparent",
boxShadow: "none",
}}>
<InfoCircleTwoTone />
</Button>
</Popover>
<br />
Quality of Response : Some Score
<Popover content="Some extra explination of what this means!">
<Button
style={{
color: "#6954EA",
border: "hidden",
fontSize: "1rem",
textAlign: "left",
borderStyle: "none",
backgroundColor: "transparent",
boxShadow: "none",
}}>
<InfoCircleTwoTone />
</Button>
</Popover>
<br />
Audio Quality : Some Score
<Popover content="Some extra explination of what this means!">
<Button
style={{
color: "#6954EA",
border: "hidden",
fontSize: "1rem",
textAlign: "left",
borderStyle: "none",
backgroundColor: "transparent",
boxShadow: "none",
}}>
<InfoCircleTwoTone />
</Button>
</Popover>
<br />
Visual Enviroment : Some Score
<Popover content="Some extra explination of what this means!">
<Button
style={{
color: "#6954EA",
border: "hidden",
fontSize: "1rem",
textAlign: "left",
borderStyle: "none",
backgroundColor: "transparent",
boxShadow: "none",
}}>
<InfoCircleTwoTone />
</Button>
</Popover>
</Modal>
</div>
);
}
Example #21
Source File: SettingsPopover.js From dexwebapp with Apache License 2.0 | 4 votes |
render() {
const theme = this.props.theme;
const userPreferences = this.props.userPreferences;
const themeName = userPreferences.themeName;
const language = userPreferences.language;
const currency = userPreferences.currency;
const content = (
<div style={{ minWidth: '360px' }}>
<Row type="flex" justify="space-between">
<Col span={4}>
<FontAwesomeIcon
icon={faGlobeAsia}
style={{
width: '24px',
height: '24px',
color: theme.textWhite,
}}
/>
</Col>
<Col span={14}>
<div
style={{
fontSize: '1rem',
color: theme.textWhite,
}}
>
<I s="Language" />
</div>
<div
style={{
fontSize: '0.85rem',
color: theme.textDim,
margin: '8px 0px',
}}
>
<I s="Change the default interface language" />
</div>
</Col>
<Col span={2}>
<OptionButton
disabled={language === 'en'}
size="small"
onClick={() => {
this.changeLanguage('en');
tracker.trackEvent({
type: 'CHANGE_LANGUAGE',
data: {
lang: 'en',
},
});
}}
>
En
</OptionButton>
</Col>
<Col span={2}></Col>
<Col span={2}>
<OptionButton
disabled={language === 'zh'}
size="small"
onClick={() => {
this.changeLanguage('zh');
tracker.trackEvent({
type: 'CHANGE_LANGUAGE',
data: {
lang: 'zh',
},
});
}}
>
中
</OptionButton>
</Col>
</Row>
<Row
type="flex"
style={{
borderTop: '1px solid ' + theme.seperator,
paddingTop: '12px',
}}
justify="space-between"
>
<Col span={4}>
<FontAwesomeIcon
icon={faCoins}
style={{
width: '24px',
height: '24px',
color: theme.textWhite,
}}
/>
</Col>
<Col span={14}>
<div
style={{
fontSize: '1rem',
color: theme.textWhite,
}}
>
<I s="Currency" />
</div>
<div
style={{
fontSize: '0.85rem',
color: theme.textDim,
margin: '8px 0px',
}}
>
<I s="Change the default currency" />
</div>
</Col>
<Col span={2}>
<OptionButton
style={{
width: '36px',
}}
disabled={currency === 'USD'}
size="small"
onClick={() => {
this.changeCurrency('USD');
tracker.trackEvent({
type: 'CHANGE_CURRENCY',
data: {
currency: 'usd',
},
});
}}
>
<I s="USD" />
</OptionButton>
</Col>
<Col
span={4}
style={{
textAlign: 'right',
}}
>
<OptionButton
style={{
width: '36px',
marginRight: '-2px',
}}
disabled={currency === 'CNY'}
size="small"
onClick={() => {
this.changeCurrency('CNY');
tracker.trackEvent({
type: 'CHANGE_CURRENCY',
data: {
currency: 'cny',
},
});
}}
>
<I s="CNY" />
</OptionButton>
</Col>
</Row>
<Row
type="flex"
style={{
borderTop: '1px solid ' + theme.seperator,
paddingTop: '12px',
}}
justify="space-between"
>
<Col span={4}>
<FontAwesomeIcon
icon={faBrush}
style={{
width: '24px',
height: '24px',
color: theme.textWhite,
}}
/>
</Col>
<Col span={14}>
<div
style={{
fontSize: '1rem',
color: theme.textWhite,
}}
>
<I s="Theme" />
</div>
<div
style={{
fontSize: '0.85rem',
color: theme.textDim,
margin: '8px 0px',
}}
>
<I s="Choose between dark and light theme" />
</div>
</Col>
<Col span={2}>
<OptionButton
disabled={themeName === 'light'}
size="small"
icon={<FontAwesomeIcon icon={faSun} />}
style={{
borderRadius: '50%',
}}
onClick={() => {
this.selectTheme('light');
tracker.trackEvent({
type: 'CHANGE_THEME',
data: {
themeName: 'light',
},
});
}}
/>
</Col>
<Col span={2} align="center">
<OptionButton
disabled={themeName === 'dark'}
size="small"
icon={<FontAwesomeIcon icon={faMoon} />}
style={{
borderRadius: '50%',
}}
onClick={() => {
this.selectTheme('dark');
tracker.trackEvent({
type: 'CHANGE_THEME',
data: {
themeName: 'dark',
},
});
}}
/>
</Col>
<Col span={2}>
<OptionButton
disabled={themeName === 'auto'}
size="small"
icon={<FontAwesomeIcon icon={faAdjust} />}
style={{
borderRadius: '50%',
}}
onClick={() => {
this.selectTheme('auto');
tracker.trackEvent({
type: 'CHANGE_THEME',
data: {
themeName: 'auto',
},
});
}}
/>
</Col>
</Row>
</div>
);
return (
<Popover
placement={'bottomLeft'}
mouseLeaveDelay={0.2}
content={content}
title={<I s="Settings" />}
trigger="click"
visible={this.props.visible}
onVisibleChange={this.props.onVisibleChange}
>
<SettingFontAwesomeIcon
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '32px',
marginTop: '12px',
marginBottom: '12px',
backgroundColor: this.props.theme.sidePanelBackground,
}}
>
<FontAwesomeIcon
icon={faCog}
style={{
width: '32px',
height: '14px',
paddingRight: '8px',
paddingLeft: '8px',
color: this.props.theme.textDim,
}}
/>
</SettingFontAwesomeIcon>
</Popover>
);
}
Example #22
Source File: index.js From certificate-generator with MIT License | 4 votes |
function ListEvents(props) {
const { Meta } = Card;
/*Recebe o organizador e o JSON de organizadores*/
const { organizador, users } = props
/*Trabalham para trocar a tela da lista de eventos com o formulário de edição/criação*/
const [ toEditFormEvent, setToEditFormEvent] = useState(false);
const [ toCreateFormEvent, setToCreateFormEvent] = useState(false);
const [ toProfile, setProfile] = useState(false);
const [ toList, setList] = useState(false);
const [ toSeeEvents, setSeeEvents] = useState(false);
/*Esta variavel guarda o evento referente quando o botão check participantes for acionado*/
const [ eventChecked, setEventChecked] = useState('');
/*JSON dos eventos*/
const [ eventos, setEventos ] = useState(eventosData)
/*Vaiável para saber qual evento foi editado*/
const [ eventEdited, setEventEdited ] = useState('')
//Dados do evento:
//Serão usados para editar no formulário
const [ company, setCompany] = useState('');
const [ course, setCourse ] = useState('');
const [ startDate, setStartDate ] = useState('');
const [ finishDate, setFinishDate ] = useState('');
const [ workload, setWorkload ] = useState('');
/*---------- Assinatura Digital ----------*/
const [ imageURL, setImageURL ] = useState(null)
const sigCanvas = useRef({})
const clear = () => sigCanvas.current.clear();
const save = () => {
setImageURL(sigCanvas.current.getTrimmedCanvas().toDataURL("image/png"))
}
/*--------- Formulário para criar evento ---------*/
const { RangePicker } = DatePicker;
/*Constroi o layout do input de datas*/
const formItemLayout = {
labelCol: {
xs: {
span: 24,
},
sm: {
span: 8,
},
},
wrapperCol: {
xs: {
span: 24,
},
sm: {
span: 16,
},
},
};
/*Constroi o layout do input de name/curso*/
const formInputLayout = {
labelCol: {
span: 4,
},
wrapperCol: {
span: 8,
},
};
/*Define as regras para que a data seja aceita */
const rangeConfig = {
rules: [
{
type: 'array',
required: true,
message: 'Este campo é obrigatório!',
},
],
};
/*Define as regras para que os inputs de texto sejam aceitos */
const rangeInputs = {
rules: [
{
required: true,
message: 'Por favor, preencha esse campo',
},
],
};
/*Função acionada quando um evento for ser criado*/
/*Ela não é chamada caso os campos não forem preeenchidos*/
const onFinish = fieldsValue => {
/*Dados do calendário*/
const rangeValue = fieldsValue['range-picker'];
if(imageURL === null) {
message.error('Por favor, escreva sua assinatura digital')
} else {
setEventos([
...eventos, {
user: organizador,
company: fieldsValue.company,
course: fieldsValue.course,
startDate: rangeValue[0].format('DD-MM-YYYY'),
finishDate: rangeValue[1].format('DD-MM-YYYY'),
workload: fieldsValue.workload,
logo: "https://miro.medium.com/max/478/1*jriufqYKgJTW4DKrBizU5w.png",
digitalSignature: imageURL
}
])
message.success('Evento criado com sucesso')
/*Retira o componente do formulário de eventos e volta para a lista*/
setToCreateFormEvent(false)
}
};
/*Buscando os eventos do organizador*/
let eventsOfOrganizer = []
eventos.map(evento => {
if(evento.user === organizador) {
eventsOfOrganizer.push(evento)
}
})
/*Verifica se existem eventos cadastrados para mostrar elemento do Antd 'No Data'*/
let noEvents = true
/* ------------- Deletando Eventos ---------------*/
const deleteEvent = (eventToBeDeleted) => {
message.success('O evento foi excluido')
setEventos( eventsOfOrganizer.filter(evento => {
if(evento.course !== eventToBeDeleted) {
return evento
}
}))
}
/* -------------- Editando eventos ----------------*/
const beforeEdit = () => {
if( !company || !course || !startDate || !finishDate || ! workload || !imageURL){
message.error('Por favor, não deixe seus dados vazios.')
//quando o formulário aparece na tela, essa mensagem aparece, caso o campo não tenha sido preenchido.
} else {
setToEditFormEvent(!toEditFormEvent)
}
}
//Ao salvar as informações editadas:
const saveEditFormEvent = (e) => {
e.preventDefault();
//Os campos que devem ser preenchidos:
if( !company || !course || !startDate || !finishDate || ! workload || !imageURL){
message.error('Por favor, preencha todos os campos do formulário.')
//quando o formulário aparece na tela, essa mensagem aparece, caso o campo não tenha sido preenchido.
} else {
/*Atualizando o evento do organizador*/
setEventos(eventsOfOrganizer.map(evento => {
/*Mudando somente o evento requerido*/
if(eventEdited === evento.course) {
evento['company'] = company
evento['course'] = course
evento['startDate'] = startDate
evento['finishDate'] = finishDate
evento['workload'] = workload
evento['digitalSignature'] = imageURL
return evento;
} else {
return evento;
}
}) )
message.success('Os dados do evento foram atualizados com sucesso!')
/*Voltando para a lista de eventos*/
//setToEditFormEvent(!toEditFormEvent)
}
}
const clickEditFormEvent = (eventToBeEdit) => {
/*Trocando a lista de eventos pelo formulário de edição*/
setToEditFormEvent(!toEditFormEvent)
/*Guardando qual evento será editado*/
setEventEdited(eventToBeEdit.course)
setCompany(eventToBeEdit.company)
setCourse(eventToBeEdit.course)
setStartDate(eventToBeEdit.startDate)
setFinishDate(eventToBeEdit.finishDate)
setWorkload(eventToBeEdit.workload)
}
/*Esta função é acionada quando o botão para o check list é acionado*/
const saveEventToList = (eventToList) => {
setList(true)
setEventChecked(eventToList)
}
/*Esta função é acionada quando o botão para mais infomações do evento*/
const seeEvents = (eventToList) => {
setSeeEvents(true)
setEventChecked(eventToList)
}
return(
<>
<div style={{ display: ( toEditFormEvent || toCreateFormEvent || toProfile || toList || toSeeEvents )? 'none' : null }}>
<h1 className="title-2-list-events"><UserOutlined onClick={() => setProfile(true)}/> {organizador}</h1>
<Button className="button-add" onClick={() => setToCreateFormEvent(true)}><UsergroupAddOutlined/> Cadastrar mais um evento</Button>
<br/>
<h1 className="title">Eventos Cadastrados</h1>
<div className="listEvents">
{
eventos.map(eventoJson => {
if(eventoJson.user === organizador ){
noEvents = false
return(
<Card
style={{ width: 300 }}
cover={
<img
alt="Poster do evento"
src="https://jaquelinecramos.files.wordpress.com/2018/03/dyfqkqaw0aad5xm.jpg?w=776"
/>
}
actions={[
<>
<Popover content={<h5>Ver mais info. do evento</h5>}>
<Button style={{ borderColor: 'transparent'}} onClick={() => seeEvents(eventoJson) }><HeartOutlined key="edit" /></Button>
</Popover>
<Popover content={<h5>Editar evento</h5>}>
<Button style={{ borderColor: 'transparent'}} onClick={() => clickEditFormEvent(eventoJson) } ><FormOutlined key="edit" /></Button>
</Popover>
<Popover content={<h5>Participantes</h5>}>
<Button style={{ borderColor: 'transparent'}} onClick={() => saveEventToList(eventoJson)}><TeamOutlined key="ellipsis" /></Button>
</Popover>
<Popconfirm
title="Você tem certeza de que quer excluir este evento?"
onConfirm={() => deleteEvent(eventoJson.course) }
okText="Sim"
cancelText="Não"
>
<Button style={{ borderColor: 'transparent'}} ><CloseOutlined key="edit" /></Button>
</Popconfirm>
</>
]}
>
<Meta
avatar={<Avatar src="https://cdn-images-1.medium.com/max/1200/1*B8rGvo7fJ7qL4uFJ_II_-w.png" />}
title={<h4 style={{ color: '#C6255A'}}>{eventoJson.course}</h4>}
description={
<>
<h5 style={{ fontSize: '12px'}}>Inicio: {eventoJson.startDate}</h5>
<h5 style={{ fontSize: '12px'}}>Encerramento: {eventoJson.finishDate}</h5>
</>
}
/>
</Card>
)
}
})
}
{ noEvents && <Empty style={{marginTop: '5%'}}/> }
</div>
</div>
{toEditFormEvent &&
// Mostra na tela o formulário com os campos para serem editados
//o value está trazendo as informações do último cadastrado "Lucas...."
//quando eu troco o nome do course (Evento), altera o nome dos 3 eventos que estão sendo mostrados na tela
<div className="edit-event"
style={{ display: toEditFormEvent ? 'block' : 'none' }} >
<h2 className="edit-event-title">Edite os dados do seu evento:</h2>
<h4>Comunidade:</h4>
<Input
className="edit-event-input"
placeholder="Comunidade"
value={company}
onChange={ newValue => setCompany(newValue.target.value) } />
<br/>
<h4>Evento:</h4>
<Input
className="edit-event-input"
placeholder="Evento"
value={course}
onChange={ newValue => setCourse(newValue.target.value) }/>
<br/>
<h4>Data de Inicio:</h4>
<Input
className="edit-event-input"
placeholder="Data de Início"
value={startDate}
onChange={ newValue => setStartDate(newValue.target.value) }/>
<br/>
<h4>Data de Encerramento:</h4>
<Input
className="edit-event-input"
placeholder="Data de Fim"
value={finishDate}
onChange={ newValue => setFinishDate(newValue.target.value) }/>
<br/>
<h4>Carga Horaria:</h4>
<Input
className="edit-event-input"
placeholder="Carga Horária"
value={workload}
onChange={ newValue => setWorkload(newValue.target.value) }/>
<br/>
<h4>Assinatura Digital:</h4>
<div>
<Popup modal trigger={<Button className="button-open-pad">Abrir Pad para assinar</Button>}>
{ close => (
<>
<SignaturePad ref={sigCanvas}
canvasProps={{
className: 'signatureCanvas'
}}
/>
<Button onClick={save} className="button-save">Salvar</Button>
<Button onClick={clear} >Apagar Tudo</Button>
<Button onClick={close} className="button-close" >Fechar</Button>
</>
)}
</Popup>
<br/>
<br/>
{ imageURL ? (
<img
src={imageURL}
alt="Minha assinatura Digital"
className="buttons-pad"
/>
) : null }
</div>
<Button
className="button-edit-event" type="primary" primary
onClick={saveEditFormEvent}>Atualizar dados</Button>
<br/>
<Button className="back-edit-event" onClick={beforeEdit}>Voltar para a lista de eventos</Button>
</div>
}
{ toCreateFormEvent &&
<>
<Form name="time_related_controls" {...formItemLayout} onFinish={onFinish}>
<div className="inputs-event">
<h1 className="h1-form-event">Criando um novo evento</h1>
<Form.Item
{...formInputLayout}
{...rangeInputs}
className="input-1-event"
name="company"
label="Comunidade" >
<Input placeholder="Digite a comunidade responsável pelo evento" />
</Form.Item>
<Form.Item
{...formInputLayout}
{...rangeInputs}
className="input-2-event"
name="course"
label="Curso/Evento">
<Input placeholder="Digite o nome do evento" />
</Form.Item>
<Form.Item
{...rangeInputs}
className="input-3-event"
label="Carga Horária"
name="workload" >
<InputNumber />
</Form.Item>
<Form.Item
name="range-picker"
className="input-4-event"
label="Data de inicio/fim do evento"
{...rangeConfig}>
<RangePicker />
</Form.Item>
<div className="upload-assinature">
<h3 className="h3-form-event">Assinatura Digital:</h3>
<div>
<Popup modal trigger={<Button className="button-open-pad">Abrir Pad para assinar</Button>}>
{ close => (
<>
<SignaturePad ref={sigCanvas}
canvasProps={{
className: 'signatureCanvas'
}}
/>
<Button onClick={save} className="button-save">Salvar</Button>
<Button onClick={clear} >Apagar Tudo</Button>
<Button onClick={close} className="button-close" >Fechar</Button>
</>
)}
</Popup>
<br/>
<br/>
{ imageURL ? (
<img
src={imageURL}
alt="Minha assinatura Digital"
className="buttons-pad"
/>
) : <h4 style={{ color: 'red'}}>Sem assinatura</h4> }
</div>
</div>
<Form.Item>
<Button type="primary" htmlType="submit" className="button-events">
Cadastrar Novo Evento
</Button>
<br/>
</Form.Item>
</div>
</Form>
<Button
onClick={() => setToCreateFormEvent(false)}
className="button-back-from-create"
>
Voltar para a lista de Eventos
</Button>
</>
}
{ toProfile &&
<>
<ProfileCard organizador={organizador} users={users} assinatura={imageURL}/>
<Button
onClick={() => setProfile(false)}
className="button-back-of-profile"
>
Voltar para a lista de Eventos
</Button>
</>
}
{ toList &&
<>
<ListOfPresents evento={eventChecked}/>
<Button onClick={() => setList(false)} className="button-back-from-list" style={{ marginButtom: '-20%'}}>
Voltar para a lista de Eventos
</Button>
</>
}
{
toSeeEvents &&
<>
<InfoEvent evento={eventChecked}/>
<Button
onClick={() => setSeeEvents(false)}
className="button-back-of-profile"
>
Voltar para a lista de Eventos
</Button>
</>
}
</>
);
}
Example #23
Source File: index.js From topology-react with MIT License | 4 votes |
Header = ({ canvas, history }) => {
const [isLock, setIsLock] = useState(false); // 是否处于锁定状态
const [scaleNumber, setScaleNumber] = useState(1); // 缩放的基数
const [lineStyle, setLineStyle] = useState('直线')
const [fromArrowType, setFromArrowType] = useState('无箭头')
const [toArrowType, setToArrowType] = useState('实心三角形')
/**
* 导入json
*/
const onHandleImportJson = () => {
const input = document.createElement('input');
input.type = 'file';
input.onchange = event => {
const elem = event.srcElement || event.target;
if (elem.files && elem.files[0]) {
const reader = new FileReader();
reader.onload = e => {
const text = e.target.result + '';
try {
const data = JSON.parse(text);
canvas.open(data);
} catch (e) {
return false;
} finally {
}
};
reader.readAsText(elem.files[0]);
}
};
input.click();
}
/**
* 保存为svg
*/
const onHandleSaveToSvg = () => {
const C2S = window.C2S;
const ctx = new C2S(canvas.canvas.width + 200, canvas.canvas.height + 200);
if (canvas.data.pens) {
for (const item of canvas.data.pens) {
item.render(ctx);
}
}
let mySerializedSVG = ctx.getSerializedSvg();
mySerializedSVG = mySerializedSVG.replace(
'<defs/>',
`<defs>
<style type="text/css">
@font-face {
font-family: 'topology';
src: url('http://at.alicdn.com/t/font_1331132_h688rvffmbc.ttf?t=1569311680797') format('truetype');
}
</style>
</defs>`
);
mySerializedSVG = mySerializedSVG.replace(/--le5le--/g, '&#x');
const urlObject = window.URL || window;
const export_blob = new Blob([mySerializedSVG]);
const url = urlObject.createObjectURL(export_blob);
const a = document.createElement('a');
a.setAttribute('download', 'le5le.topology.svg');
a.setAttribute('href', url);
const evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, true);
a.dispatchEvent(evt);
}
/**
* 选中menu时, 触发的函数
*/
const onHandleSelect = data => {
switch (data.key) {
case 'create_new':
canvas.open({ nodes: [], lines: [] });
break;
case 'import_json':
onHandleImportJson();
break;
case 'save_json':
FileSaver.saveAs(
new Blob([JSON.stringify(canvas.data)], { type: 'text/plain;charset=utf-8' }),
`le5le.topology.json`
);
break;
case 'save_png':
canvas.saveAsImage('le5le.topology.png');
break;
case 'save_svg':
onHandleSaveToSvg();
break;
case 'undo':
canvas.undo();
break;
case 'redo':
canvas.redo();
break;
case 'copy':
canvas.copy();
break;
case 'cut':
canvas.cut();
break;
case 'paste':
canvas.paste();
break;
case 'preview':
let reader = new FileReader();
console.log(canvas.data);
const result = new Blob([JSON.stringify(canvas.data)], { type: 'text/plain;charset=utf-8' });
reader.readAsText(result, 'text/plain;charset=utf-8');
reader.onload = (e) => {
history.push({ pathname: '/preview', state: { data: JSON.parse(reader.result) } });
}
break;
default:
break;
}
}
/**
* 放大画布
*/
const scaleZoomOut = () => {
if (scaleNumber < 5) {
setScaleNumber(scaleNumber + 0.5);
canvas.scaleTo(scaleNumber + 0.5)
}
}
/**
* 缩小画布
*/
const scaleZoomIn = () => {
if (scaleNumber > 0.5) {
setScaleNumber(scaleNumber - 0.5);
canvas.scaleTo(scaleNumber - 0.5)
}
}
/**
* 设置默认的连线类型
*/
const onHandleSelectMenu = data => {
setLineStyle(data.item.props.children);
canvas.data.lineName = data.key;
canvas.render();
}
/**
* 设置默认的连线起始箭头
*/
const onHandleSelectMenu1 = data => {
setFromArrowType(data.item.props.children);
canvas.data.fromArrowType = data.key;
canvas.render();
}
/**
* 设置默认的连线终止箭头
*/
const onHandleSelectMenu2 = data => {
setToArrowType(data.item.props.children);
canvas.data.toArrowType = data.key;
canvas.render();
}
/**
* 元素连线之间的选项
*/
const menu2 = (
<Menu onClick={data => onHandleSelectMenu2(data)} style={{ border: 0 }}>
<Menu.Item key="空">
无箭头
</Menu.Item>
<Menu.Item key="triangleSolid">
实心三角形
</Menu.Item>
<Menu.Item key="triangle">
空心三角形
</Menu.Item>
<Menu.Item key="diamondSolid">
实心菱形
</Menu.Item>
<Menu.Item key="diamond">
空心菱形
</Menu.Item>
<Menu.Item key="circleSolid">
实心圆
</Menu.Item>
<Menu.Item key="circle">
空心圆
</Menu.Item>
<Menu.Item key="line">
线型箭头
</Menu.Item>
<Menu.Item key="lineUp">
上单边线箭头
</Menu.Item>
<Menu.Item key="lineDown">
下单边线箭头
</Menu.Item>
</Menu>
);
/**
* 元素连线之间的选项
*/
const menu1 = (
<Menu onClick={data => onHandleSelectMenu1(data)} style={{ border: 0 }}>
<Menu.Item key="空">
无箭头
</Menu.Item>
<Menu.Item key="triangleSolid">
实心三角形
</Menu.Item>
<Menu.Item key="triangle">
空心三角形
</Menu.Item>
<Menu.Item key="diamondSolid">
实心菱形
</Menu.Item>
<Menu.Item key="diamond">
空心菱形
</Menu.Item>
<Menu.Item key="circleSolid">
实心圆
</Menu.Item>
<Menu.Item key="circle">
空心圆
</Menu.Item>
<Menu.Item key="line">
线型箭头
</Menu.Item>
<Menu.Item key="lineUp">
上单边线箭头
</Menu.Item>
<Menu.Item key="lineDown">
下单边线箭头
</Menu.Item>
</Menu>
);
/**
* 连线起始箭头
*/
const menu = (
<Menu onClick={data => onHandleSelectMenu(data)} style={{ border: 0 }}>
<Menu.Item key="line">
直线
</Menu.Item>
<Menu.Item key="polyline">
折线
</Menu.Item>
<Menu.Item key="curve">
曲线
</Menu.Item>
</Menu>
);
return (
<div style={{ height: 48, width: '100vw', borderBottom: '1px solid #e8e8e8' }}>
<Menu mode="horizontal" style={{ width: 500, float: 'left' }} onClick={onHandleSelect}>
<SubMenu
title={
<span className="submenu-title-wrapper">
<Icon type="file" />
文件
</span>
}
>
<Menu.Item key="create_new">新建文件</Menu.Item>
<Menu.Item key="import_json">打开本地文件</Menu.Item>
<Menu.Divider>{}</Menu.Divider>
<Menu.Item key="save_json">保存到本地</Menu.Item>
<Menu.Item key="save_png">保存为PNG</Menu.Item>
<Menu.Item key="save_svg">保存为SVG</Menu.Item>
</SubMenu>
<SubMenu
title={
<span className="submenu-title-wrapper">
<Icon type="edit" />
编辑
</span>
}
>
<Menu.Item key="undo">撤销</Menu.Item>
<Menu.Item key="redo">恢复</Menu.Item>
<Menu.Divider>{}</Menu.Divider>
<Menu.Item key="copy">复制</Menu.Item>
<Menu.Item key="cut">剪切</Menu.Item>
<Menu.Item key="paste">粘贴</Menu.Item>
</SubMenu>
<SubMenu
title={
<span className="submenu-title-wrapper">
<Icon type="global" />
社区
</span>
}
>
<Menu.Item key="issues"><a href="https://github.com/Summer-andy/topology-react/issues" rel="noopener noreferrer" target="_blank">咨询与建议</a></Menu.Item>
<Menu.Item key="github"><a href="https://github.com/Summer-andy/topology-react/" rel="noopener noreferrer" target="_blank">开源github</a></Menu.Item>
<Menu.Item key="docs"> <a href="https://www.yuque.com/alsmile/topology/installation" rel="noopener noreferrer" target="_blank">开发文档</a></Menu.Item>
</SubMenu>
</Menu>
<Tag color="cyan" style={{ float: 'right', right: 10, marginTop: 12 }}>x{scaleNumber}</Tag>
<ButtonGroup style={{ float: 'right', right: 10, marginTop: 7 }}>
<Popover content={menu} title="默认连线类型" trigger="hover">
<Button>{lineStyle}</Button>
</Popover>
<Popover content={menu1} title="默认起点箭头" trigger="hover">
<Button>{fromArrowType}</Button>
</Popover>
<Popover content={menu2} title="默认终点箭头" trigger="hover">
<Button>{toArrowType}</Button>
</Popover>
<Button onClick={() => onHandleSelect({ key: 'preview' })}>
<Icon type="eye" />
预览
</Button>
{
isLock ? <Button onClick={() => { setIsLock(false); canvas.lock(0) }}>
<Icon type="unlock" />
解锁
</Button> : <Button onClick={() => { setIsLock(true); canvas.lock(2) }}>
<Icon type="lock" />
锁定
</Button>
}
<Button onClick={() => scaleZoomOut()}>
<Icon type="plus" />
</Button>
<Button onClick={() => scaleZoomIn()} >
<Icon type="minus" />
</Button>
</ButtonGroup>
</div>
);
}
Example #24
Source File: ProjectDescription.jsx From node-project-manager with Apache License 2.0 | 4 votes |
ProjectDescription = ({ project,projects,removeProject,selectedProject}) => {
const [edited, setEdited] = useState(false);
const [name, setName] = useState(project.nombre);
const [description, setDescription] = useState(project.descripcion);
const [editName, setEditName] = useState(true);
const [editDesc, setEditDesc] = useState(true);
const [showUserEditForm, setShowUserEditForm] = useState(false);
const [showTeacherForm, setShowTeacherForm] = useState(false);
const [showTechForm, setShowTechForm] = useState(false);
const [showSaved, setShowSaved] = useState(true);
const [alertMessage, setAlertMessage] = useState("");
const [typeMessage, setTypeMessage] = useState("");
const openNotification = result => {
// TODO :
switch (result.type){
case "success":
notification.success({
message: `${result.message}`,
placement:'bottomRight'
});
break;
default:
notification.error({
message: `Something went wrong`,
placement:'bottomRight'
});
}
};
const saveProject = async () => {
project.nombre=name;
project.descripcion=description;
const result = await Http.post(project,'/api/projects/updateProject/'+project.id);
if(result){
openNotification(result);
}
setEdited(false);
setEditDesc(true);
setEditName(true);
}
const deleteProject = async() =>{
const result = await Http.get('/api/projects/deleteProject/'+project.id);
if(result){
console.log(result);
selectedProject(projects[1]);
removeProject(project.id);
}
}
//Cada vez que cambiamos de proyecto, seteamos las variables al valor de cada proyecto
useEffect(() => {
setEditName(true);
setEditDesc(true);
setShowSaved(false);
setName(project.nombre);
setDescription(project.descripcion);
setAlertMessage(" ");
setTypeMessage(" ");
}, [project]);
return (
<div className="descripciones">
<Descriptions className="itemsDescripciones"
title={
<span className="titulo">
{project.nombre}
<div className="projectActions">
<Button
type="danger"
onClick={deleteProject}
>
<DeleteOutlined /> Borrar</Button>
</div>
{showSaved ? <div> <Modal
title="Usuario editado"
visible={showSaved}
destroyOnClose={true}
okText="Salir"
onOk={() => {
setShowSaved(!showSaved);
}}
cancelText="Cancelar"
onCancel={() => {
setShowSaved(!showSaved);
}}
><Alert className="alertaUpdate" message={alertMessage} type={typeMessage} /> </Modal></div>:""}
{edited ? (
<span className="botonsitoGuardar">
<Button
type="primary"
shape="round"
icon={<SaveOutlined />}
onClick={saveProject}
>
Guardar
</Button>
</span>
) : (
""
)}
</span>
}
bordered
column={{ xxl: 4, xl: 4, lg: 3, md: 3, sm: 2, xs: 2 }}
>
<Descriptions.Item
className="nombreProyecto"
label={
<span>
Nombre Proyecto
<EditOutlined
onClick={() => {
project.seleccionado = "";
setEditName(!editName);
}}
/>
</span>
}
>
{editName ? (
<span onDoubleClick={()=>{project.seleccionado="";setEditName(!editName)}}>{project.nombre}</span>
) : (
<Input
defaultValue={project.nombre}
onChange={(e) => {
setName(e.target.value);
setEdited(true);
}}
size="small"
/>
)}
</Descriptions.Item>
<Descriptions.Item className="alumnos" label={<span> Alumnos <EditOutlined
onClick={()=>{
setShowUserEditForm(!showUserEditForm);
}}/></span>}>
<Modal
title="Editar Alumnos"
visible={showUserEditForm}
destroyOnClose={true}
okText="Salir"
onOk={() => {
setEdited(true);
setShowUserEditForm(!showUserEditForm);
}}
cancelText="Cancelar"
onCancel={() => {
setShowUserEditForm(!showUserEditForm);
}}
>
<TransferFormStudents/>
</Modal>
{project.usuarios.alumnos
? project.usuarios.alumnos.map((usr) => {
usr.icon = require("../../img/" + usr.avatar);
return (
<Popover content={contentPopOverUsers(usr)} key={usr.id}>
<Avatar src={usr.icon} />
</Popover>
);
})
: ""}
</Descriptions.Item>
<Descriptions.Item className="profesores"label={<span>Profesores <EditOutlined
onClick={()=>{
setShowTeacherForm(!showTeacherForm);
}}/></span>}>
<Modal
title="Editar Alumnos"
visible={showTeacherForm}
destroyOnClose={true}
okText="Salir"
onOk={() => {
setEdited(true);
setShowTeacherForm(!showTeacherForm);
}}
cancelText="Cancelar"
onCancel={() => {
setShowTeacherForm(!showTeacherForm);
}}
>
<TransferFormTeachers/>
</Modal>
{project.usuarios.profesores
? project.usuarios.profesores.map((usr) => {
usr.icon = require("../../img/" + usr.avatar);
return (
<Popover content={contentPopOverUsers(usr)} key={usr.id}>
<Avatar src={usr.icon} />
</Popover>
);
})
: ""}
</Descriptions.Item>
<Descriptions.Item className="tecnologias" label={<span>Tecnologías <EditOutlined
onClick={()=>{
setShowTechForm(!showTechForm);
}}/></span>}>
<Modal
title="Editar usuarios"
visible={showTechForm}
destroyOnClose={true}
okText="Salir"
onOk={() => {
setEdited(true);
setShowTechForm(!showTechForm);
}}
cancelText="Cancelar"
onCancel={() => {
setShowTechForm(!showTechForm);
}}
>
<TransferTechForm/>
</Modal>
{project.tecnologias
? project.tecnologias.map((tech) => {
tech.icon = require("../../img/techs/" + tech.logo);
return (
<Popover content={contentPopOverTechs(tech)} key={tech.id}>
<Avatar src={tech.icon} />
</Popover>
);
})
: ""}
</Descriptions.Item>
<Descriptions.Item
className="descripciones"
label={
<span>
Descripcion
<EditOutlined
onClick={() => {
project.seleccionado = "";
setEditDesc(!editDesc);
}}
/>
</span>
}
>
{editDesc ? (
<pre onDoubleClick={()=>{project.seleccionado = ""; setEditDesc(!editDesc)}}>{project.descripcion}</pre>
) : (
<Input.TextArea
defaultValue={project.descripcion}
onChange={(e) => {
setDescription(e.target.value);
setEdited(true);
}
}
size="small"
/>
)}
</Descriptions.Item>
</Descriptions>
</div>
);
}
Example #25
Source File: index.js From scalable-form-platform with MIT License | 4 votes |
render() {
const {fileList} = this.state;
const messages = this.props.formContext && this.props.formContext.messages;
let schema = this.props.schema;
let options = this.props.options,
disabled = this.props.disabled,
onChange = this.props.onChange;
// templateFileUrl表示配置的模板地址,如果该字段非空字符串,则在提交按钮右侧展示“模板”;exampleImageUrl表示配置的示例图片,如果该字段非空字符串,则在字段下面展示“示例图片”
let {_errorType, validate, label, uploadType, vertical, listType, templateFileUrl, exampleImageUrl, ...otherOptions} = options;
let maxFileNum = schema.maxFileNum || Infinity;
let maxFileSize = schema.maxFileSize || Infinity;
if (uploadType === 'picture') {
vertical = true;
listType = 'picture';
} else if (uploadType === 'picture-inline') {
vertical = false;
listType = 'picture';
} else if (uploadType === 'picture-card') {
vertical = true;
listType = 'picture-card';
} else {
vertical = false;
listType = 'text';
}
//解析schema中约定的_errorType字段,用来标识是validate中哪种类型校验不通过
let validateMessage = '';
_errorType = _errorType || '';
if (_errorType !== '' && typeof validate !== 'undefined') {
validateMessage = this._getValidateMessage(_errorType, validate);
}
const uploader = (
<Upload
multiple
disabled={disabled}
customRequest={this._customRequest}
withCredentials
beforeUpload={(file, fileList) => {
const filename = file.name;
const blacklistExts = ['php', 'js', 'html', 'htm', 'shtml', 'shtm'];
const current = this.state.fileList;
const ext = filename.slice(filename.lastIndexOf('.') + 1).toLowerCase();
// 文件的扩展名不能在黑名单里
if (blacklistExts.indexOf(ext) > -1) {
message.error(messages[getMessageId('xformUploaderFileCheckMessage')]);
return false;
}
// 文件数量不能超出最大限制
if (fileList.length + current.length > maxFileNum) {
message.error(messages[getMessageId('xformMaxFileNumErrorTip')]);
return false;
}
// 文件大小不能超过配置
if (file.size > maxFileSize * 1024 * 1024) {
message.error(file.name + messages[getMessageId('xformMaxFileSizeErrorTip')] + maxFileSize + 'M');
return false;
}
return true;
}}
onChange={(info) => {
const current = this.state.fileList;
let fileList = info.fileList;
let file = info.file;
const filename = file.name;
const blacklistExts = ['php', 'js', 'html', 'htm', 'shtml', 'shtm'];
const ext = filename.slice(filename.lastIndexOf('.') + 1).toLowerCase();
if (info.file.status === 'error') {
message.error(info.file.name + messages[getMessageId('xformUploadErrorTip')]);
}
// 文件数量不能超出最大限制
// 文件大小不能超过配置
// 文件扩展名不能在黑名单里
if ((fileList.length > maxFileNum) ||
(file.size > maxFileSize * 1024 * 1024) ||
(blacklistExts.indexOf(ext) > -1)) {
this.setState({
fileList: current
});
} else {
this.setState({
fileList
});
}
}}
onRemove={(file) => {
// 如果是字段禁用状态,不允许删除
if (disabled) {
return false;
}
const {fileList} = this.state;
const filterFileList = fileList.filter((fileItem) => {
return file.uid !== fileItem.uid;
});
this.setState({
fileList: filterFileList
});
// const submitFileList = filterFileList.filter((fileItem) => {
// return !(fileItem.originFileObj);
// });
onChange(filterFileList);
}}
onPreview={(previewFile) => {
const fileList = this.state.fileList;
let url;
fileList.map((file) => {
if (file.uid === previewFile.uid) {
url = file.url;
}
});
this.handleImageView(url);
}}
fileList={fileList}
listType={listType}
{...otherOptions}
>
<Tooltip placement="top" title={messages[getMessageId('xformBatchUploadToolTip')]}>
<Button type="ghost" disabled={disabled}>
<Icon type="upload" />
{label || messages[getMessageId('xformBatchUploadDefaultLabel')]}
</Button>
</Tooltip>
</Upload>
);
let uploaderActionWrapper = '';
if (typeof templateFileUrl !== 'undefined' && templateFileUrl.length > 0) {
if (typeof exampleImageUrl !== 'undefined' && exampleImageUrl.length > 0) {
uploaderActionWrapper = (
<div className="uploader-action-wrapper">
{uploader}
<a href={templateFileUrl[0].url} className="template-trigger-link" download={templateFileUrl[0].name}>{messages[getMessageId('xformFileTemplateLabel')]}</a>
<div className="example-pic-wrapper">
<p className="example-pic-trigger-label">{messages[getMessageId('xformExampleImageLabel')]}</p>
<Popover
content={(<img src={exampleImageUrl[0].url} onClick={() => {this.handleImageView(exampleImageUrl[0].url);}} />)}
overlayClassName="xform-custom-uploader-popover"
arrowPointAtCenter
>
<img className="example-pic-trigger" src={exampleImageUrl[0].url} onClick={() => {this.handleImageView(exampleImageUrl[0].url);}} />
</Popover>
</div>
</div>
);
} else {
uploaderActionWrapper = (
<div className="uploader-action-wrapper">
{uploader}
<a href={templateFileUrl[0].url} className="template-trigger-link" download={templateFileUrl[0].name}>{messages[getMessageId('xformFileTemplateLabel')]}</a>
</div>
);
}
} else {
if (typeof exampleImageUrl !== 'undefined' && exampleImageUrl.length > 0) {
uploaderActionWrapper = (
<div className="uploader-action-wrapper">
{uploader}
<div className="example-pic-wrapper">
<p className="example-pic-trigger-label">{messages[getMessageId('xformExampleImageLabel')]}</p>
<Popover
content={(<img src={exampleImageUrl[0].url} onClick={() => {this.handleImageView(exampleImageUrl[0].url);}} />)}
overlayClassName="xform-custom-uploader-popover"
arrowPointAtCenter
>
<img className="example-pic-trigger" src={exampleImageUrl[0].url} onClick={() => {this.handleImageView(exampleImageUrl[0].url);}} />
</Popover>
</div>
</div>
);
} else {
uploaderActionWrapper = (
<div className="uploader-action-wrapper">
{uploader}
</div>
);
}
}
return (
<div className={classnames({
'ant-form-item-control': true,
'xform-custom-widget': true,
'xform-custom-uploader': true,
'upload-list-inline': !vertical,
'has-error': _errorType !== ''
})}>
{uploaderActionWrapper}
<div className="ant-form-explain">{validateMessage}</div>
</div>
);
}
Example #26
Source File: index.js From AgileTC with Apache License 2.0 | 4 votes |
render() {
const {
minder,
noteContent,
showEdit,
inputContent,
noteNode,
activeTab,
showToolBar,
fullScreen,
loading,
isLock,
locked,
// undoCnt,
// redoCnt,
popoverVisible,
nowUseList,
} = this.state;
const {
progressShow = true,
readOnly = false,
editorStyle = {},
tags,
wsUrl = '',
wsParam,
callback,
iscore,
type,
} = this.props;
const childProps = {
...this.props,
minder,
isLock,
};
const tabContentClass = `toolbar has-right-border`;
return (
<ConfigProvider locale={zhCN}>
<div
className={`kityminder-editor-container${
fullScreen ? ' full-screen' : ''
}`}
style={editorStyle}
>
{minder && type !== 'compare' && (
<Socket
url={wsUrl}
wsParam={wsParam}
onOpen={this.handleWsOpen}
onMessage={this.handleWsData}
onClose={this.handleWsClose}
wsMinder={this.minder}
handleLock={this.handleLock}
handleWsUserStat={this.handleWsUserStat}
// onError={e => {
// notification.info({
// message: 'websocket连接错误,错误详情:' + e,
// });
// }}
// reconnect={false}
ref={ws => {
this.ws = ws;
window.ws = ws;
}}
/>
)}
{minder && (
<Tabs
activeKey={activeTab}
className={`kityminder-tools-tab${
showToolBar ? '' : ' collapsed'
}`}
tabBarExtraContent={[
<Popover
key="list"
placement="bottomRight"
content={
<List
grid={{
gutter: 30,
column: nowUseList.length >= 4 ? 4 : 1,
}}
itemLayout="horizontal"
dataSource={nowUseList || []}
renderItem={item => (
<List.Item>
<List.Item.Meta
avatar={
<Avatar
style={{
backgroundColor: this.getColorByName(item),
}}
>
{item.substr(0, 1)}
</Avatar>
}
title={
<div style={{ lineHeight: '32px' }}>{item}</div>
}
/>
</List.Item>
)}
/>
}
trigger="click"
visible={popoverVisible}
onVisibleChange={visible =>
this.setState({ popoverVisible: visible })
}
>
<Tooltip title={'当前在线列表'}>
<Button
type="primary"
style={{ marginRight: 15 }}
onClick={() =>
this.setState({ popoverVisible: !popoverVisible })
}
>
{nowUseList ? nowUseList.length : 1}人在线
</Button>
</Tooltip>
</Popover>,
<Tooltip
key="lock"
title={
isLock || locked
? '用例被锁住,当前只读,点击开关解锁。'
: '用例未上锁,点击开关锁住。'
}
getPopupContainer={triggerNode => triggerNode.parentNode}
>
{type !== 'compare' && (
<Switch
size="small"
checkedChildren={<Icon type="lock" />}
unCheckedChildren={<Icon type="unlock" />}
checked={isLock || locked}
onClick={checked => {
this.ws.sendMessage('lock', {message: checked ? 'lock' : 'unlock'});
}}
className="agiletc-lock"
/>
)}
</Tooltip>,
<Button
key="full"
type="link"
icon={`fullscreen${fullScreen ? '-exit' : ''}`}
onClick={() => {
this.setState({ fullScreen: !fullScreen });
callback && callback({ fullScreen: !fullScreen });
}}
>
{fullScreen ? '退出全屏' : '全屏'}
</Button>,
<Button
key="show"
type="link"
onClick={() => this.setState({ showToolBar: !showToolBar })}
>
<Icon type="double-left" rotate={showToolBar ? 90 : -90} />{' '}
{showToolBar ? '收起' : '展开'}
</Button>,
]}
onChange={activeKey => {
this.setState({ activeTab: activeKey });
}}
>
{type !== 'compare' && (
<TabPane tab="思路" key="1">
<div className={tabContentClass}>
<DoGroup
ref={groupNode => (this.groupNode = groupNode)}
initData={this.initData}
{...childProps}
/>
{!readOnly && (
<Nodes
initData={this.initData}
{...childProps}
callback={() => {
setTimeout(this.handleShowInput, 300);
}}
/>
)}
{!readOnly && <DoMove {...childProps} />}
{!readOnly && (
<OperationGroup
{...childProps}
handleShowInput={this.handleShowInput}
/>
)}
<MediaGroup {...childProps} />
{!readOnly && <PriorityGroup {...childProps} />}
{progressShow && <ProgressGroup {...childProps} />}
{!readOnly && tags && <TagGroup {...childProps} />}
</div>
</TabPane>
)}
<TabPane tab="外观" key={type !== 'compare' ? '2' : '1'}>
<div className={tabContentClass}>
<ThemeGroup {...childProps} />
<TemplateGroup {...childProps} />
{type !== 'compare' && (
<React.Fragment>
<ResetLayoutGroup {...childProps} />
<StyleGroup {...childProps} />
<FontGroup {...childProps} />
</React.Fragment>
)}
</div>
</TabPane>
{type !== 'compare' && (
<TabPane tab="视图" key="3">
<div className={tabContentClass}>
<ViewGroup {...childProps} />
</div>
</TabPane>
)}
</Tabs>
)}
<div
className="kityminder-core-container"
ref={input => {
if (!this.minder) {
this.minder = new window.kityminder.Minder({
renderTo: input,
});
this.centerNode = input;
this.initOnEvent(this.minder);
this.initHotbox(this.minder);
}
}}
style={{
height: `calc(100% - 45px - ${showToolBar ? '80px' : '0px'})`,
}}
>
{loading && <Spin className="agiletc-loader" />}
</div>
<NavBar ref={this.navNode} {...childProps} />
{this.minder && noteContent && (
<div
ref={previewNode => (this.previewNode = previewNode)}
className={`note-previewer${noteContent ? '' : ' hide'}`}
dangerouslySetInnerHTML={{ __html: noteContent }}
onMouseEnter={() => this.minder.fire('shownoterequest', noteNode)}
/>
)}
{this.minder && (
<div
className={`edit-input${showEdit ? '' : ' hide'}`}
ref={inputNode => (this.inputNode = inputNode)}
>
<Input.TextArea
rows={1}
value={inputContent || ''}
onChange={this.handleInputChange}
onBlur={() => {
// minder.setStatus('readonly');
minder.refresh();
// this.minder.setStatus('normal');
minder.fire('contentchange');
}}
style={{ minWidth: 300 }}
autoFocus
autoSize
/>
</div>
)}
</div>
<div
style={{
display: 'inline-block',
position: 'fixed',
bottom: '30px',
right: '20px',
zIndex: 999,
}}
>
{iscore != 2 && (
<Button type="primary" onClick={this.onButtonSave}>
保存
</Button>
)}
<span> </span>
{iscore == 3 && (
<Button type="primary" onClick={this.onButtonClear} >
清除执行记录
</Button>
)}
</div>
</ConfigProvider>
);
}
Example #27
Source File: index.jsx From juno with Apache License 2.0 | 4 votes |
render() {
const {
app_service_tree,
use_cases,
editor,
selected_user_case,
node_addr_list,
selected_service,
right_menu_visible,
right_menu_position,
right_menu,
dispatch,
response,
active_tab,
selected_history_id,
public_cases,
settings,
setting_dialog_visible,
service_bind_dialog_visible,
proto_list,
appList,
use_case_loading,
} = this.props;
let addrOptions = node_addr_list?.hosts
? node_addr_list.hosts
.filter((i) => i.env !== 'prod' && i.env !== 'gray')
.map((item) => {
return (
<AutoComplete.Option key={item.addr} value={item.addr + ':' + node_addr_list.port}>
<Tag>{item.env}</Tag>
<span>
{item.addr}:{node_addr_list.port}
</span>
</AutoComplete.Option>
);
})
: [];
if (settings && settings.localhost) {
addrOptions.push(
<AutoComplete.Option
key={settings.localhost}
value={settings.localhost + ':' + node_addr_list.port}
>
<Tag>local</Tag>
<span>
{settings.localhost}:{node_addr_list.port}
</span>
</AutoComplete.Option>,
);
}
let metadata = editor.form.metadata || [];
if (!(metadata instanceof Array)) {
try {
metadata = JSON.parse(metadata);
} catch (e) {
metadata = [];
}
}
return (
<div className={styles.debugPage}>
<div className={styles.layoutHeader}>
<Cascader
showSearch
value={selected_service}
className={styles.serviceCascader}
displayRender={(labels) => {
return labels.join('/');
}}
placeholder="切换服务"
options={(app_service_tree || []).map((app) => {
return {
label: app.app_name,
value: app.app_name,
children: (app.services || []).map((service) => {
return {
value: '' + service.id,
label: service.name,
};
}),
};
})}
onChange={this.onChangeService}
/>
<Button
shape="circle"
icon={<SettingOutlined />}
className={styles.settingButton}
onClick={this.onShowSettingDialog}
/>
<Button
shape="circle"
icon={<LinkOutlined />}
className={styles.bindServiceButton}
onClick={this.onShowServiceBindDialog}
/>
</div>
<div className={styles.main}>
<div className={styles.layoutSider}>
<Tabs
type={'card'}
className={styles.leftTabs}
activeKey={active_tab}
onChange={this.onTabChange}
renderTabBar={(props, DefaultTabBar) => {
return (
<DefaultTabBar
{...props}
style={{
backgroundColor: 'rgb(250,250,250)',
padding: '10px 0 0 10px',
margin: '0',
flex: '0 0 50px',
}}
/>
);
}}
>
<Tabs.TabPane key="history" tab="History">
{active_tab === 'history' ? (
<History
selectedService={selected_service}
onChange={(id) => {
dispatch({ type: 'grpcDebugModel/loadHistoryItem', payload: id }).then(
(res) => {
if (res.code === 0) {
this.form.current.setFieldsValue({
case_name: editor.form.case_name,
address: res.data.addr,
});
}
},
);
}}
activeId={selected_history_id}
/>
) : null}
</Tabs.TabPane>
<Tabs.TabPane key="api" tab="API">
<ScrollArea style={{ height: '830px' }}>
<DirectoryTree
onRightClick={this.onUserCaseTreeRightClicked}
defaultExpandAll
onSelect={this.onSelectUserCaseTree}
selectedKeys={[selected_user_case]}
style={{ marginTop: '10px' }}
>
{(use_cases || []).map((method, id) => {
return (
<TreeNode
title={
method.description ? (
<Popover content={method.description}>{method.name}</Popover>
) : (
method.name
)
}
key={`method:${method.id}`}
>
<TreeNode
icon={<PlusOutlined />}
key={`new:${method.id}`}
title="New"
isLeaf
/>
{method.use_cases
? method.use_cases.map((tc, id) => {
return <TreeNode title={tc.name} key={`case:${tc.id}`} isLeaf />;
})
: null}
</TreeNode>
);
})}
</DirectoryTree>
</ScrollArea>
</Tabs.TabPane>
</Tabs>
</div>
{editor.form.method_id ? (
<Spin spinning={use_case_loading} wrapperClassName={styles.formSpin}>
{this.renderForm(editor, addrOptions, metadata, response)}
</Spin>
) : (
<div style={{ flex: '1 1 auto', padding: '100px' }}>
<Empty desciption={'请选择用例'} />
</div>
)}
</div>
<SettingDialog
onCancel={() => {
dispatch({
type: 'grpcDebugModel/showSettings',
payload: false,
});
}}
settings={settings}
onSave={this.onSaveSettings}
visible={setting_dialog_visible}
/>
<ServiceBindDialog
visible={service_bind_dialog_visible}
protoList={proto_list}
appList={appList}
onSubmit={this.onBindAppService}
onCancel={() => {
dispatch({
type: 'grpcDebugModel/showServiceBindDialog',
payload: false,
});
}}
/>
</div>
);
}
Example #28
Source File: Cluster.js From kafka-map with Apache License 2.0 | 4 votes |
render() {
const columns = [{
title: <FormattedMessage id="index"/>,
dataIndex: 'id',
key: 'id',
render: (id, record, index) => {
return index + 1;
}
}, {
title: <FormattedMessage id="name"/>,
dataIndex: 'name',
key: 'name',
render: (name, record) => {
let short = name;
if (short && short.length > 30) {
short = short.substring(0, 30) + " ...";
}
return (
<Tooltip placement="topLeft" title={name}>
{short}
</Tooltip>
);
},
sorter: true,
}, {
title: <FormattedMessage id="servers"/>,
dataIndex: 'servers',
key: 'servers',
}, {
title: <FormattedMessage id="delay-message"/>,
dataIndex: 'delayMessageStatus',
key: 'delayMessageStatus',
render: (delayMessageStatus, record, index) => {
return <Popover content={content}>
<Switch checked={delayMessageStatus === 'enabled'}
onChange={async (checked) => {
let url = `/clusters/${record['id']}/disableDelayMessage`;
if (checked) {
url = `/clusters/${record['id']}/enableDelayMessage`;
}
await request.post(url);
this.loadTableData()
}
}/>
</Popover>
}
}, {
title: <FormattedMessage id="topic"/>,
dataIndex: 'topicCount',
key: 'topicCount',
render: (topicCount, record, index) => {
return <Link
to={`/topic?clusterId=${record['id']}&clusterName=${record['name']}&brokerCount=${record['brokerCount']}`}>
{topicCount}
</Link>
}
}, {
title: <FormattedMessage id="broker"/>,
dataIndex: 'brokerCount',
key: 'brokerCount',
render: (brokerCount, record, index) => {
return <Link to={`/broker?clusterId=${record['id']}&clusterName=${record['name']}`}>
{brokerCount}
</Link>
}
}, {
title: <FormattedMessage id="consumer-group"/>,
dataIndex: 'consumerCount',
key: 'consumerCount',
render: (consumerCount, record, index) => {
return <Link to={`/consumer-group?clusterId=${record['id']}&clusterName=${record['name']}`}>
{consumerCount}
</Link>
}
}, {
title: <FormattedMessage id="created"/>,
dataIndex: 'created',
key: 'created',
render: (text, record) => {
return (
<Tooltip title={text}>
{dayjs(text).fromNow()}
</Tooltip>
)
},
sorter: true,
},
{
title: <FormattedMessage id="operate"/>,
key: 'action',
render: (text, record, index) => {
return (
<div>
<Button type="link" size='small' onClick={() => {
this.showModal(<FormattedMessage id="edit"/>, record)
}}><FormattedMessage id="edit"/></Button>
<Popconfirm
title={<FormattedMessage id="delete-confirm"/>}
onConfirm={() => this.delete(record['id'])}
>
<Button type="text" size='small' danger><FormattedMessage id="delete"/></Button>
</Popconfirm>
</div>
)
},
}
];
const selectedRowKeys = this.state.selectedRowKeys;
const rowSelection = {
selectedRowKeys: this.state.selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
this.setState({selectedRowKeys});
},
};
const hasSelected = selectedRowKeys.length > 0;
return (
<div className='kd-content'>
<div style={{marginBottom: 20}}>
<Row justify="space-around" align="middle" gutter={24}>
<Col span={12} key={1}>
<Title level={3}><FormattedMessage id="cluster"/></Title>
</Col>
<Col span={12} key={2} style={{textAlign: 'right'}}>
<Space>
<Search
ref={this.inputRefOfName}
placeholder={'name'}
allowClear
onSearch={this.handleSearchByName}
/>
<Tooltip title={<FormattedMessage id="reset"/>}>
<Button icon={<UndoOutlined/>} onClick={() => {
this.inputRefOfName.current.setValue('');
this.loadTableData({pageIndex: 1, pageSize: 10, name: ''})
}}>
</Button>
</Tooltip>
<Divider type="vertical"/>
<Tooltip title={<FormattedMessage id="import-cluster"/>}>
<Button type="dashed" icon={<PlusOutlined/>}
onClick={() => this.showModal(<FormattedMessage id="import-cluster"/>)}>
</Button>
</Tooltip>
<Tooltip title={<FormattedMessage id="refresh"/>}>
<Button icon={<SyncOutlined/>} onClick={() => {
this.loadTableData(this.state.queryParams)
}}>
</Button>
</Tooltip>
<Tooltip title={<FormattedMessage id="batch-delete"/>}>
<Button type="primary" danger disabled={!hasSelected} icon={<DeleteOutlined/>}
loading={this.state.delBtnLoading}
onClick={() => {
const content = <div>
Are you sure delete <Text style={{color: '#1890FF'}}
strong>{this.state.selectedRowKeys.length}</Text> items?
</div>;
confirm({
icon: <ExclamationCircleOutlined/>,
content: content,
onOk: () => {
this.batchDelete()
},
onCancel() {
},
});
}}>
</Button>
</Tooltip>
</Space>
</Col>
</Row>
</div>
<Table
rowSelection={rowSelection}
rowKey='id'
dataSource={this.state.items}
columns={columns}
position={'both'}
pagination={{
showSizeChanger: true,
current: this.state.queryParams.pageIndex,
pageSize: this.state.queryParams.pageSize,
onChange: this.handleChangPage,
onShowSizeChange: this.handleChangPage,
total: this.state.total,
showTotal: total => {
return <FormattedMessage id="total-items" values={{total: total}}/>
}
}}
loading={this.state.loading}
/>
{
this.state.modalVisible ?
<ClusterModal
title={this.state.modalTitle}
handleOk={this.handleOk}
handleCancel={this.handleCancelModal}
confirmLoading={this.state.modalConfirmLoading}
model={this.state.model}
/> : undefined
}
</div>
);
}
Example #29
Source File: UserShareSelectedAsset.js From next-terminal with GNU Affero General Public License v3.0 | 4 votes |
render() {
const columns = [{
title: '序号',
dataIndex: 'id',
key: 'id',
render: (id, record, index) => {
return index + 1;
}
}, {
title: '资产名称',
dataIndex: 'name',
key: 'name',
render: (name, record) => {
let short = name;
if (short && short.length > 15) {
short = short.substring(0, 15) + " ...";
}
return (
<Tooltip placement="topLeft" title={name}>
{short}
</Tooltip>
);
}
}, {
title: '协议',
dataIndex: 'protocol',
key: 'protocol',
render: (text, record) => {
const title = `${record['ip'] + ':' + record['port']}`
return (
<Tooltip title={title}>
<Tag color={PROTOCOL_COLORS[text]}>{text}</Tag>
</Tooltip>
)
}
}, {
title: '标签',
dataIndex: 'tags',
key: 'tags',
render: tags => {
if (!isEmpty(tags)) {
let tagDocuments = []
let tagArr = tags.split(',');
for (let i = 0; i < tagArr.length; i++) {
if (tags[i] === '-') {
continue;
}
tagDocuments.push(<Tag key={tagArr[i]}>{tagArr[i]}</Tag>)
}
return tagDocuments;
}
}
}, {
title: '状态',
dataIndex: 'active',
key: 'active',
render: text => {
if (text) {
return (
<Tooltip title='运行中'>
<Badge status="processing" text='运行中'/>
</Tooltip>
)
} else {
return (
<Tooltip title='不可用'>
<Badge status="error" text='不可用'/>
</Tooltip>
)
}
}
}, {
title: '所有者',
dataIndex: 'ownerName',
key: 'ownerName'
}, {
title: '创建日期',
dataIndex: 'created',
key: 'created',
render: (text, record) => {
return (
<Tooltip title={text}>
{dayjs(text).fromNow()}
</Tooltip>
)
}
},
];
const selectedRowKeys = this.state.selectedRowKeys;
const rowSelection = {
selectedRowKeys: this.state.selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
this.setState({selectedRowKeys, selectedRows});
},
getCheckboxProps: (record) => ({
disabled: record['disabled'],
}),
};
let hasSelected = false;
if (selectedRowKeys.length > 0) {
let totalSelectedRows = this.state.totalSelectedRows;
let allSelectedRowKeys = totalSelectedRows.map(item => item['id']);
for (let i = 0; i < selectedRowKeys.length; i++) {
let selectedRowKey = selectedRowKeys[i];
if (!allSelectedRowKeys.includes(selectedRowKey)) {
hasSelected = true;
break;
}
}
}
const renderStatus = (text) => {
if (text === '1') {
return <Tag color={'green'}>允许</Tag>
} else {
return <Tag color={'red'}>禁止</Tag>
}
}
return (
<>
<Row gutter={16}>
<Col span={6}>
<Title level={3}>授权策略</Title>
<Select style={{minWidth: 200}} onChange={(strategyId) => {
this.setState({
'strategyId': strategyId
})
}}>
{this.state.strategies.map(item => {
return (
<Select.Option key={item.id}>{item.name}</Select.Option>
);
})}
</Select>
</Col>
<Col span={18}>
<Title level={3}>已授权资产列表</Title>
<div>
{
this.state.totalSelectedRows.map(item => {
let strategyName = '「未配置策略」';
let content = '';
if (item['strategy'] !== undefined) {
strategyName = item['strategy']['name'];
content = (
<div>
<p>上传:{renderStatus(item['strategy']['upload'])}</p>
<p>下载:{renderStatus(item['strategy']['download'])}</p>
<p>编辑:{renderStatus(item['strategy']['edit'])}</p>
<p>删除:{renderStatus(item['strategy']['delete'])}</p>
<p>重命名:{renderStatus(item['strategy']['rename'])}</p>
<p>复制:{renderStatus(item['strategy']['copy'])}</p>
<p>粘贴:{renderStatus(item['strategy']['paste'])}</p>
</div>
);
}
return (
<Popover content={content} title={strategyName}>
<Tag color={PROTOCOL_COLORS[item['protocol']]} closable
onClose={(e) => {
e.preventDefault()
this.unSelectRow(item['id'])
}}
key={item['id']}>{[item['name'], strategyName].join(':')}</Tag>
</Popover>
);
})
}
</div>
</Col>
</Row>
<Divider/>
<Content key='page-content' className="site-layout-background">
<div style={{marginBottom: 20}}>
<Row justify="space-around" align="middle" gutter={24}>
<Col span={4} key={1}>
<Title level={3}>全部资产列表</Title>
</Col>
<Col span={20} key={2} style={{textAlign: 'right'}}>
<Space>
<Search
ref={this.inputRefOfName}
placeholder="资产名称"
allowClear
onSearch={this.handleSearchByName}
style={{width: 200}}
/>
<Search
ref={this.inputRefOfIp}
placeholder="资产IP"
allowClear
onSearch={this.handleSearchByIp}
style={{width: 200}}
/>
<Select mode="multiple"
allowClear
placeholder="资产标签" onChange={this.handleTagsChange}
style={{minWidth: 150}}>
{this.state.tags.map(tag => {
if (tag === '-') {
return undefined;
}
return (<Select.Option key={tag}>{tag}</Select.Option>)
})}
</Select>
<Select onChange={this.handleSearchByProtocol}
value={this.state.queryParams.protocol ? this.state.queryParams.protocol : ''}
style={{width: 100}}>
<Select.Option value="">全部协议</Select.Option>
<Select.Option value="rdp">rdp</Select.Option>
<Select.Option value="ssh">ssh</Select.Option>
<Select.Option value="vnc">vnc</Select.Option>
<Select.Option value="telnet">telnet</Select.Option>
</Select>
<Tooltip title='重置查询'>
<Button icon={<UndoOutlined/>} onClick={() => {
this.inputRefOfName.current.setValue('');
this.inputRefOfIp.current.setValue('');
this.loadTableData({
...this.state.queryParams,
pageIndex: 1,
pageSize: 10,
protocol: ''
})
}}>
</Button>
</Tooltip>
<Divider type="vertical"/>
<Tooltip title="刷新列表">
<Button icon={<SyncOutlined/>} onClick={() => {
this.loadTableData(this.state.queryParams)
}}>
</Button>
</Tooltip>
<Tooltip title="添加授权">
<Button type="primary" disabled={!hasSelected} icon={<PlusOutlined/>}
onClick={async () => {
let totalSelectedRows = this.state.totalSelectedRows;
let totalSelectedRowKeys = totalSelectedRows.map(item => item['id']);
let selectedRows = this.state.selectedRows;
let newRowKeys = []
for (let i = 0; i < selectedRows.length; i++) {
let selectedRow = selectedRows[i];
if (totalSelectedRowKeys.includes(selectedRow['id'])) {
continue;
}
selectedRow['strategy'] = this.getStrategyByAssetId(this.state.strategies, this.state.sharers, selectedRow['id'], this.state.strategyId);
totalSelectedRows.push(selectedRow);
newRowKeys.push(selectedRow['id']);
}
let userId = this.state.sharer;
let userGroupId = this.state.userGroupId;
let strategyId = this.state.strategyId;
let result = await request.post(`/resource-sharers/add-resources`, {
userGroupId: userGroupId,
userId: userId,
strategyId: strategyId,
resourceType: 'asset',
resourceIds: newRowKeys
});
if (result['code'] === 1) {
message.success('操作成功', 3);
this.setState({
totalSelectedRows: totalSelectedRows
})
await this.loadTableData();
} else {
message.error(result['message'], 10);
}
}}>
</Button>
</Tooltip>
</Space>
</Col>
</Row>
</div>
<Table key='assets-table'
rowSelection={rowSelection}
dataSource={this.state.items}
columns={columns}
position={'both'}
pagination={{
showSizeChanger: true,
current: this.state.queryParams.pageIndex,
pageSize: this.state.queryParams.pageSize,
onChange: this.handleChangPage,
onShowSizeChange: this.handleChangPage,
total: this.state.total,
showTotal: total => `总计 ${total} 条`
}}
loading={this.state.loading}
/>
</Content>
</>
);
}