rxjs#zip TypeScript Examples
The following examples show how to use
rxjs#zip.
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: bridge.service.ts From rubic-app with GNU General Public License v3.0 | 6 votes |
private setTokens(): void {
const tokensObservables: Observable<BridgeTokenPairsByBlockchains>[] = [];
BLOCKCHAIN_NAMES.forEach(fromBlockchain => {
BLOCKCHAIN_NAMES.forEach(toBlockchain => {
const provider: BlockchainsBridgeProvider =
this.blockchainsProviders[fromBlockchain]?.[toBlockchain];
if (provider) {
tokensObservables.push(
provider.tokenPairs$.pipe(
map(bridgeTokens => ({
fromBlockchain,
toBlockchain,
tokenPairs: bridgeTokens
}))
)
);
}
});
});
zip(...tokensObservables)
.pipe(first())
.subscribe(tokens => {
this._tokens$.next(tokens);
});
}
Example #2
Source File: index.ts From dbm with Apache License 2.0 | 6 votes |
stylesheets$ = resolve("**/[!_]*.scss", { cwd: "src" })
.pipe(
concatMap(file => zip(
of(ext(file, ".css")),
transformStyle({
from: `src/${file}`,
to: ext(`${base}/${file}`, ".css")
}))
)
)
Example #3
Source File: index.ts From dbm with Apache License 2.0 | 6 votes |
javascripts$ = resolve("**/{bundle,search}.ts", { cwd: "src" })
.pipe(
concatMap(file => zip(
of(ext(file, ".js")),
transformScript({
from: `src/${file}`,
to: ext(`${base}/${file}`, ".js")
}))
)
)
Example #4
Source File: index.ts From dbm with Apache License 2.0 | 6 votes |
index$ = zip(icons$, emojis$)
.pipe(
map(([icons, emojis]) => {
const cdn = "https://raw.githubusercontent.com"
return {
icons: {
base: `${cdn}/squidfunk/mkdocs-material/master/material/.icons/`,
data: Object.fromEntries(icons)
},
emojis: {
base: `${cdn}/twitter/twemoji/master/assets/svg/`,
data: Object.fromEntries(emojis)
}
} as IconSearchIndex
}),
switchMap(data => write(
`${base}/overrides/assets/javascripts/iconsearch_index.json`,
JSON.stringify(data)
))
)
Example #5
Source File: my-addons.component.ts From WowUp with GNU General Public License v3.0 | 6 votes |
public onRemoveAddons(listItems: AddonViewModel[]): void {
let message = "";
if (listItems.length > 3) {
message = this._translateService.instant("PAGES.MY_ADDONS.UNINSTALL_POPUP.CONFIRMATION_MORE_THAN_THREE", {
count: listItems.length,
});
} else {
message = this._translateService.instant("PAGES.MY_ADDONS.UNINSTALL_POPUP.CONFIRMATION_LESS_THAN_THREE", {
count: listItems.length,
});
listItems.forEach((listItem) => (message = `${message}\n\t• ${listItem.addon?.name ?? ""}`));
}
message +=
"\n\n" +
(this._translateService.instant("PAGES.MY_ADDONS.UNINSTALL_POPUP.CONFIRMATION_ACTION_EXPLANATION") as string);
const dialogRef = this._dialog.open(ConfirmDialogComponent, {
data: {
title: this._translateService.instant("PAGES.MY_ADDONS.UNINSTALL_POPUP.TITLE", { count: listItems.length }),
message: message,
},
});
dialogRef
.afterClosed()
.pipe(
first(),
switchMap((result) => {
if (!result) {
return of(undefined);
}
return zip(listItems.map((listItem) => from(this._addonService.removeAddon(listItem.addon))));
})
)
.subscribe();
}
Example #6
Source File: search.tsx From codedoc with MIT License | 5 votes |
export function GithubSearch(this: ComponentThis, options: SearchOptions, renderer: RendererLike<any, any>) {
const query = new Subject<string>();
const pick = new RegExp(options.pick);
const drop = new RegExp(options.drop);
const cache: {[q: string]: string[]} = {};
const results = query.pipe(
switchMap(q =>
(q in cache) ? of({ result: cache[q] }) : // --> respond from cache if query in cache
ajax.getJSON<HotGithubResponse>(
`https://api.github.com/search/code?q=${encodeURIComponent(q)}`
+ `+in:file` // --> search in files
+ `+path:${options.root}` // --> search in root directory
+ `+extension:md` // --> search in `.md` files
+ `+repo:${options.user}/${options.repo}` // --> search in given repo of given user
).pipe(catchError(() => of(undefined))) // --> no sweat in case of error
),
map(res =>
res ?
( isCached(res) ? res.result : // --> if cached result, no need to process
res.items
.map(item => item.path)
.filter(x => pick.test(x)) // --> check if it should be picked
.filter(x => !drop.test(x)) // --> check if it shouldn't be dropped
.map(x => x.substr(0, x.length - 3)) // --> remove the extension `.md`
.map(x => x.substr(options.root.length)) // --> remove the root path part
.map(x => x === '/index' ? '/' : x) // --> turn `/index` to `/`
): []
),
share(),
);
zip(query, results).pipe( // --> for pairs of query and result...
tap(([query, results]) => {
if (results.length > 0) // --> ...if the result is valid...
cache[query] = results; // --> ...cache it.
})
).subscribe();
return <ToCSearchBtn label={options.label} query={query} results={results}/>;
}
Example #7
Source File: stake-button-container.component.ts From rubic-app with GNU General Public License v3.0 | 5 votes |
public ngOnInit(): void {
this.amountFormControl.valueChanges
.pipe(
startWith(this.amountFormControl.value),
withLatestFrom(this.selectedTokenBalance$, this.limit$),
map(([amount, balance, limit]) => {
const adjustedAmount = new BigNumber(amount ? amount.split(',').join('') : NaN);
return [adjustedAmount, balance, limit];
}),
tap(([amount, balance, limit]) => {
this.checkAmountAndBalance(amount as BigNumber, balance as BigNumber, limit as Limits);
if (this.isUserWhitelisted) {
this.checkAmountAndBalanceWhitelist(
amount as BigNumber,
balance as BigNumber,
limit as Limits
);
}
}),
withLatestFrom(this.selectedToken$),
switchMap(([[amount, balance, limit], selectedToken]) => {
return zip(
selectedToken.blockchain !== BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN
? of(false)
: this.stakingService.needApprove(amount as BigNumber),
of(balance),
of(limit),
of(amount)
);
}),
tap(([needApprove, balance, limit, amount]) => {
this._needApprove$.next(needApprove);
this.checkAmountAndBalance(amount as BigNumber, balance as BigNumber, limit as Limits);
if (this.stakingService.isUserWhitelisted) {
this.checkAmountAndBalanceWhitelist(
amount as BigNumber,
balance as BigNumber,
limit as Limits
);
}
}),
takeUntil(this.destroy$)
)
.subscribe();
}
Example #8
Source File: clean-finished-groups.dialog.ts From RcloneNg with MIT License | 5 votes |
ngOnInit() {
const outer = this;
const trigger = new Subject();
const listGroup$ = new (class extends ListGroupFlow {
public prerequest$ = trigger.pipe(
withLatestFrom(outer.cmdService.listCmd$.verify(this.cmd)),
map(x => x[1])
);
})();
listGroup$.deploy();
const stats$ = new (class extends CoreStatsFlow {
public prerequest$ = trigger.pipe(
withLatestFrom(outer.cmdService.listCmd$.verify(this.cmd)),
map(x => x[1])
);
})();
stats$.deploy();
this.loading = true;
listGroup$.clearCache();
stats$.clearCache();
zip(listGroup$.getOutput(), stats$.getOutput()).subscribe(([list, stats]) => {
this.loading = false;
if (list[1].length !== 0 || stats[1].length !== 0) return;
const transferring = stats[0]['core-stats'].transferring;
this.finishedGroup = !transferring
? list[0].groups
: list[0].groups.filter(x => !transferring.some(y => x === y.group));
this.check = this.finishedGroup.map(() => true);
});
trigger.next();
this.deleteStates$ = new (class extends CoreStatsDeleteFlow {
public prerequest$: Observable<CombErr<CoreStatsDeleteFlowInNode>> = outer.deleteTrigger.pipe(
withLatestFrom(outer.cmdService.listCmd$.verify(this.cmd)),
switchMap(([groups, y]) => {
if (y[1].length !== 0) return of([{}, y[1]] as any);
return of(...groups.map(group => [{ ...y[0], group }, []]));
}),
// TODO: need a tasks queue
concatMap(x => of(x).pipe(delay(1000)))
);
})();
this.deleteStates$.deploy();
this.deleteStates$.getOutput().subscribe();
}
Example #9
Source File: oracle-explorer.service.ts From bitcoin-s-ts with MIT License | 5 votes |
getLocalOracleName(pubkey: string) {
console.debug('getLocalOracleName()', pubkey)
return zip(this.getOracleName(pubkey),
this.messageService.sendMessage(getMessageBody(MessageType.getoraclename)))
.pipe(tap(arr => {
const result = arr[0]
const result2 = arr[1]
let osOracleName: string = '' // oracleName according to oracleServer
if (result2 && result2.result) {
osOracleName = result2.result
console.warn('oracleServer OracleName:', osOracleName)
}
const lsOracleName = localStorage.getItem(ORACLE_NAME_KEY); // historical
if (result && result.result) { // OracleExplorer.getOracleName()
this.oracleName.next(result.result.oracleName)
this.serverOracleName.next(true)
if (result.result.oracleName && lsOracleName && lsOracleName !== result.result.oracleName) {
console.warn('lsOracleName:', lsOracleName)
console.error('local oracleName and oracle explorer oracleName do not match!')
// Force server oracleName
// localStorage.setItem(ORACLE_NAME_KEY, result.result.oracleName)
this.setOracleName(result.result.oracleName, true)
} else if (result.result.oracleName && osOracleName !== result.result.oracleName) {
console.error('local oracleServer oracleName and oracle explorer oracleName do not match!')
// Force server oracleName
this.setOracleName(result.result.oracleName, true)
}
} else if (osOracleName) {
this.oracleName.next(osOracleName)
this.serverOracleName.next(false)
} else if (lsOracleName) {
// Use localStorage oracleName if it's set, but hasn't been used on the Oracle Explorer yet
this.oracleName.next(lsOracleName)
this.setOracleName(lsOracleName, true)
this.serverOracleName.next(false)
} else {
console.warn('no oracleName found')
this.oracleName.next('')
this.serverOracleName.next(false)
}
}))
}
Example #10
Source File: notifications.page.ts From fyle-mobile-app with MIT License | 5 votes |
ngOnInit() {
this.delegationOptions = ['Notify me and my delegate', 'Notify my delegate', 'Notify me only'];
this.isAllSelected = {
emailEvents: false,
pushEvents: false,
};
this.orgUserSettings$ = this.orgUserSettingsService.get();
// creating form
this.notificationForm = this.formBuilder.group({
notifyOption: [],
pushEvents: new FormArray([]), // push notification event form control array
emailEvents: new FormArray([]), // email notification event form control array
});
let notifyOption;
this.getDelegateeSubscription().subscribe((option) => {
notifyOption = option;
this.notificationForm.controls.notifyOption.setValue(notifyOption);
});
this.isDelegateePresent$ = from(this.authService.getEou()).pipe(map((eou) => eou.ou.delegatee_id !== null));
this.orgSettings$ = this.offlineService.getOrgSettings();
this.notificationEvents$ = this.orgUserSettingsService.getNotificationEvents();
const mergedData$ = zip(this.notificationEvents$, this.orgUserSettings$, this.orgSettings$)
.pipe(
finalize(() => {
this.isAllEventsSubscribed();
this.updateNotificationEvents();
})
)
.subscribe((res) => {
this.notificationEvents = res[0];
this.orgUserSettings = res[1];
this.setEvents(this.notificationEvents, this.orgUserSettings);
});
/**
* on valueChange of any check box, checking for all box selected or not
* if selected will toggle all select box
*/
this.notificationForm.valueChanges.subscribe((change) => {
this.isAllSelected.emailEvents = change.emailEvents.every((selected) => selected === true);
this.isAllSelected.pushEvents = change.pushEvents.every((selected) => selected === true);
});
}
Example #11
Source File: index.ts From jetlinks-ui-antd with MIT License | 5 votes |
root$ = zip(auth$, systemInfo$)
.pipe(
map(([auth, systemInfo]) => ({ auth, systemInfo })),
shareReplay(1))
Example #12
Source File: index.tsx From jetlinks-ui-antd with MIT License | 4 votes |
TenantDevice: React.FC<Props> = (props) => { const initState: State = { searchParam: { pageSize: 10, sorts: { order: "descend", field: "createTime" } }, productList: [], deviceData: {}, }; const [searchParam, setSearchParam] = useState(initState.searchParam); const [deviceData, setDeviceData] = useState(initState.deviceData); const [spinning, setSpinning] = useState(true); const statusMap = new Map(); statusMap.set('online', <Tag color="#87d068">在线</Tag>); statusMap.set('offline', <Tag color="#f50">离线</Tag>); statusMap.set('notActive', <Tag color="#1890ff">未激活</Tag>); const handleSearch = (params?: any) => { setSearchParam(params); apis.deviceInstance.list(encodeQueryParam(params)) .then((response: any) => { if (response.status === 200) { setDeviceData(response.result); } setSpinning(false); }) .catch(() => { }) }; const columns: ColumnProps<DeviceInstance>[] = [ { title: 'ID', dataIndex: 'id', }, { title: '设备名称', dataIndex: 'name', }, { title: '产品名称', dataIndex: 'productName', }, { title: '状态', dataIndex: 'state', width: '90px', render: record => record ? statusMap.get(record.value) : '', filters: [ { text: '未激活', value: 'notActive', }, { text: '离线', value: 'offline', }, { text: '在线', value: 'online', }, ], filterMultiple: false, }, ]; useEffect(() => { handleSearch(searchParam); }, []); const onTableChange = ( pagination: PaginationConfig, filters: any, sorter: SorterResult<DeviceInstance>,) => { setSpinning(true); let { terms } = searchParam; if (filters.state) { if (terms) { terms.state = filters.state[0]; } else { terms = { state: filters.state[0], }; } } handleSearch({ pageIndex: Number(pagination.current) - 1, pageSize: pagination.pageSize, terms, sorts: sorter, }); }; const service = new Service(''); const [data, setData] = useState<any[]>([]); const user = JSON.parse(localStorage.getItem('user-detail') || '{}'); const tenantId = (user.tenants || []).filter((i: any) => i.mainTenant)[0]?.tenantId; const tenantAdmin = (user.tenants || []).filter((i: any) => i.mainTenant)[0]?.adminMember; const getProduct = (userId: string) => service.assets.productNopaging(encodeQueryParam({ terms: { id$assets: JSON.stringify({ tenantId: tenantId, assetType: 'product', memberId: userId, }), } })); const getDeviceState = (product: any, userId: string) => service.assets.instanceNopaging(encodeQueryParam({ terms: { productId: product.id, // id$assets: JSON.stringify({ // tenantId: tenantId, // assetType: 'device', // memberId: userId, // }), } })).pipe( groupBy((instance: any) => instance.state.value), mergeMap(group$ => group$.pipe( count(), map(count => { let v: any = {}; v[group$.key] = count; return v; }), )), map(state => ({ productName: product.name, online: state.online || 0, offline: state.offline || 0 })), defaultIfEmpty({ productName: product.name, 'online': 0, 'offline': 0 }), ); const getAlarmCount = (productId: string, userId: string) => service.alarm.count(encodeQueryParam({ terms: { // deviceId$assets: JSON.stringify({ // tenantId: tenantId, // assetType: 'device', // memberId: userId, // }), productId: productId, } })); useEffect(() => { // todo 查询租户 if (tenantId) { service.member.queryNoPaging({}) .pipe( flatMap((i: any) => getProduct(i.userId) .pipe( flatMap((product: any) => zip(getDeviceState(product, i.userId), getAlarmCount(product.id, i.userId))), map(tp2 => ({ userId: i.userId, name: i.name, key: `${i.userId}-${randomString(7)}`, ...tp2[0], alarmCount: tp2[1] })), defaultIfEmpty({ userId: i.userId, name: i.name, key: `${i.userId}` }) )), toArray(), map(list => list.sort((a, b) => a.userId - b.userId)), ).subscribe((result) => { setData(result); }); } }, [tenantId]); const test: string[] = []; const columns2 = [ { title: '成员', dataIndex: 'name', render: (text, row, index) => { test.push(text); return { children: text, props: { rowSpan: test.filter(i => i === text).length > 1 ? 0 : data.filter(i => i.name === text).length, }, }; }, }, { title: '产品', dataIndex: 'productName', // render: renderContent, }, { title: '设备在线', // colSpan: 2, dataIndex: 'online', render: (text: any) => text || 0, // render: (value, row, index) => { // const obj = { // children: value, // props: { // // rowSpan: 0, // }, // }; // if (index === 2) { // obj.props.rowSpan = 2; // } // // These two are merged into above cell // if (index === 3) { // obj.props.rowSpan = 0; // } // if (index === 4) { // obj.props.colSpan = 0; // } // return obj; // }, }, { title: '设备离线', // colSpan: 0, dataIndex: 'offline', render: (text: any) => text || 0, }, { dataIndex: 'alarmCount', title: '告警记录', render: (text: any) => text || 0, }, ]; return ( <Spin spinning={spinning}> <Card bordered={false}> <div className={styles.tableList}> <div className={styles.tableListForm}> {/* <Search search={(params: any) => { setSpinning(true); params.state = searchParam.terms?.state; handleSearch({ terms: params, pageSize: 10, sorts: searchParam.sorts }); }} /> */} </div> <div className={styles.StandardTable} style={{ marginTop: 10 }}> {/* <Table size='middle' columns={columns} dataSource={(deviceData || {}).data} rowKey="id" onChange={onTableChange} pagination={{ current: deviceData.pageIndex + 1, total: deviceData.total, pageSize: deviceData.pageSize, }} /> */} <Table size="small" pagination={false} columns={tenantAdmin ? columns2 : columns2.filter(i => i.dataIndex !== 'name')} dataSource={data} bordered /> </div> </div> </Card> </Spin> ); }
Example #13
Source File: index.tsx From jetlinks-ui-antd with MIT License | 4 votes |
Save: React.FC<Props> = props => {
const service = new Service('dueros/product');
const { onFieldValueChange$ } = FormEffectHooks
const [productInfo, setProductInfo] = useState<{ list: any[], type: any[] }>({ list: [], type: [] });
const testRef = useRef<any>({});
const productRef = useRef<any>({});
const [funcList, setFuncList] = useState<any>({});
const [loading, setLoading] = useState<boolean>(true);
const createLinkageUtils = () => {
const { setFieldState } = createFormActions()
const linkage = (key: string, defaultValue: any) => (path: string, value: any) =>
setFieldState(path, state => {
FormPath.setIn(state, key, value !== undefined ? value : defaultValue)
})
return {
hide: linkage('visible', false),
show: linkage('visible', true),
enum: linkage('props.enum', []),
loading: linkage('loading', true),
loaded: linkage('loading', false),
value: linkage('value', '')
}
}
const initValue = () => {
zip(service.queryProduct({}),
service.productTypes()).subscribe(data => {
const temp = {
list: data[0].map((item: any) => ({ value: item.id, label: item.name, ...item })),
type: data[1].map((item: any) => ({ value: item.id, label: item.name, ...item }))
};
setProductInfo(temp);
testRef.current = temp;
}, () => { }, () => setLoading(false));
}
useEffect(() => initValue(), [loading]);
const linkageEffect = async () => {
const linkage = createLinkageUtils();
onFieldValueChange$('applianceType').subscribe(fieldState => {
if (!fieldState.value) return;
const product = testRef.current.type.find((item: any) => item.id === fieldState.value);
const actions = (product.actions || []).map((item: any) => ({ label: item.name, value: item.id }));
linkage.show('actionMappings', true);
linkage.show('propertyMappings', true);
linkage.enum('actionMappings.*.action', actions);
linkage.enum('propertyMappings.*.source',
product.properties.map((item: any) => ({ label: item.name, value: item.id })));
linkage.enum('propertyMappings.*.target',
productRef.current.metadata.properties.map((item: any) => ({ label: item.name, value: item.id, ...item })));
});
onFieldValueChange$('actionMappings.*.command.messageType').subscribe(fieldState => {
const wpropertiesPath = FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.message._properties)`);
const rpropertiesPath = FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.message.properties)`);
const valuePath = FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.message._value)`);
const functionPath = FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.message.functionId)`);
const functionParamPath = FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.message.function)`);
switch (fieldState.value) {
case 'READ_PROPERTY':
linkage.enum(
rpropertiesPath,
productRef.current.metadata.properties.map((item: any) => ({ label: item.name, value: item.id, ...item })));
linkage.show(valuePath, false);
linkage.show(rpropertiesPath, true);
linkage.show(wpropertiesPath, false);
linkage.show(functionPath, false);
linkage.show(functionParamPath, false);
return;
case 'WRITE_PROPERTY':
linkage.enum(
wpropertiesPath,
productRef.current.metadata.properties.map((item: any) => ({ label: item.name, value: item.id, ...item })));
linkage.show(wpropertiesPath, true);
linkage.show(rpropertiesPath, false);
linkage.show(valuePath, true);
linkage.show(functionPath, false);
linkage.show(functionParamPath, false);
return;
case 'INVOKE_FUNCTION':
linkage.hide(wpropertiesPath, false);
linkage.hide(rpropertiesPath, false);
linkage.show(valuePath, false);
linkage.show(functionPath, true);
linkage.enum(functionPath,
productRef.current.metadata.functions.map((item: any) => ({ label: item.name, value: item.id, ...item })));
return;
default:
return;
}
});
onFieldValueChange$('actionMappings.*.actionType').subscribe(fieldState => {
if (fieldState.value === 'latestData') {
linkage.hide(FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.messageType)`), false);
linkage.show(FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.message._properties)`), true);
} else if (fieldState.value === 'command') {
linkage.hide(FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.messageType)`), true);
}
});
onFieldValueChange$('id').subscribe(fieldState => {
if (!fieldState.value) return;
const product = testRef.current.list.find((item: any) => item.id === fieldState.value);
try {
product.metadata = JSON.parse(product.metadata);
} catch (error) {
message.error('解析产品数据错误,请检查产品是否存在!');
props.close();
return;
}
productRef.current = product;
linkage.show('applianceType', true);
!props.data.id&& linkage.value('name', product.name);
});
onFieldValueChange$('actionMappings.*.command.message.functionId').subscribe(fieldState => {
if (!fieldState.value) return;
const funcPath = FormPath.transform(fieldState.name, /\d/, $1 => `*(actionMappings.${$1}.command.message.function)`);
const func = productRef.current.metadata.functions.find((item: any) => item.id === fieldState.value);
linkage.value(funcPath, func.inputs || {});
linkage.show(funcPath, true);
const componentMap = {
"string": "input",
"int": "numberpicker"
}
const componentType = {
'string': 'string',
'int': 'number',
}
const list = {};
(func.inputs || []).forEach((item: any) => {
const valueType = item.valueType;
list['funcparam.' + item.id] = {
"title": item.description ? `{{text("${item.name}",help("${item.description.replaceAll('\n', '')}"))}}` : item.name,
"x-component": componentMap[valueType.type],
"type": componentType[valueType.type],
"x-component-props": {
"width": "100%"
},
"x-mega-props": {
"span": 1,
"labelCol": 10
},
}
});
// 参数列表
setFuncList(list);
})
}
return (
<Modal
width='70VW'
title={`${props.data.id ? '编辑' : '新建'}`}
visible
okText="确定"
cancelText="取消"
onOk={() => { actions.submit() }}
onCancel={() => props.close()}
>
<Spin spinning={loading}>
{!loading && <SchemaForm
effects={linkageEffect}
expressionScope={createRichTextUtils()}
initialValues={props.data}
actions={actions}
onSubmit={data => {
if (data.actionMappings?.length > 1) {
data.actionMappings.map((item: any) => {
const funcParam = item?.command?.message?.funcparam;
const inputs: any = []
if (funcParam) {
Object.keys(funcParam).forEach(key => {
inputs.push({
name: key,
value: funcParam[key]
})
})
}
item.command = item.command ? item.command : {};
if (!item.command.message) {
item.command.message = {};
if (!item.command.message.inputs) {
item.command.message.inputs = inputs;
}
} else {
item.command.message.inputs = inputs;
}
if (item?.command?.messageType === 'WRITE_PROPERTY') {
const temp = {};
const key = item.command.message._properties;
const value = item.command.message._value;
temp[key] = value;
item.command.message.properties = temp;
}
return item
});
}
props.save(data);
}}
components={{ DatePicker, Input, Select, ArrayPanels, ArrayTable, FormCard, NumberPicker }}
schema={{
"type": "object",
"properties": {
"NO_NAME_FIELD_$0": {
"type": "object",
"x-component": "mega-layout",
"x-component-props": {
"grid": true,
"autoRow": true,
"columns": 2,
"labelCol": 4
},
"properties": {
"id": {
"title": '产品',
"x-mega-props": {
"span": 1,
},
"x-rules": [
{
"required": true,
"message": "此字段必填"
}
],
readOnly:!!props.data.id,
"enum": productInfo.list,
"x-component": "select",
"x-component-props":{
showSearch:true,
optionFilterProp:'children'
}
},
"name": {
"x-mega-props": {
"span": 1,
},
"title": "名称",
"x-component": "input",
"x-rules": [
{
"required": true,
"message": "此字段必填"
}
],
},
"manufacturerName": {
"x-mega-props": {
"span": 1,
},
"title": "厂商名称",
"x-component": "input",
"x-rules": [
{
"required": true,
"message": "此字段必填"
}
],
},
"version": {
"x-mega-props": {
"span": 1,
},
"title": "设备版本",
"x-component": "input",
"x-component-props":{
showSearch:true,
optionFilterProp:'children'
},
"x-rules": [
{
"required": true,
"message": "此字段必填"
}
],
},
"applianceType": {
"x-mega-props": {
"span": 1,
},
"title": "设备类型",
"x-rules": [
{
"required": true,
"message": "此字段必填"
}
],
"x-component": "select",
"x-component-props":{
showSearch:true,
optionFilterProp:'children'
},
"visible": false,
"enum": productInfo.type
},
"actionMappings": {
"x-mega-props": {
"span": 4,
"labelCol": 2
},
"title": "动作映射",
"x-component": "arraypanels",
"type": "array",
// "visible": false,
"items": {
"type": "object",
"properties": {
"action": {
"title": "动作",
"x-component": "select",
"x-rules": [
{
"required": true,
"message": "此字段必填"
}
],
},
"actionType": {
"title": "操作",
"x-component": "select",
"enum": [
{ "label": "下发指令", "value": "command" },
{ "label": "获取历史数据", "value": "latestData" }
],
"x-rules": [
{
"required": true,
"message": "此字段必填"
}
],
},
"command.messageType": {
"title": "指令类型",
"x-component": "select",
"visible": false,
"enum": [
{ "label": "读取属性", "value": "READ_PROPERTY" },
{ "label": "修改属性", "value": "WRITE_PROPERTY" },
{ "label": "调用功能", "value": "INVOKE_FUNCTION" }
],
},
"command.message._properties": {
"title": "属性",
"x-component": "select",
"visible": false,
},
"command.message.properties": {
"title": "属性",
"x-component": "select",
"visible": false,
"x-component-props": {
"mode": "tags"
}
},
"command.message._value": {
"title": "值",
"x-component": "input",
"visible": false,
},
"command.message.functionId": {
"title": "功能",
"x-component": "select",
"visible": false,
},
"command.message.function": {
"x-mega-props": {
"span": 2,
},
"x-component": "block",
"x-component-props": {
"title": "参数列表",
"span": 2
},
"type": "object",
"visible": false,
"properties": funcList
}
}
}
},
"propertyMappings": {
"x-mega-props": {
"span": 4,
"labelCol": 2
},
"title": "属性映射",
"x-component": "arraypanels",
"type": "array",
// "visible": false,
"items": {
"type": "object",
"properties": {
"source": {
"title": "DuerOS",
"x-component": "select",
},
"target": {
"title": "平台属性",
"x-component": "select",
"x-props": {
"mode": 'tags'
}
}
}
}
},
}
}
}
}
} >
</SchemaForm>}
</Spin>
</Modal>
)
}
Example #14
Source File: index.tsx From jetlinks-ui-antd with MIT License | 4 votes |
Auth = (props: Props) => {
const service = new Service('open-api');
const [treeData, setTreeData] = useState<{ children: any; title: any; key: any }[]>();
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
const [permissions, setPermissions] = useState<any[]>();
useEffect(() => {
const selected: string[] = [];
zip(
service.permission.auth(
encodeQueryParam({
terms: {
dimensionTarget: props.current.id,
},
}),
),
service.permission.query({}),
)
.pipe(
map(list =>
list[1].map(item => ({
...item,
children: (item.children || []).map((i: any) => {
const flag = (list[0].find(j => j.key === item.key)?.actions || []).includes(i.key);
if (flag) selected.push(`${item.key}:${i.key}`);
return {
...i,
key: `${item.key}:${i.key}`,
enabled: flag,
};
}),
})),
),
)
.subscribe(data => {
setTreeData(data);
setExpandedKeys(data.map(item => item.key));
setCheckedKeys(selected);
setPermissions(data);
});
}, []);
const onExpand = expandedKeys => {
setExpandedKeys(expandedKeys);
setAutoExpandParent(false);
};
const onCheck = (keys?: any) => {
setCheckedKeys(keys);
const list: { id: string; actions: string[] }[] = [];
keys
.filter((i: string) => i.indexOf(':') > 0)
.forEach((j: string) => {
const id = j.split(':')[0];
const action = j.split(':')[1];
const temp = list.findIndex(i => i.id === id);
if (temp > -1) {
list[temp].actions.push(action);
} else {
list.push({ id, actions: [action] });
}
});
setPermissions(list);
return list;
};
const onSelect = (selectedKeys, info) => {
setSelectedKeys(selectedKeys);
};
const updateAuth = () => {
const permissions = onCheck(checkedKeys);
service.permission
.save({
targetId: props.current.id,
targetType: 'open-api',
permissionList: permissions,
})
.subscribe(() => {
message.success('保存成功');
});
};
return (
<Drawer
title="授权"
width="50VW"
visible
onClose={() => props.close()}
bodyStyle={{
overflow: 'auto',
height: '800px',
}}
>
<Tree
defaultExpandAll
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onCheck}
checkedKeys={checkedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={treeData}
/>
<div
style={{
position: 'absolute',
right: 0,
bottom: 0,
width: '100%',
borderTop: '1px solid #e9e9e9',
padding: '10px 16px',
background: '#fff',
textAlign: 'right',
}}
>
<Button
onClick={() => {
props.close();
}}
style={{ marginRight: 8 }}
>
关闭
</Button>
<Button
onClick={() => {
updateAuth();
}}
type="primary"
>
保存
</Button>
</div>
</Drawer>
);
}
Example #15
Source File: index.tsx From jetlinks-ui-antd with MIT License | 4 votes |
Save = (props: Props) => {
const service = new Service('tenant');
const [tempMap, setTempMap] = useState<any>([]);
const [loading, setLoading] = useState<boolean>(true);
const [userList, setUserList] = useState<any[]>();
const [selectedRow, setSelectedRow] = useState<any[]>([]);
const [result, setResult] = useState<any>({});
const {
data: { id },
} = props;
const [searchParam, setSearchParam] = useState<any>({
pageSize: 10,
terms: {
'id$tenant-user$not': id || undefined,
},
});
const handleSearch = (params: any) => {
setSearchParam(params);
if (id) {
zip(
service.member.userlist(encodeQueryParam(params)),
service.member.query(id, {}),
).subscribe(data => {
setLoading(false);
const all: any[] = data[0].data;
const checked: any[] = data[1].map((i: any) => i.userId);
setResult(data[0]);
const unchecked = all.filter(item => !checked.includes(item.id));
setLoading(false);
setUserList(unchecked);
});
}
};
useEffect(() => {
handleSearch(searchParam);
}, []);
const rowSelection = {
selectedRowKeys: selectedRow.map(item => item.id),
onChange: (selectedRowKeys: any[], selectedRows: any[]) => {
setSelectedRow(selectedRows);
},
getCheckboxProps: (record: any) => ({
name: record.name,
}),
};
const saveData = () => {
if (selectedRow.length <= 0) {
message.error('请勾选绑定用户');
return;
}
setLoading(true);
// const tempData = selectedRow.map(item=>{
// if(item.status===1){
// return {
// name: item.name,
// userId: item.id,
// state:'enabled',
// admin: tempMap.find((i: { id: string }) => i.id === item.id)?.tag || false,
// }
// }else{
// return {
// name: item.name,
// userId: item.id,
// state:'disabled',
// admin: tempMap.find((i: { id: string }) => i.id === item.id)?.tag || false,
// }
// }
// })
const tempData = selectedRow.map(item => ({
name: item.name,
userId: item.id,
state:item.status,
admin: tempMap.find((i: { id: string }) => i.id === item.id)?.tag || false,
}));
const tempId = props.data?.id;
if (tempId) {
service.member.bind(tempId, tempData).subscribe(() => {
setLoading(false);
message.success('保存成功');
setSelectedRow([]);
props.close();
});
}
};
const columns = [
{
title: '姓名',
dataIndex: 'name',
},
{
title: '用户名',
dataIndex: 'username',
},
{
title: '是否管理员',
dataIndex: 'id',
render: (text: string) => (
<Switch
onChange={(e: boolean) => {
if (e === false) {
//移除
const t = tempMap.filter((i: { id: string }) => i.id !== text);
setTempMap(t);
} else {
tempMap.push({ id: text, tag: e });
setTempMap(tempMap);
}
}}
/>
),
},
];
const onTableChange = (pagination: any, filters: any, sorter: any) => {
handleSearch({
pageIndex: Number(pagination.current) - 1,
pageSize: pagination.pageSize,
terms: searchParam.terms,
// sorts: sorter.field ? sorter : searchParam.sorter,
});
};
return (
<Drawer visible width="40VW" title="添加用户" onClose={() => props.close()}>
<Input.Search
placeholder="输入姓名搜索"
style={{ marginBottom: 10 }}
onSearch={value => {
handleSearch({
pageSize: 10,
terms: { name$LIKE: value },
});
}}
/>
<div style={{ marginBottom: '30px' }}>
<Table
size="small"
loading={loading}
rowKey="id"
rowSelection={rowSelection}
columns={columns}
dataSource={result.data}
onChange={onTableChange}
pagination={{
current: result.pageIndex + 1,
total: result.total,
pageSize: result.pageSize,
showQuickJumper: true,
showSizeChanger: true,
pageSizeOptions: ['10', '20', '50', '100'],
showTotal: (total: number) =>
`共 ${total} 条记录 第 ${result.pageIndex + 1}/${Math.ceil(
result.total / result.pageSize,
)}页`,
}}
/>
</div>
<div
style={{
position: 'absolute',
right: 0,
bottom: 0,
width: '100%',
borderTop: '1px solid #e9e9e9',
padding: '10px 16px',
background: '#fff',
textAlign: 'right',
}}
>
<Button
onClick={() => {
props.close();
}}
style={{ marginRight: 8 }}
>
关闭
</Button>
<Button
onClick={() => {
saveData();
}}
type="primary"
>
保存
</Button>
</div>
</Drawer>
);
}
Example #16
Source File: capacitor-storage-preferences.spec.ts From capture-lite with GNU General Public License v3.0 | 4 votes |
describe('CapacitorStoragePreferences', () => {
let preferences: Preferences;
const id = 'id';
beforeEach(() => {
TestBed.configureTestingModule({
imports: [SharedTestingModule],
providers: [{ provide: STORAGE_PLUGIN, useValue: Storage }],
});
const storagePlugin = TestBed.inject(STORAGE_PLUGIN);
preferences = new CapacitorStoragePreferences(id, storagePlugin);
});
it('should be created', () => expect(preferences).toBeTruthy());
it('should get the same ID set in constructor', () =>
expect(preferences.id).toEqual(id));
it('should get the default boolean Observable if not set previously', done => {
const notExistedKey = 'unknown';
const defaultValue = true;
preferences.getBoolean$(notExistedKey, defaultValue).subscribe(result => {
expect(result).toEqual(defaultValue);
done();
});
});
it('should get the default number Observable if not set previously', done => {
const notExistedKey = 'unknown';
const defaultValue = 999;
preferences.getNumber$(notExistedKey, defaultValue).subscribe(result => {
expect(result).toEqual(defaultValue);
done();
});
});
it('should get the default string Observable if not set previously', done => {
const notExistedKey = 'unknown';
const defaultValue = 'default';
preferences.getString$(notExistedKey, defaultValue).subscribe(result => {
expect(result).toEqual(defaultValue);
done();
});
});
it('should get the default boolean value if not set previously', async () => {
const notExistedKey = 'unknown';
const defaultValue = true;
const bool = await preferences.getBoolean(notExistedKey, defaultValue);
expect(bool).toEqual(defaultValue);
});
it('should get the default number value if not set previously', async () => {
const notExistedKey = 'unknown';
const defaultValue = 999;
const num = await preferences.getNumber(notExistedKey, defaultValue);
expect(num).toEqual(defaultValue);
});
it('should get the default string value if not set previously', async () => {
const notExistedKey = 'unknown';
const defaultValue = 'default';
const str = await preferences.getString(notExistedKey, defaultValue);
expect(str).toEqual(defaultValue);
});
it('should get the same boolean Observable set previously', done => {
const key = 'key';
const value = true;
defer(() => preferences.setBoolean(key, value))
.pipe(concatMapTo(preferences.getBoolean$(key)))
.subscribe(result => {
expect(result).toEqual(value);
done();
});
});
it('should get the same number Observable set previously', done => {
const key = 'key';
const value = 99;
defer(() => preferences.setNumber(key, value))
.pipe(concatMapTo(preferences.getNumber$(key)))
.subscribe(result => {
expect(result).toEqual(value);
done();
});
});
it('should get the same string Observable set previously', done => {
const key = 'key';
const value = 'value';
defer(() => preferences.setString(key, value))
.pipe(concatMapTo(preferences.getString$(key)))
.subscribe(result => {
expect(result).toEqual(value);
done();
});
});
it('should get the same boolean value set previously', async () => {
const key = 'key';
const value = true;
await preferences.setBoolean(key, value);
const result = await preferences.getBoolean(key);
expect(result).toEqual(value);
});
it('should get the same number value set previously', async () => {
const key = 'key';
const value = 99;
await preferences.setNumber(key, value);
const result = await preferences.getNumber(key);
expect(result).toEqual(value);
});
it('should get the same string value set previously', async () => {
const key = 'key';
const value = 'value';
await preferences.setString(key, value);
const result = await preferences.getString(key);
expect(result).toEqual(value);
});
it('should set boolean atomically', done => {
const key = 'key';
const operationCount = 100;
const lastBoolean = true;
const booleans: boolean[] = [
...Array(operationCount - 1).fill(false),
lastBoolean,
];
defer(() =>
Promise.all(booleans.map(bool => preferences.setBoolean(key, bool)))
)
.pipe(concatMapTo(preferences.getBoolean$(key)))
.subscribe(result => {
expect(result).toEqual(lastBoolean);
done();
});
});
it('should set number atomically', done => {
const key = 'key';
const operationCount = 100;
const lastNumber = -20;
const numbers: number[] = [...Array(operationCount - 1).keys(), lastNumber];
defer(() => Promise.all(numbers.map(n => preferences.setNumber(key, n))))
.pipe(concatMapTo(preferences.getNumber$(key)))
.subscribe(result => {
expect(result).toEqual(lastNumber);
done();
});
});
it('should set string atomically', done => {
const key = 'key';
const operationCount = 1000;
const lastString = 'last';
const strings: string[] = [
...`${Array(operationCount - 1).keys()}`,
lastString,
];
defer(() =>
Promise.all(strings.map(str => preferences.setString(key, str)))
)
.pipe(concatMapTo(preferences.getString$(key)))
.subscribe(result => {
expect(result).toEqual(lastString);
done();
});
});
it('should remove all values after clear', done => {
const booleanKey = 'booleanKey';
const booleanValue = true;
const defaultBooleanValue = false;
const numberKey = 'numberKey';
const numberValue = 77;
const defaultNumberValue = 55;
const stringKey = 'stringKey';
const stringValue = 'stringValue';
const defaultStringValue = 'defaultStringValue';
defer(async () => {
await preferences.setBoolean(booleanKey, booleanValue);
await preferences.setNumber(numberKey, numberValue);
await preferences.setString(stringKey, stringValue);
await preferences.clear();
})
.pipe(
concatMapTo(
zip(
preferences.getBoolean$(booleanKey, defaultBooleanValue),
preferences.getNumber$(numberKey, defaultNumberValue),
preferences.getString$(stringKey, defaultStringValue)
)
),
first()
)
.subscribe(([booleanResult, numberResult, stringResult]) => {
expect(booleanResult).toEqual(defaultBooleanValue);
expect(numberResult).toEqual(defaultNumberValue);
expect(stringResult).toEqual(defaultStringValue);
done();
});
});
it('should clear idempotently', async () => {
const key = 'key';
const expected = 2;
await preferences.setNumber(key, 1);
await preferences.clear();
await preferences.clear();
expect(await preferences.getNumber(key, expected)).toEqual(expected);
});
});