lodash#filter JavaScript Examples
The following examples show how to use
lodash#filter.
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: PageScriptModal.js From hzero-front with Apache License 2.0 | 6 votes |
handleScriptRemove(record, e) {
if (e && e.preventDefault) {
e.preventDefault();
}
const { editRecord, dataSource } = this.state;
const nextState = {};
if (editRecord === record) {
nextState.editRecord = null;
nextState.scriptEditProps = {};
}
nextState.dataSource = filter(dataSource, r => r !== record);
this.setState(nextState);
}
Example #2
Source File: DailyCountsCell.js From covid19 with MIT License | 6 votes |
Success = ({
// Query data
dailyCounts = [],
countries = [],
// Inherited read-only from hooks
enabledCountries = [],
defaultCountry = 'usa'
// log = false
}) => {
const filteredCounts = filter(dailyCounts, (count) =>
enabledCountries.includes(count.country.iso)
)
return (
<Chart
dailyCounts={filteredCounts}
defaultCountry={defaultCountry}
enabledCountries={enabledCountries}
countries={countries}
// log={log}
/>
)
}
Example #3
Source File: ComposeTableEditModal.js From hzero-front with Apache License 2.0 | 6 votes |
getValidateDataSource() {
const { dataSource } = this.state;
const { rowKey = 'id' } = this.props;
return Promise.resolve(
map(filter(dataSource, r => r.isCreate || r.isUpdate), r => {
if (r.isCreate) {
return omit(r, ['isCreate', 'isUpdate', rowKey]);
}
return omit(r, ['isCreate', 'isUpdate']);
})
);
}
Example #4
Source File: addModerators.js From haven with MIT License | 6 votes |
onChangeState(peerID) {
const { selected } = this.state;
const idx = findIndex(selected, o => o === peerID);
if (idx >= 0) {
const newArray = filter(selected, o => o !== peerID);
this.setState({
selected: newArray,
});
} else {
this.setState({
selected: [...selected, peerID],
});
}
}
Example #5
Source File: RequestsContainer.js From covidsos with MIT License | 6 votes |
getCount(type) {
const {allRequests, isLoading} = this.state;
if (isLoading) {
return 'Loading';
}
if (!type) {
return (allRequests && allRequests.length) || 0;
}
return (allRequests && allRequests.filter(r => r.type === type).length) || 0
}
Example #6
Source File: DataCloud.js From lens-extension-cc with MIT License | 6 votes |
_deserializeCollection = function (
resourceType,
body,
namespace,
create
) {
if (!body || !Array.isArray(body.items)) {
logger.error(
'DataCloud._deserializeCollection()',
`Failed to parse "${resourceType}" collection payload: Unexpected data format`
);
return [];
}
return body.items
.map((data, idx) => {
try {
return create({ data, namespace });
} catch (err) {
logger.warn(
'DataCloud._deserializeCollection()',
`Ignoring ${logValue(
resourceType
)} resource index=${idx}: Could not be deserialized; name=${logValue(
data?.metadata?.name
)}; namespace=${logValue(namespace.name)}; error="${getErrorMessage(
err
)}"`,
err
);
return undefined;
}
})
.filter((obj) => !!obj);
}
Example #7
Source File: enhancers.js From plant-3d-explorer with GNU Affero General Public License v3.0 | 6 votes |
export function ifNotNil (fn) {
return function (...args) {
if (filter(args, [null, undefined, false]).length) {
return fn(...args)
} else {
return args.length === 1
? first(args)
: args
}
}
}
Example #8
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 模板明细行-批量删除
*/
@Bind()
handleDeleteTemplateLine() {
const {
dispatch,
templateManage: { line = {}, linePagination },
} = this.props;
const { content = [] } = line;
const { templateLineSelectedRowKeys } = this.state;
const newParameters = filter(
content,
item => templateLineSelectedRowKeys.indexOf(item.templateDtlId) >= 0
);
Modal.confirm({
title: intl.get('hzero.common.message.confirm.remove').d('确定删除选中数据?'),
onOk: () => {
dispatch({
type: 'templateManage/deleteTemplateLine',
payload: { newParameters },
}).then(res => {
if (res) {
notification.success();
this.fetchTemplateLine(linePagination);
this.setState({ templateLineSelectedRowKeys: [] });
}
});
},
});
}
Example #9
Source File: List.js From course-manager with MIT License | 6 votes |
function applySortFilter(array, comparator, query) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
if (query) {
return filter(array, (_user) => _user.name.toLowerCase().indexOf(query.toLowerCase()) !== -1);
}
return stabilizedThis.map((el) => el[0]);
}
Example #10
Source File: UserSearchResults.js From haven with MIT License | 6 votes |
render() {
const {
results, loading_user: loading, load,
} = this.props;
const finalResult = filter(results, o => !isEmpty(o));
if (loading) {
return this.renderLoadingState();
}
return finalResult.length > 0 ? (
<View style={styles.resultWrapper}>
<FlatList
keyExtractor={this.keyExtractor}
horizontal={false}
data={finalResult}
renderItem={this.renderItem}
onEndReached={load}
onEndReachedThreshold={0.8}
ListHeaderComponent={this.renderListHeader()}
ListFooterComponent={this.renderListFooter()}
/>
</View>
) : (
this.renderEmptyState()
);
}
Example #11
Source File: MetaColumnsTable.js From hzero-front with Apache License 2.0 | 6 votes |
@Bind()
moveRow(dragIndex, hoverIndex) {
const { tableDataSource } = this.state;
const dragRow = tableDataSource[dragIndex];
// 先删除拖动的那条数据,再在删除后的数组中的hoverIndex处插入拖动的那条数据
const newAllData = filter(tableDataSource, (item, index) => index !== dragIndex);
newAllData.splice(hoverIndex, 0, dragRow);
this.setState({ tableDataSource: newAllData });
for (let i = 0; i < newAllData.length; i++) {
newAllData[i].ordinal = i + 1;
}
this.updateDataSource(newAllData);
}
Example #12
Source File: addModerators.js From haven with MIT License | 6 votes |
getProfileList() {
const { storeModerators } = this.props;
const { options } = this.state;
const filteredOptions = filter(options, (val) => {
const idx = findIndex(storeModerators, o => o === val);
return idx === -1;
});
return filteredOptions || [];
}
Example #13
Source File: workflows.js From holo-schedule with MIT License | 6 votes |
filterByTitle = lives => filter(
lives,
live => {
// Ensure lives of Hololive China members at Bilibili are kept
// eslint-disable-next-line no-use-before-define
if (range(45, 51).includes(getMember(live)['id'])) {
return true
}
const { platform, title } = live
return platform !== 'bilibili' || /B.*限/i.test(title)
},
)
Example #14
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 模板-单选删除
*/
@Bind()
handleDeleteTemplate() {
const {
dispatch,
match,
reportDefinition: { template = [] },
} = this.props;
const { templateSelectedRowKeys } = this.state;
let reportTemplate = {};
const parameters = filter(
template,
(item) => templateSelectedRowKeys.indexOf(item.reportTemplateId) >= 0
);
parameters.forEach((item) => {
reportTemplate = { ...reportTemplate, ...item };
});
Modal.confirm({
title: intl.get('hzero.common.message.confirm.remove').d('确定删除选中数据?'),
onOk: () => {
dispatch({
type: 'reportDefinition/deleteTemplate',
payload: reportTemplate,
}).then((res) => {
if (res) {
dispatch({
type: 'reportDefinition/fetchTemplateDetail',
payload: { reportId: match.params.id },
});
this.setState({ templateSelectedRowKeys: [] });
}
});
},
});
}
Example #15
Source File: User.js From Django-REST-Framework-React-BoilerPlate with MIT License | 6 votes |
function applySortFilter(array, comparator, query) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
if (query) {
return filter(array, (_user) => _user.name.toLowerCase().indexOf(query.toLowerCase()) !== -1);
}
return stabilizedThis.map((el) => el[0]);
}
Example #16
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* 模板-新增
* @param {object} values - 保存数据
*/
@Bind()
handleAddTemplate() {
const {
dispatch,
match,
reportDefinition: { templateList = [], header = {} },
} = this.props;
const { templateListSelectedRowKeys } = this.state;
const parameters = filter(
templateList,
(item) => templateListSelectedRowKeys.indexOf(item.templateId) >= 0
);
const newParams = parameters.map((item) => ({
templateId: item.templateId,
tenantId: item.tenantId,
reportId: header.reportId,
}));
dispatch({
type: 'reportDefinition/createTemplate',
payload: { newParams },
}).then((res) => {
if (res) {
this.setState({ templateDrawerVisible: false });
dispatch({
type: 'reportDefinition/fetchTemplateDetail',
payload: { reportId: match.params.id },
});
}
});
}
Example #17
Source File: RequestsContainer.js From covidsos with MIT License | 5 votes |
getDistanceWiseSlides(requestsToDisplay, isAuthorisedUser, currentUserID) {
const lessThan1Km = requestsToDisplay.filter(r => r.hd <= 1000);
const lessThan10Km = requestsToDisplay.filter(r => r.hd > 1000 && r.hd <= 10000);
const moreThan10Km = requestsToDisplay.filter(r => r.hd > 10000);
let toReturn = [];
toReturn.push(
<Row className="mx-0 pb-4" key="moreThan10Km">
<Col xs={12} className="text-uppercase pt-4 text-center h5">
Far requests ({moreThan10Km.length})
</Col>
{this.getRequestSlides(moreThan10Km, isAuthorisedUser, currentUserID)}
</Row>);
if (lessThan1Km.length === 0 && lessThan10Km.length === 0) {
toReturn.push(
<Row className="mx-0 border-bottom pb-4" key="lessThan10Km">
<Col xs={12} className="text-uppercase pt-4 text-center h5">
There are no pending requests nearby<span role="img" aria-label="happy">???</span>.
Please search another locality/city where you have good friends share with them on <i
className="fab fa-whatsapp"/>
</Col>
</Row>
);
toReturn.reverse();
return toReturn;
} else if (lessThan10Km.length !== 0) {
toReturn.push(<Row className="mx-0 border-bottom pb-4" key="lessThan10Km">
<Col xs={12} className="text-uppercase pt-4 text-center h5">
Pending requests slightly further away ({lessThan10Km.length})
</Col>
{this.getRequestSlides(lessThan10Km, isAuthorisedUser, currentUserID)}
</Row>);
}
if (lessThan1Km.length === 0) {
toReturn.push(
<Row className="mx-0 border-bottom pb-4" key="lessThan1Km">
<Col xs={12} className="text-uppercase pt-4 text-center h5">
There are pending requests slightly away from your location <span role="img"
aria-label="sad">???</span>.
Please share with someone who can help <i className="fab fa-whatsapp"/>
</Col>
</Row>);
} else {
toReturn.push(<Row className="mx-0 border-bottom pb-4" key="lessThan1Km">
<Col xs={12} className="text-uppercase pt-4 text-center h5">
Pending requests near you ({lessThan1Km.length})
</Col>
{this.getRequestSlides(lessThan1Km, isAuthorisedUser, currentUserID)}
</Row>);
}
toReturn.reverse();
return toReturn;
}
Example #18
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
/**
* 参数列表- 行删除
* @param {obejct} record - 规则对象
*/
@Bind()
handleDeleteContent(record) {
const {
dispatch,
sendConfig: { header = {}, copyDetail },
history: {
location: { payload = {} },
},
} = this.props;
const { isCopy } = payload;
const { serverList = [], ...otherValues } = header;
const { serverList: copyServerList = [], ...otherCopyValues } = copyDetail;
const recordTempServerLineId = record.tempServerLineId;
if (!isCopy && !recordTempServerLineId.toString().startsWith('create-')) {
dispatch({
type: 'sendConfig/deleteLine',
payload: { ...record },
}).then((res) => {
if (res) {
notification.success();
this.handleSearch();
}
});
} else if (isCopy) {
// 删除的操作
const newParameters = filter(
copyServerList,
(item) => recordTempServerLineId !== item.tempServerLineId
);
dispatch({
type: 'sendConfig/updateState',
payload: {
copyDetail: { serverList: [...newParameters], ...otherCopyValues },
},
});
} else {
// 删除的操作
const newParameters = filter(
serverList,
(item) => recordTempServerLineId !== item.tempServerLineId
);
dispatch({
type: 'sendConfig/updateState',
payload: {
header: { serverList: [...newParameters], ...otherValues },
},
});
}
}
Example #19
Source File: index.jsx From mui-phone-input-ssr with MIT License | 5 votes |
constructor(props) {
super(props);
let filteredCountries = countryData.allCountries;
if (props.disableAreaCodes) filteredCountries = this.deleteAreaCodes(filteredCountries);
if (props.regions) filteredCountries = this.filterRegions(props.regions, filteredCountries);
const onlyCountries = this.excludeCountries(
this.getOnlyCountries(props.onlyCountries, filteredCountries), props.excludeCountries,
);
const preferredCountries = filter(filteredCountries, (country) => some(props.preferredCountries, (preferredCountry) => preferredCountry === country.iso2));
const inputNumber = props.value || '';
let countryGuess;
if (inputNumber.length > 1) {
// Country detect by value field
countryGuess = this.guessSelectedCountry(inputNumber.replace(/\D/g, '').substring(0, 6), onlyCountries, props.defaultCountry) || 0;
} else if (props.defaultCountry) {
// Default country
countryGuess = find(onlyCountries, { iso2: props.defaultCountry }) || 0;
} else {
// Empty params
countryGuess = 0;
}
const countryGuessIndex = findIndex(this.allCountries, countryGuess);
const dialCode = (
inputNumber.length < 2
&& countryGuess
&& !startsWith(inputNumber.replace(/\D/g, ''), countryGuess.dialCode)
) ? countryGuess.dialCode : '';
const formattedNumber = (inputNumber === '' && countryGuess === 0) ? ''
: this.formatNumber(
(props.disableCountryCode ? '' : dialCode) + inputNumber.replace(/\D/g, ''),
countryGuess.name ? countryGuess.format : undefined,
);
this.state = {
formattedNumber,
placeholder: props.placeholder,
onlyCountries,
preferredCountries,
defaultCountry: props.defaultCountry,
selectedCountry: countryGuess,
highlightCountryIndex: countryGuessIndex,
queryString: '',
freezeSelection: false,
debouncedQueryStingSearcher: debounce(this.searchCountry, 100),
anchorEl: null,
};
}
Example #20
Source File: Listings.js From haven with MIT License | 5 votes |
render() {
const {
results, mode, status,
} = this.props;
const finalResult = filter(results, o => !isEmpty(o));
return (
<View style={styles.resultWrapper}>
{mode === 'card' && (
<FlatList
style={{
height:
(cardStyles.wrapper.height + cardStyles.columnWrapperStyle.paddingBottom) *
Math.ceil(finalResult.length / 2),
}}
numColumns={2}
columnWrapperStyle={cardStyles.columnWrapperStyle}
keyExtractor={this.keyExtractor}
horizontal={false}
data={
finalResult.length % 2 === 0 ? finalResult.reverse() : [...finalResult.reverse(), {}]
}
renderItem={this.renderCardItem}
onEndReached={this.onEndReached}
onEndReachedThreshold={0.8}
key={`${status}_card_view`}
/>
)}
{mode === 'list' && (
<FlatList
style={{ height: listItemHeight * finalResult.length }}
horizontal={false}
data={finalResult.reverse()}
keyExtractor={this.keyExtractor}
renderItem={this.renderListItem}
onEndReached={this.onEndReached}
onEndReachedThreshold={0.8}
key={`${status}_list_view`}
/>
)}
</View>
);
}
Example #21
Source File: SlashMenu.jsx From volto-slate with MIT License | 5 votes |
PersistentSlashMenu = ({ editor }) => {
const props = editor.getBlockProps();
const {
block,
blocksConfig,
data,
onMutateBlock,
properties,
selected,
allowedBlocks,
detached,
} = props;
const disableNewBlocks = data?.disableNewBlocks || detached;
const [slashMenuSelected, setSlashMenuSelected] = React.useState(0);
const useAllowedBlocks = !isEmpty(allowedBlocks);
const slashCommand = data.plaintext?.trim().match(/^\/([a-z]*)$/);
const availableBlocks = React.useMemo(
() =>
filter(blocksConfig, (item) =>
useAllowedBlocks
? allowedBlocks.includes(item.id)
: typeof item.restricted === 'function'
? !item.restricted({ properties, block: item })
: !item.restricted,
)
.filter(
// TODO: make it work with intl?
(block) => slashCommand && block.id.indexOf(slashCommand[1]) === 0,
)
.sort((a, b) => (a.title < b.title ? -1 : 1)),
[allowedBlocks, blocksConfig, properties, slashCommand, useAllowedBlocks],
);
const slashMenuSize = availableBlocks.length;
const show = selected && slashCommand && !disableNewBlocks;
const isMounted = useIsMounted();
React.useEffect(() => {
if (isMounted && show && slashMenuSelected > slashMenuSize - 1) {
setSlashMenuSelected(slashMenuSize - 1);
}
}, [show, slashMenuSelected, isMounted, slashMenuSize]);
editor.showSlashMenu = show;
editor.slashEnter = () =>
slashMenuSize > 0 &&
onMutateBlock(
block,
{
'@type': availableBlocks[slashMenuSelected].id,
},
emptySlateBlock(),
);
editor.slashArrowUp = () =>
setSlashMenuSelected(
slashMenuSelected === 0 ? slashMenuSize - 1 : slashMenuSelected - 1,
);
editor.slashArrowDown = () =>
setSlashMenuSelected(
slashMenuSelected >= slashMenuSize - 1 ? 0 : slashMenuSelected + 1,
);
return show ? (
<SlashMenu
currentBlock={block}
onMutateBlock={onMutateBlock}
availableBlocks={availableBlocks}
selected={slashMenuSelected}
/>
) : (
''
);
}
Example #22
Source File: DataCloud.js From lens-extension-cc with MIT License | 5 votes |
_fetchNamespaces = async function (cloud, preview = false) {
// NOTE: we always fetch ALL known namespaces because when we display metadata
// about this DataCloud, we always need to show the actual total, not just
// what we're syncing
const {
resources: { [apiResourceTypes.NAMESPACE]: namespaces },
watches,
tokensRefreshed,
errors,
} = await _fetchCollection({
resourceType: apiResourceTypes.NAMESPACE,
cloud,
create: ({ data }) => {
const mvvData = rtv.verify(data, namespaceTs).mvv;
return new Namespace({ data: mvvData, cloud, preview });
},
});
const userRoles = extractJwtPayload(cloud.token).iam_roles || [];
const hasReadPermissions = (name) =>
userRoles.includes(`m:kaas:${name}@reader`) ||
userRoles.includes(`m:kaas:${name}@writer`) ||
userRoles.includes(`m:kaas:${name}@user`) ||
userRoles.includes(`m:kaas:${name}@operator`) ||
userRoles.includes('m:kaas@global-admin');
const ignoredNamespaces = cloud?.config?.ignoredNamespaces || [];
return {
namespaces: filter(
namespaces,
(ns) =>
ns.phase !== apiNamespacePhases.TERMINATING &&
!ignoredNamespaces.includes(ns.name) &&
hasReadPermissions(ns.name)
),
watches,
tokensRefreshed,
error: errors?.[apiResourceTypes.NAMESPACE],
};
}
Example #23
Source File: ComposeTableEditModal.js From hzero-front with Apache License 2.0 | 5 votes |
getDataSource() {
const { dataSource } = this.state;
return map(filter(dataSource, r => r.isCreate || r.isUpdate), r =>
omit(r, ['isCreate', 'isUpdate'])
);
}
Example #24
Source File: 142-test.js From cybsec with GNU Affero General Public License v3.0 | 4 votes |
describe('github issue #142: Add schema definition in `graphql-tools` way', () => {
// example data
const authors = [{
id: 1,
firstName: 'Tom',
lastName: 'Coleman'
}, {
id: 2,
firstName: 'Sashko',
lastName: 'Stubailo'
}, {
id: 3,
firstName: 'Mikhail',
lastName: 'Novikov'
}];
const _posts = [{
id: 1,
authorId: 1,
title: 'Introduction to GraphQL',
votes: 2
}, {
id: 2,
authorId: 2,
title: 'Welcome to Meteor',
votes: 3
}, {
id: 3,
authorId: 2,
title: 'Advanced GraphQL',
votes: 1
}, {
id: 4,
authorId: 3,
title: 'Launchpad is Cool',
votes: 7
}];
const typeDefs = `
type Author {
id: Int!
firstName: String
lastName: String
"""
the list of Posts by this author
"""
posts: [Post]
}
type Post {
id: Int!
title: String
author: Author
votes: Int
}
# the schema allows the following query:
type Query {
posts: [Post]
author(id: Int!): Author
}
# this schema allows the following mutation:
type Mutation {
upvotePost (
postId: Int!
): Post
}
`;
const resolvers = {
Query: {
posts: () => _posts,
author: (_, {
id
}) => find(authors, {
id
})
},
Mutation: {
upvotePost: (_, {
postId
}) => {
const post = find(_posts, {
id: postId
});
if (!post) {
throw new Error(`Couldn't find post with id ${postId}`);
}
post.votes += 1;
return post;
}
},
Author: {
posts: author => filter(_posts, {
authorId: author.id
})
},
Post: {
author: post => find(authors, {
id: post.authorId
})
}
};
schemaComposer.addTypeDefs(typeDefs);
schemaComposer.addResolveMethods(resolvers);
const schema = schemaComposer.buildSchema();
it('test graphql query',
/*#__PURE__*/
_asyncToGenerator(function* () {
expect((yield graphql.graphql(schema, `
query {
author(id: 2) {
id
firstName
}
posts {
title
author {
firstName
}
}
}
`))).toEqual({
data: {
author: {
firstName: 'Sashko',
id: 2
},
posts: [{
author: {
firstName: 'Tom'
},
title: 'Introduction to GraphQL'
}, {
author: {
firstName: 'Sashko'
},
title: 'Welcome to Meteor'
}, {
author: {
firstName: 'Sashko'
},
title: 'Advanced GraphQL'
}, {
author: {
firstName: 'Mikhail'
},
title: 'Launchpad is Cool'
}]
}
});
}));
});
Example #25
Source File: DataCloud.js From lens-extension-cc with MIT License | 4 votes |
/**
* Fetches new data from the `cloud`. Add event listeners to get notified when
* the fetch completes.
*/
async fetchData() {
if (this.fetching) {
return;
}
// make sure we have a Cloud and it's connected
if (!this.cloud?.connected) {
// if no config (eg. when we restore cloud from disk) try to load it
if (!this.cloud.config) {
await this.cloud.loadConfig();
// if loadConfig error we get it as connectError
if (this.cloud.connectError) {
this.error = getErrorMessage(this.cloud.connectError);
}
}
}
// if we're still not connected, stop the fetch before it starts
if (!this.cloud.connected) {
logger.log(
'DataCloud.fetchData()',
`Cannot fetch data: Cloud is ${
this.cloud ? this.cloud.status : 'unknown'
}; dataCloud=${this}`
);
return;
}
this.fetching = true;
logger.log(
'DataCloud.fetchData()',
`Fetching full data for dataCloud=${this}`
);
this.stopWatching();
// NOTE: we always fetch ALL namespaces (which should be quite cheap to do)
// since we need to discover new ones, and know when existing ones are removed
const nsResults = await _fetchNamespaces(this.cloud, this.preview);
// NOTE: if we fail to get namespaces for whatever reason, we MUST abort the fetch;
// if we don't, `nsResults.namespaces` will be empty and we'll assume all namespaces
// have been deleted, resulting in all the user's sync settings being lost and all
// items removed from the Catalog...
if (nsResults.error) {
this.error = nsResults.error.message;
logger.error(
'DataCloud.fetchData()',
`Failed to get namespaces: Aborting data fetch, will try again soon; dataCloud=${this}`
);
this.fetching = false;
this.startInterval(FETCH_INTERVAL_QUICK); // retry sooner rather than later
return;
}
const allNamespaces = nsResults.namespaces.concat();
// if we're not generating a preview, only fetch full data for synced namespaces
// (which may contain some newly-discovered ones after the update we just did
// using `allNamespaces`)
const fetchedNamespaces = this.preview
? allNamespaces
: allNamespaces.filter((ns) =>
this.cloud.syncedProjects.includes(ns.name)
);
let errorsOccurred = false;
if (!this.preview) {
const credResults = await _fetchCredentials(
this.cloud,
fetchedNamespaces
);
const keyResults = await _fetchSshKeys(this.cloud, fetchedNamespaces);
// map all the resources fetched so far into their respective Namespaces
fetchedNamespaces.forEach((namespace) => {
namespace.sshKeys = keyResults.sshKeys[namespace.name] || [];
namespace.credentials = credResults.credentials[namespace.name] || [];
});
errorsOccurred =
errorsOccurred ||
credResults.errorsOccurred ||
keyResults.errorsOccurred;
const proxyResults = await _fetchProxies(this.cloud, fetchedNamespaces);
const licenseResults = await _fetchLicenses(
this.cloud,
fetchedNamespaces
);
// map fetched proxies and licenses into their respective Namespaces
fetchedNamespaces.forEach((namespace) => {
namespace.proxies = proxyResults.proxies[namespace.name] || [];
namespace.licenses = licenseResults.licenses[namespace.name] || [];
});
errorsOccurred =
errorsOccurred ||
proxyResults.errorsOccurred ||
licenseResults.errorsOccurred;
// NOTE: fetch machines only AFTER licenses have been fetched and added
// into the Namespaces because the Machine resource expects to find Licenses
const machineResults = await _fetchMachines(
this.cloud,
fetchedNamespaces
);
// map fetched machines into their respective Namespaces
fetchedNamespaces.forEach((namespace) => {
namespace.machines = machineResults.machines[namespace.name] || [];
});
errorsOccurred = errorsOccurred || machineResults.errorsOccurred;
// NOTE: fetch clusters only AFTER everything else has been fetched and added
// into the Namespaces because the Cluster resource expects to find all the
// other resources
const clusterResults = await _fetchClusters(
this.cloud,
fetchedNamespaces
);
// map fetched clusters into their respective Namespaces
fetchedNamespaces.forEach((namespace) => {
namespace.clusters = clusterResults.clusters[namespace.name] || [];
});
errorsOccurred = errorsOccurred || clusterResults.errorsOccurred;
if (errorsOccurred) {
this.error = strings.dataCloud.error.fetchErrorsOccurred();
logger.error(
'DataCloud.fetchData()',
`At least one error occurred while fetching cloud resources other than namespaces: Ignoring all data, will try again next poll; dataCloud=${this}`
);
this.fetching = false;
this.startInterval(FETCH_INTERVAL_QUICK); // retry sooner rather than later
return;
}
// TODO[PRODX-22469]: Disabling watches until a solution can be found to the behavior
// where a watch request's response comes back almost immediately as status 200, but
// then attempting to extract the body with `response.text()` in netUtils.js#tryExtractBody()
// NEVER resolves. It just hangs.
// I thought this might be similar to this issue: https://github.com/node-fetch/node-fetch/issues/665
// And solution (for node-fetch 2.x): https://github.com/node-fetch/node-fetch#custom-highwatermark
// But, alas, that didn't help at all. No clue what's going on. Works great in Postman,
// so clearly, the issue is with how we're handling these types of long-poll requests
// in netUtil.js#request(), but not sure what to do.
//
// this.startWatching([
// ...nsResults.watches,
// ...credResults.watches,
// ...keyResults.watches,
// ...proxyResults.watches,
// ...licenseResults.watches,
// ...machineResults.watches,
// ...clusterResults.watches,
// ]);
//
// if (this.watching) {
// this.resetInterval(false);
// } else {
// logger.info('DataCloud.fetchData()', 'Unable to start watching for changes: Falling back to polling');
// this.startInterval();
// }
this.startInterval();
} else {
logger.log(
'DataCloud.fetchData()',
`Preview only: Skipping all but namespace fetch; dataCloud=${logValue(
this.cloudUrl
)}`
);
this.startInterval();
}
// update the synced vs ignored namespace lists of the Cloud
// NOTE: we do this AFTER fetching ALL data (if not preview) so that when
// we update the Cloud's namespace metadata, we have the summary counts
// for what we fetched from the __synced__ namespaces among all the namespaces
this.cloud.updateNamespaces(allNamespaces);
this.error = null;
this.namespaces = allNamespaces;
if (!this.loaded) {
// successfully loaded at least once
this.loaded = true;
logger.log(
'DataCloud.fetchData()',
`Initial data load successful; dataCloud=${this}`
);
}
this.fetching = false;
logger.log(
'DataCloud.fetchData()',
`Full data fetch complete; dataCloud=${this}`
);
}
Example #26
Source File: EditModal.js From hzero-front with Apache License 2.0 | 4 votes |
@Bind()
getColumns() {
const { match } = this.props;
this.columns = [
{
title: intl.get('hpfm.profile.model.profileValue.levelCode').d('层级'),
dataIndex: 'levelCode',
width: 100,
render: (item, record) => {
// 当时平台级时,levelCode,levelValue 固定是 GLOBAL,且不能修改
const { levelCode = [] } = this.props;
const { $form } = record;
return (
<FormItem>
{$form.getFieldDecorator('levelCode', {
initialValue: item,
rules: [
{
required: true,
message: intl.get('hzero.common.validation.notNull', {
name: intl.get('hpfm.profile.model.profileValue.levelCode').d('层级'),
}),
},
],
})(
<ValueList
options={levelCode}
onChange={value => this.handleRecordLevelCodeChange(value, record)}
className={styles['full-width']}
disabled={this.getEditDisabled(false)}
/>
)}
</FormItem>
);
},
},
{
title: intl.get('hpfm.profile.model.profileValue.levelValue').d('层级值'),
dataIndex: 'levelValue',
width: 200,
render: (item, record) => {
const { $form } = record;
const tenantId = this.getCurrentTenantId();
const currentLevelCode = $form.getFieldValue('levelCode');
// 当时平台级时,levelCode,levelValue 固定是 GLOBAL,且不能修改
let $levelValueInputComponent;
switch (currentLevelCode) {
case 'USER':
$levelValueInputComponent = (
<Lov
textValue={record.levelValueDescription}
code="HIAM.TENANT.USER"
onChange={() => this.handleRecordChange(record)}
queryParams={{ organizationId: tenantId }}
className={styles['full-width']}
disabled={this.getEditDisabled(tenantId === undefined)}
/>
);
break;
case 'ROLE':
$levelValueInputComponent = (
<Lov
textValue={record.levelValueDescription}
code="HIAM.TENANT.ROLE"
onChange={() => this.handleRecordChange(record)}
queryParams={{ organizationId: tenantId }}
className={styles['full-width']}
disabled={this.getEditDisabled(tenantId === undefined)}
/>
);
break;
case 'GLOBAL':
// 如果层级是 GLOBAL 那么层级值 只能是 GLOBAL
$levelValueInputComponent = (
<Select className={styles['full-width']} disabled>
<Select.Option value="GLOBAL" key="GLOBAL">
{intl.get('hpfm.profile.model.profileValue.levelValue.GLOBAL').d('全局')}
</Select.Option>
</Select>
);
break;
default:
// 没有选择 层级 是不能选择层级值的.
$levelValueInputComponent = <Input disabled />;
break;
}
return (
<FormItem>
{$form.getFieldDecorator('levelValue', {
initialValue: item,
rules: [
{
required: true,
message: intl.get('hzero.common.validation.notNull', {
name: intl.get('hpfm.profile.model.profileValue.levelValue').d('层级值'),
}),
},
],
})($levelValueInputComponent)}
</FormItem>
);
},
},
{
title: intl.get('hpfm.profile.model.profileValue.profileValue').d('配置值'),
width: 200,
dataIndex: 'value',
render: (item, record) => {
const { $form } = record;
return (
<FormItem>
{$form.getFieldDecorator('value', {
initialValue: item,
rules: [
{
required: true,
message: intl.get('hzero.common.validation.notNull', {
name: intl.get('hpfm.profile.model.profileValue.profileValue').d('配置值'),
}),
},
{
max: 480,
message: intl.get('hzero.common.validation.max', {
max: 480,
}),
},
],
})(
<Input
onChange={() => this.handleRecordChange(record)}
disabled={this.getEditDisabled(false)}
/>
)}
</FormItem>
);
},
},
!this.getEditDisabled(false) && {
title: intl.get('hzero.common.button.action').d('操作'),
width: 120,
render: (_, record) => {
const actions = [];
actions.push({
key: 'remove',
ele: (
<Popconfirm
placement="topRight"
title={intl.get('hzero.common.message.confirm.delete').d('是否删除此条记录?')}
onConfirm={() => {
this.handleRecordRemove(record);
}}
>
<ButtonPermission
type="text"
permissionList={[
{
code: `${match.path}.button.valueDelete`,
type: 'button',
meaning: '配置维护(租户)配置值-删除',
},
]}
>
{intl.get('hzero.common.button.delete').d('删除')}
</ButtonPermission>
</Popconfirm>
),
});
return operatorRender(actions);
},
},
].filter(Boolean);
return this.columns;
}
Example #27
Source File: MessagesChain.js From CyberStateRP with MIT License | 4 votes |
MessagesChain = props => {
const { phone } = useContext(PhoneContext)
const { myNumber, messagingWith } = phone
const myNum = parseInt(myNumber, 10)
const hisNum = parseInt(messagingWith, 10)
const contact = phone.fetchContact(hisNum)
const handleInputChange = e => {
const { value } = e.target
setMessageText(value)
}
const [messageText, setMessageText] = useState('')
const loadMessages = () => {
const msgs = phone.messages
const currentMessages = filter(msgs, msg => {
if (msg.sender_num === hisNum || msg.creator_num === hisNum) return true
return false
})
const messagesToRender = []
for (let i = 0; i < currentMessages.length; i++) {
const msg = currentMessages[i]
if (msg.sender_num === myNum) {
messagesToRender.push(
<div className="messages-group" key={msg.id}>
<div className="message">{msg.text}</div>
</div>
)
} else if (msg.creator_num === myNum) {
messagesToRender.push(
<div className="messages-group my" key={msg.id}>
<div className="message">{msg.text}</div>
</div>
)
}
}
//console.log(messagesToRender)
return messagesToRender
}
return (
<div className="app messages">
<div className="container">
<div className="control-bar">
<div
className="control back"
role="presentation"
onClick={() => {
phone.setActiveTab(2, 0)
phone.setInteracting(-1, [])
}}
>
<div className="icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 17">
<path d="M9.619,2.1A1.214,1.214,0,0,0,9.66.378,1.229,1.229,0,0,0,7.929.336Q.371,7.61.351,7.631a1.254,1.254,0,0,0,.04,1.78l7.537,7.251a1.229,1.229,0,0,0,1.732-.039A1.214,1.214,0,0,0,9.622,14.9L3.373,8.786a.4.4,0,0,1,0-.57Z" />
</svg>
</div>
</div>
<div className="title">{contact}</div>
<div className="control inactive" />
</div>
<div className="workspace chat">
{loadMessages()}
</div>
</div>
<div className="app-input">
<div className="input-group">
<input
type="text"
placeholder="SMS"
onChange={handleInputChange}
value={messageText}
/>
<button
className="send"
type="submit"
onClick={() => {
phone.emitSendMessage(messagingWith, messageText)
}}
>
<div className="icon">
<img src={ArrowImg} alt="" />
</div>
</button>
</div>
</div>
</div>
)
}
Example #28
Source File: dataMapping.js From haven with MIT License | 4 votes |
restructureListingInfo = (
listingInfo,
acceptedCurrencies,
moderators = [],
isCreating = true,
) => {
const slug = isCreating ? uuidv4() : listingInfo.slug;
const { type = {}, currency, shippingOptions, termsAndConditions, refundPolicy } = listingInfo || {};
const contractType = (type.value || type).toUpperCase();
const metadata = {
contractType,
format: 'FIXED_PRICE',
expiry: '2037-12-31T05:00:00.000Z',
escrowTimeoutHours: 1080,
acceptedCurrencies,
};
const options = listingInfo.options.map((val) => {
const { name, description, variants } = val;
const parsedVariants = variants.map(val => ({ name: val }));
return {
name,
description,
variants: parsedVariants,
};
});
const images = filter(listingInfo.images, o => !isEmpty(o)).map(val => ({
filename: val.filename,
...val.hashes,
}));
const item = {
priceCurrency: getBigCurrencyInfo(currency, true),
title: listingInfo.title,
description: listingInfo.description,
bigPrice: getPriceInMinimumUnit(listingInfo.price, currency).toString(),
tags: listingInfo.tags,
images,
categories: listingInfo.categories,
options,
condition: hasIn(listingInfo.condition, 'label')
? listingInfo.condition.label
: listingInfo.condition,
skus: listingInfo.inventory.map(({ quantity, surcharge, ...val }) => ({
...val,
bigSurcharge: getPriceInMinimumUnit(surcharge, currency),
bigQuantity: quantity.toString(),
})),
nsfw: listingInfo.nsfw,
};
const reShippingOptions = shippingOptions.map((val) => {
const {
name, type, regions, services,
} = val;
const newRegions = regions.map((region) => {
if (hasIn(region, 'value')) {
if (region.value === 'any') {
return 'ALL';
}
return region.value.toUpperCase();
}
return region.toUpperCase();
});
return {
name,
type,
regions: newRegions,
services: services.map((val) => {
const { price, additionalItemPrice, ...restVal } = val;
return {
...restVal,
bigPrice: getPriceInMinimumUnit(price, currency).toString(),
bigAdditionalItemPrice: getPriceInMinimumUnit(additionalItemPrice, currency).toString(),
};
}),
};
});
const taxes = [];
const { coupons = [] } = listingInfo;
return {
slug: isCreating ? '' : slug,
metadata,
item,
shippingOptions: contractType === 'PHYSICAL_GOOD' ? reShippingOptions : undefined,
termsAndConditions,
refundPolicy,
taxes,
coupons: coupons.map(bundleCoupon),
moderators,
};
}
Example #29
Source File: index.js From hzero-front with Apache License 2.0 | 4 votes |
// 生成报表
@Bind()
buildReport(pageParams = {}) {
const { reportDataId } = this.state;
const {
form,
dispatch,
dateFormat,
dateTimeFormat,
reportQuery: { detail = {} },
} = this.props;
const { paramsData = {} } = detail[reportDataId] || {};
const { reportUuid, formElements, reportTypeCode } = paramsData;
this.form.validateFields((err1) => {
if (!err1) {
const fieldValues = isUndefined(this.form)
? {}
: filterNullValueObject(this.form.getFieldsValue());
form.validateFields((err, values) => {
const { fCodeTenant, ...othersData } = values;
const valueData = { ...othersData, 'f-templateCode': fCodeTenant };
const newValues = filter(valueData, (item) => !isUndefined(item));
let strParam = '';
map(fieldValues, (value, key) => {
if (isArray(value) && value.length > 0) {
const separator = `&${key}=`;
if (strParam) {
strParam = `${separator}${join(value, separator)}&${strParam}`;
} else {
strParam = `${separator}${join(value, separator)}`;
}
if (isEmpty(newValues)) {
strParam = strParam.substring(1);
}
// eslint-disable-next-line no-param-reassign
delete fieldValues[key];
} else if (isArray(value) && value.length === 0) {
// eslint-disable-next-line no-param-reassign
delete fieldValues[key];
}
});
const formatFieldValues = { ...fieldValues };
for (const key of Object.keys(fieldValues)) {
if (isObject(fieldValues[key]) && moment(fieldValues[key]).isValid()) {
// TODO: 处理日期时间的格式化
formElements.forEach((n) => {
if (n.name === key) {
if (n.type === 'DatePicker') {
formatFieldValues[key] = moment(fieldValues[key]).format(dateFormat);
} else if (n.type === 'DatetimePicker') {
formatFieldValues[key] = moment(fieldValues[key]).format(dateTimeFormat);
}
}
});
}
}
if (!err) {
if (reportTypeCode !== 'C') {
dispatch({
type: 'reportQuery/buildReport',
payload: {
// type: reportTypeCode,
strParam,
reportUuid,
...formatFieldValues,
...values,
...pageParams,
},
}).then((res) => {
if (res) {
this.setState({ reportData: res }, () => {
if (reportTypeCode === 'ST') {
this.handleScrollDom();
}
});
}
});
} else if (reportTypeCode === 'C') {
const params = { strParam, ...formatFieldValues, ...values, ...pageParams };
this.setState({
EChartsVisible: true,
uuidKey: uuid(),
chartParams: params,
});
}
}
});
}
});
}