immutable#Map TypeScript Examples
The following examples show how to use
immutable#Map.
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: Accounts.ts From compound-protocol with BSD 3-Clause "New" or "Revised" License | 6 votes |
export function loadAccounts(accounts: string[]): Accounts {
return Object.entries(accountMap).reduce((acc, [name, index]) => {
if (accounts[index]) {
return acc.set(name, { name: name, address: accounts[index] });
} else {
return acc;
}
}, <Map<string, Account>>Map({}));
}
Example #2
Source File: htmlToDraft.ts From brilliant with MIT License | 6 votes |
function getSoftNewlineChunk(block, depth, flat = false, data = Map()) {
if (flat === true) {
return {
text: '\r',
inlines: [OrderedSet()],
entities: new Array(1),
blocks: [
{
type: block,
data,
depth: Math.max(0, Math.min(MAX_DEPTH, depth)),
},
],
isNewline: true,
};
}
return {
text: '\n',
inlines: [OrderedSet()],
entities: new Array(1),
blocks: [],
};
}
Example #3
Source File: loadOutgoingTransactions.ts From multisig-react with MIT License | 6 votes |
loadOutgoingTransactions = async (safeAddress: string): Promise<SafeTransactionsType> => {
const defaultResponse = {
cancel: Map(),
outgoing: List(),
}
const state = store.getState()
if (!safeAddress) {
return defaultResponse
}
const currentUser: string = state[PROVIDER_REDUCER_ID].get('account')
const safe: SafeRecord = state[SAFE_REDUCER_ID].getIn(['safes', safeAddress])
if (!safe) {
return defaultResponse
}
const { eTag, results }: { eTag: string | null; results: TxServiceModel[] } = await fetchTransactions(
TransactionTypes.OUTGOING,
safeAddress,
previousETag,
)
previousETag = eTag
const { cancellationTxs, outgoingTxs } = extractCancelAndOutgoingTxs(safeAddress, results)
// this should be only used for the initial load or when paginating
const { cancel, outgoing } = await batchProcessOutgoingTransactions({
cancellationTxs,
currentUser,
outgoingTxs,
safe,
})
return {
cancel: fromJS(cancel),
outgoing: fromJS(outgoing),
}
}
Example #4
Source File: GenericListItemMore.tsx From ui-schema with MIT License | 6 votes |
GenericListItemMore = (
{
index, listRequired, schema,
onChange, storeKeys, notDeletable, btnSize = 'small',
}: GenericListItemSharedProps,
): React.ReactElement => {
const readOnly = schema.get('readOnly')
return <React.Fragment>
{!readOnly && !notDeletable ?
<IconButton
onClick={() =>
onChange({
storeKeys,
scopes: ['value', 'internal'],
type: 'list-item-delete',
index: index,
schema,
required: listRequired,
})
}
size={btnSize}
style={{margin: '0 0 auto 0'}}
>
<AccessTooltipIcon
title={
<Trans text={'labels.remove-item'} context={Map({actionLabels: schema.get('listActionLabels')})}/>
}
>
<Delete fontSize={'inherit'} style={{margin: btnSize === 'small' ? 2 : undefined}}/>
</AccessTooltipIcon>
</IconButton> : null}
</React.Fragment>
}
Example #5
Source File: Networks.ts From compound-protocol with BSD 3-Clause "New" or "Revised" License | 5 votes |
function readNetworkFile(world: World, isABI: boolean): Promise<Networks> {
return readFile(
world,
getNetworkPath(world.basePath, world.network, isABI ? '-abi' : ''),
Map({}),
parseNetworkFile
);
}
Example #6
Source File: index.ts From zebra-editor-core with MIT License | 5 votes |
style: Map<string, any> = Map();
Example #7
Source File: SampleTemplate.ts From apl-suggester with Apache License 2.0 | 5 votes |
export function getSampleTemplates() : Map<string, ISampleTemplate> {
return SAMPLE_TEMPLATE_METADATA;
}
Example #8
Source File: insertEmptyBlock.ts From brilliant with MIT License | 5 votes |
insertEmptyBlock = (editorState, blockType = 'unstyled', data = {}) => {
const contentState = editorState.getCurrentContent();
const selection = editorState.getSelection();
const key = selection.getStartKey();
const currentBlock = contentState.getBlockForKey(key);
const emptyBlockKey = genKey();
const emptyBlock = new ContentBlock({
characterList: List(),
depth: 0,
key: emptyBlockKey,
text: '',
type: blockType,
data: Map().merge(data),
});
const blockMap = contentState.getBlockMap();
const blocksBefore = blockMap
.toSeq()
.takeUntil(value => value === currentBlock);
const blocksAfter = blockMap
.toSeq()
.skipUntil(value => value === currentBlock)
.rest();
const augmentedBlocks = [
[currentBlock.getKey(), currentBlock],
[emptyBlockKey, emptyBlock],
];
const newBlocks = blocksBefore
.concat(augmentedBlocks, blocksAfter)
.toOrderedMap();
const focusKey = emptyBlockKey;
const newContentState = contentState.merge({
blockMap: newBlocks,
selectionBefore: selection,
selectionAfter: selection.merge({
anchorKey: focusKey,
anchorOffset: 0,
focusKey,
focusOffset: 0,
isBackward: false,
}),
});
return EditorState.push(editorState, newContentState, 'split-block');
}
Example #9
Source File: fetchSafe.ts From multisig-react with MIT License | 5 votes |
buildSafe = async (
safeAdd: string,
safeName: string,
latestMasterContractVersion?: string,
): Promise<SafeRecordProps> => {
const safeAddress = checksumAddress(safeAdd)
const safeParams = ['getThreshold', 'nonce', 'VERSION', 'getOwners']
const [
[, thresholdStr, nonceStr, currentVersion, remoteOwners = []],
safeInfo,
localSafe,
ethBalance,
] = await Promise.all([
generateBatchRequests<[undefined, string | undefined, string | undefined, string | undefined, string[]]>({
abi: GnosisSafeSol.abi as AbiItem[],
address: safeAddress,
methods: safeParams,
}),
getSafeInfo(safeAddress),
getLocalSafe(safeAddress),
getBalanceInEtherOf(safeAddress),
])
const threshold = Number(thresholdStr)
const nonce = Number(nonceStr)
const owners = buildOwnersFrom(remoteOwners, localSafe)
const needsUpdate = safeNeedsUpdate(currentVersion, latestMasterContractVersion)
const featuresEnabled = enabledFeatures(currentVersion)
const modules = await getModules(safeInfo)
const spendingLimits = safeInfo ? await getSpendingLimits(safeInfo.modules, safeAddress) : null
return {
address: safeAddress,
name: safeName,
threshold,
owners,
ethBalance,
nonce,
currentVersion: currentVersion ?? '',
needsUpdate,
featuresEnabled,
balances: localSafe?.balances || Map(),
latestIncomingTxBlock: 0,
activeAssets: Set(),
activeTokens: Set(),
blacklistedAssets: Set(),
blacklistedTokens: Set(),
modules,
spendingLimits,
}
}
Example #10
Source File: GenericListFooter.tsx From ui-schema with MIT License | 5 votes |
GenericListFooter: React.ComponentType<GenericListFooterProps> = (
{
schema, required,
onChange, storeKeys,
notAddable,
btnColor, btnVariant, btnSize,
btnAddShowLabel, btnAddStyle,
errors, showValidity,
}
) => {
return <Box mt={2}>
{!schema.get('readOnly') && !notAddable ?
<ListButton
onClick={() => {
onChange({
storeKeys,
scopes: ['value', 'internal'],
type: 'list-item-add',
schema,
required,
})
}}
btnSize={btnSize}
btnVariant={btnVariant}
btnColor={btnColor}
showLabel={btnAddShowLabel}
style={btnAddStyle}
Icon={Add}
title={
<Trans
text={'labels.add-item'}
context={Map({actionLabels: schema.get('listActionLabels')})}
/>
}
/> : null}
<ValidityHelperText
/*
* only pass down errors which are not for a specific sub-schema
* todo: check if all needed are passed down
*/
errors={errors}
showValidity={showValidity}
schema={schema}
/>
</Box>
}
Example #11
Source File: SampleTemplate.ts From apl-suggester with Apache License 2.0 | 4 votes |
SAMPLE_TEMPLATE_METADATA : Map<string, ISampleTemplate> = Map({
IMAGE_RIGHT_DETAIL : {
apl: detailImageRightApl,
data: detailImageRightData
},
IMAGE_LEFT_DETAIL : {
apl: detailImageLeftApl,
data: detailImageLeftData
},
GRID_LIST : {
apl: gridListDarkApl,
data: gridListDarkData
},
HEADLINE : {
apl: headlineDarkApl,
data: headlineDarkData
},
IMAGE_LIST : {
apl: imageListDarkApl,
data: imageListDarkData
},
PAGINATED_LIST : {
apl: paginatedListDarkApl,
data: paginatedListDarkData
},
TEXT_LIST : {
apl: textListDarkApl,
data: textListDarkData
},
DETAILS : {
apl: detailImageRightLightApl,
data: detailImageRightLightData
},
GRID : {
apl: gridListLightApl,
data: grigListLightData
},
SHORT_TEXT : {
apl: headlineLightApl,
data: headlineLightData
},
HORIZONTAL_LIST : {
apl: imageListLightApl,
data: imageListLightData
},
FULL_SCREEN_LIST : {
apl: paginatedListLightApl,
data: paginatedListLightData
},
VERTICAL_LIST : {
apl: textListLightApl,
data: textListLightData
},
VIDEO_PLAYER : {
apl: videoPlayerApl,
data: videoPlayerData
},
IMAGE_DISPLAY : {
apl: imageDisplayApl,
data: imageDisplayData
},
FULL_TEXT : {
apl: longTextApl,
data: longTextData
},
CHECK_LIST : {
apl: checkListApl,
data: checkListData
},
ANALOG_CLOCK : {
apl: aplAnalogClockApl,
data: aplAnalogClockData
},
DANCING_EQUALIZER_BARS : {
apl: aplEqualizerApl,
data: aplEqualizerData
},
ANIMATED_BACKGROUND : {
apl: aplAnimateLeafsBgApl,
data: aplAnimateLeafsBgData
},
PARALLAX_EFFECT : {
apl: parallaxEffectApl,
data: parallaxEffectData
},
ANIMATION : {
apl: animationApl,
data: animationData
},
START_FROM_SCRATCH : {
apl: defaultApl,
data: defaultData
},
LONG_TEXT_SAMPLE : {
apl: longTextSampleApl,
data: longTextSampleData
},
IMAGE_RIGHT_DETAIL_SAMPLE : {
apl: imageRightDetailApl,
data: imageRightDetailData
},
IMAGE_LEFT_DETAIL_SAMPLE : {
apl: imageLeftDetailApl,
data: imageLeftDetailData
},
SHORT_TEXT_SAMPLE : {
apl: shortTextApl,
data: shortTextData
},
IMAGE_DISPLAY_SAMPLE : {
apl: imageDisplaySampleApl,
data: imageDisplaySampleData
},
TEXT_FORWARD_LIST_SAMPLE : {
apl: textForwardListApl,
data: textForwardListData
},
IMAGE_FORWARD_LIST_SAMPLE : {
apl: imageForwardlistApl,
data: imageForwardListData
}
})
Example #12
Source File: index.tsx From aqualink-app with MIT License | 4 votes |
Apply = ({ classes }: ApplyProps) => {
const dispatch = useDispatch();
const user = useSelector(userInfoSelector);
const [formModel, setFormModel] = useState(Map<string, string | boolean>());
const [formErrors, setFormErrors] = useState(Map<string, string>());
const [registerDialogOpen, setRegisterDialogOpen] = useState(false);
const [signInDialogOpen, setSignInDialogOpen] = useState(false);
const [snackbarOpenFromDatabase, setSnackbarOpenFromDatabase] =
useState(false);
const [snackbarOpenFromCarto, setSnackbarOpenFromCarto] = useState(false);
const [databaseSubmissionOk, setDatabaseSubmissionOk] = useState(false);
const [submitLoading, setSubmitLoading] = useState(false);
const [newSiteId, setNewSiteId] = useState<number>();
const handleRegisterDialog = (open: boolean) => setRegisterDialogOpen(open);
const handleSignInDialog = (open: boolean) => setSignInDialogOpen(open);
useEffect(() => {
if (user && user.fullName && user.email) {
setFormModel(
formModel
.set("name", user.fullName)
.set("org", user.organization || " ")
.set("email", user.email)
);
} else {
setFormModel(formModel.set("name", "").set("org", "").set("email", ""));
}
}, [user, formModel]);
const contactFormElements: FormElement[] = [
{ id: "name", label: "Name" },
{ id: "org", label: "Organization" },
{
id: "email",
label: "Email",
validator: validators.isEmail,
},
];
const locationFormElements: FormElement[] = [
{
id: "lat",
label: "Latitude",
validator: validators.isLat,
},
{
id: "lng",
label: "Longitude",
validator: validators.isLong,
},
{ id: "siteName", label: "Site Name" },
{
id: "depth",
label: "Depth (m)",
validator: validators.isInt,
},
];
const joinedFormElements = locationFormElements.concat(contactFormElements);
function updateFormElement(id: string, value: string | boolean) {
setFormModel(formModel.set(id, value));
}
function updateMarkerPosition(position: L.LatLngTuple) {
const [lat, lng] = position;
setFormModel(
formModel.set("lat", lat.toString()).set("lng", lng.toString())
);
}
function handleFormSubmission() {
const errors = joinedFormElements.reduce(
(acc, { id, label, validator }) => {
const value = formModel.get(id);
if (!value) {
return { ...acc, [id]: `"${label}" is required` };
}
const errorMessage = validator && validator(value as string);
if (errorMessage) {
return { ...acc, [id]: errorMessage };
}
return acc;
},
{}
);
setFormErrors(fromJS(errors));
if (isEmpty(errors)) {
const { siteName, lat, lng, depth } = formModel.toJS() as {
[key: string]: string;
};
// Add to database
if (user && user.token) {
setSubmitLoading(true);
siteServices
.registerSite(
siteName,
parseFloat(lat),
parseFloat(lng),
parseInt(depth, 10),
user.token
)
.then(({ data }) => {
setNewSiteId(data.site.id);
setDatabaseSubmissionOk(true);
setSnackbarOpenFromDatabase(true);
if (user?.token) {
dispatch(getSelf(user.token));
}
})
.catch((error) => {
setDatabaseSubmissionOk(false);
setSnackbarOpenFromDatabase(true);
console.error(error);
})
.finally(() => setSubmitLoading(false));
}
}
}
const textFieldProps = {
fullWidth: true,
variant: "outlined" as "outlined",
size: "small" as "small",
InputProps: { classes: pick(classes, ["root", "notchedOutline"]) },
};
return (
<>
{newSiteId && <Redirect to={`/sites/${newSiteId}`} />}
<NavBar searchLocation={false} />
<Box className={classes.boxBar} height="100%" pt={4}>
<Container>
<Grid container spacing={6}>
<Grid item xs={12}>
<Typography variant="h3" gutterBottom>
Register your local site
</Typography>
<Typography>
To get your local site registered with Aqualink please complete
the form below. Your site will become immediately available for
you to see though some of the satellite and model data will take
up to 24 hours to show up.
</Typography>
</Grid>
</Grid>
</Container>
<Box bgcolor="grey.100" mt={8} p={{ xs: 0, md: 4 }}>
<Container>
<Grid container spacing={6}>
<Grid item xs={12} md={7}>
<LocationMap
markerPositionLat={formModel.get("lat", "") as string}
markerPositionLng={formModel.get("lng", "") as string}
updateMarkerPosition={updateMarkerPosition}
/>
</Grid>
<Grid item xs={12} md={5}>
<Paper elevation={2}>
<Box color="text.secondary" p={4}>
<Typography variant="h4" gutterBottom>
Site Information
</Typography>
{!user && (
<Typography variant="h6" gutterBottom>
Please
<Button
color="primary"
onClick={() => handleRegisterDialog(true)}
>
Sign up
</Button>
/
<Button
color="primary"
onClick={() => handleSignInDialog(true)}
>
Sign in
</Button>
before registering a new site
</Typography>
)}
<Grid container spacing={2}>
<>
{contactFormElements.map(({ id, label }) => (
<Grid item xs={12} key={label}>
<TextField
id={id}
disabled
label={label}
error={formErrors.get(id, "").length !== 0}
helperText={formErrors.get(id, "")}
value={formModel.get(id, "")}
onChange={(e) =>
updateFormElement(id, e.target.value)
}
{...textFieldProps}
/>
</Grid>
))}
<Grid item xs={12}>
<Typography>Location: Select point on map</Typography>
</Grid>
{locationFormElements.map(({ id, label }) => (
<Grid
item
// eslint-disable-next-line no-nested-ternary
xs={
// eslint-disable-next-line no-nested-ternary
id === "siteName" ? 8 : id === "depth" ? 4 : 6
}
key={label}
>
<TextField
id={id}
label={label}
error={formErrors.get(id, "").length !== 0}
helperText={formErrors.get(id, "")}
value={formModel.get(id, "")}
onChange={(e) =>
updateFormElement(id, e.target.value)
}
{...textFieldProps}
/>
</Grid>
))}
<Grid item xs={12}>
<Tooltip
disableHoverListener={Boolean(user)}
title="Please Sign up before registering a new site"
>
<div>
<Button
disabled={!user || submitLoading}
fullWidth
variant="contained"
color="primary"
onClick={handleFormSubmission}
>
{submitLoading ? "Saving..." : "Submit"}
</Button>
</div>
</Tooltip>
</Grid>
</>
</Grid>
</Box>
</Paper>
</Grid>
</Grid>
</Container>
</Box>
</Box>
<Snackbar
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
open={snackbarOpenFromCarto && snackbarOpenFromDatabase}
autoHideDuration={4000}
onClose={() => {
setSnackbarOpenFromCarto(false);
setSnackbarOpenFromDatabase(false);
}}
>
<Alert
onClose={() => {
setSnackbarOpenFromCarto(false);
setSnackbarOpenFromDatabase(false);
}}
severity={databaseSubmissionOk ? "success" : "error"}
elevation={6}
variant="filled"
>
{databaseSubmissionOk
? "Application successfully submitted."
: "Something went wrong, please try again"}
</Alert>
</Snackbar>
<Footer />
<RegisterDialog
open={registerDialogOpen}
handleRegisterOpen={handleRegisterDialog}
handleSignInOpen={handleSignInDialog}
/>
<SignInDialog
open={signInDialogOpen}
handleRegisterOpen={handleRegisterDialog}
handleSignInOpen={handleSignInDialog}
/>
</>
);
}
Example #13
Source File: htmlToDraft.ts From brilliant with MIT License | 4 votes |
function genFragment(
node: { nodeName: string; textContent: any; firstChild: any },
inlineStyle: OrderedSet<unknown>,
lastList: string,
inBlock: string,
fragmentBlockTags: string | any[],
depth: number,
processCustomInlineStyles: (arg0: any, arg1: any, arg2: any) => any,
checkEntityNode: (
arg0: any,
arg1: any,
arg2: any,
arg3: any,
arg4: any,
arg5: any
) => any,
checkEntityText: any,
checkBlockType: (arg0: any, arg1: any, arg2: any, arg3: any) => any,
createEntity: any,
getEntity: any,
mergeEntityData: any,
replaceEntityData: any,
options: { flat: boolean },
inEntity: string
) {
let nodeName = node.nodeName.toLowerCase();
let newBlock = false;
let nextBlockType = 'unstyled';
if (nodeName === '#text') {
let text = node.textContent;
if (text.trim() === '' && inBlock === null) {
return getEmptyChunk();
}
if (text.trim() === '' && inBlock !== 'code-block') {
return getWhitespaceChunk(inEntity);
}
if (inBlock !== 'code-block') {
text = text.replace(REGEX_LF, SPACE);
}
const entities = Array(text.length).fill(inEntity);
let offsetChange = 0;
const textEntities = checkEntityText(
text,
createEntity,
getEntity,
mergeEntityData,
replaceEntityData
).sort(rangeSort);
textEntities.forEach(({ entity, offset, length, result }) => {
const adjustedOffset = offset + offsetChange;
if (result === null || result === undefined) {
result = text.substr(adjustedOffset, length);
}
const textArray = text.split('');
textArray.splice
.bind(textArray, adjustedOffset, length)
.apply(textArray, result.split(''));
text = textArray.join('');
entities.splice
.bind(entities, adjustedOffset, length)
.apply(entities, Array(result.length).fill(entity));
offsetChange += result.length - length;
});
return {
text,
inlines: Array(text.length).fill(inlineStyle),
entities,
blocks: [],
};
}
if (nodeName === 'br') {
const blockType = inBlock;
if (blockType === null) {
return getSoftNewlineChunk('unstyled', depth, true);
}
return getSoftNewlineChunk(blockType || 'unstyled', depth, options.flat);
}
let chunk = getEmptyChunk();
let newChunk = null;
inlineStyle = processInlineTag(nodeName, node, inlineStyle);
inlineStyle = processCustomInlineStyles(nodeName, node, inlineStyle);
if (nodeName === 'ul' || nodeName === 'ol') {
if (lastList) {
depth += 1;
}
lastList = nodeName;
inBlock = null;
}
let blockInfo = checkBlockType(nodeName, node, lastList, inBlock);
let blockType;
let blockDataMap;
if (blockInfo === false) {
return getEmptyChunk();
}
blockInfo = blockInfo || {};
if (typeof blockInfo === 'string') {
blockType = blockInfo;
blockDataMap = Map();
} else {
blockType = typeof blockInfo === 'string' ? blockInfo : blockInfo.type;
blockDataMap = blockInfo.data ? Map(blockInfo.data) : Map();
}
if (!inBlock && (fragmentBlockTags.indexOf(nodeName) !== -1 || blockType)) {
if(getBlockTypeForTag(nodeName, lastList)==='div'){
}
else{
chunk = getBlockDividerChunk(
blockType || getBlockTypeForTag(nodeName, lastList),
depth,
blockDataMap
);
inBlock = blockType || getBlockTypeForTag(nodeName, lastList);
newBlock = true;
}
} else if (
lastList &&
(inBlock === 'ordered-list-item' || inBlock === 'unordered-list-item') &&
nodeName === 'li'
) {
const listItemBlockType = getBlockTypeForTag(nodeName, lastList);
chunk = getBlockDividerChunk(listItemBlockType, depth);
inBlock = listItemBlockType;
newBlock = true;
nextBlockType =
lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item';
} else if (inBlock && inBlock !== 'atomic' && blockType === 'atomic') {
inBlock = blockType;
newBlock = true;
chunk = getSoftNewlineChunk(blockType, depth, true, blockDataMap);
}
let child = node.firstChild;
if (
child == null &&
inEntity &&
(blockType === 'atomic' || inBlock === 'atomic')
) {
child = document.createTextNode(' ');
}
if (child != null) {
nodeName = child.nodeName.toLowerCase();
}
let entityId = null;
while (child) {
entityId = checkEntityNode(
nodeName,
child,
createEntity,
getEntity,
mergeEntityData,
replaceEntityData
);
newChunk = genFragment(
child,
inlineStyle,
lastList,
inBlock,
fragmentBlockTags,
depth,
processCustomInlineStyles,
checkEntityNode,
checkEntityText,
checkBlockType,
createEntity,
getEntity,
mergeEntityData,
replaceEntityData,
options,
entityId || inEntity
);
chunk = joinChunks(chunk, newChunk, options.flat);
const sibling = child.nextSibling;
if (sibling && fragmentBlockTags.indexOf(nodeName) >= 0 && inBlock) {
let newBlockInfo = checkBlockType(nodeName, child, lastList, inBlock);
let newBlockType;
let newBlockData;
if (newBlockInfo !== false) {
newBlockInfo = newBlockInfo || {};
if (typeof newBlockInfo === 'string') {
newBlockType = newBlockInfo;
newBlockData = Map();
} else {
newBlockType =
newBlockInfo.type || getBlockTypeForTag(nodeName, lastList);
newBlockData = newBlockInfo.data ? Map(newBlockInfo.data) : Map();
}
chunk = joinChunks(
chunk,
getSoftNewlineChunk(newBlockType, depth, options.flat, newBlockData),
options.flat
);
}
}
if (sibling) {
nodeName = sibling.nodeName.toLowerCase();
}
child = sibling;
}
if (newBlock) {
chunk = joinChunks(
chunk,
getBlockDividerChunk(nextBlockType, depth, Map()),
options.flat
);
}
return chunk;
}
Example #14
Source File: demo2.tsx From yforms with MIT License | 4 votes |
Demo = () => {
const [form] = YForm.useForm();
const [loading, setLoading] = useState(true);
const [data, setData] = useState({});
const count = useRef(1);
const [diff, setDiff] = useState(false);
const loadData = useCallback(() => {
setTimeout(() => {
setData({
map: Map({ a: 1, b: 2, c: 3 }),
name: `原值_${count.current}`,
start: '1591943666',
end: '1592116466',
date: '1591943666',
phones: [{ start: '1591943666', end: '1592116466' }],
list: [{ age: '10' }],
});
count.current += 1;
setLoading(false);
}, 10);
}, []);
useEffect(() => {
loadData();
}, [loadData]);
const onFinish = (values: any) => {
loadData();
console.log('Success:', values);
};
return (
<YForm
name="basic"
form={form}
loading={loading}
onFinish={onFinish}
initialValues={data}
oldValues={{
date: '1592030066',
start: '1591943666',
end: '1592030066',
name: `原值_2`,
phones: [{ start: '1591943666', end: '1592030066' }],
}}
scenes={{ diff }}
>
{[
{
type: 'input',
label: '支持多层对象',
name: ['first', 'second'],
deFormat: (value) => `${value || ''} first 为 undefined `,
},
{
type: 'input',
label: 'immutable',
name: 'map',
deFormat: (value) => value && value.set('d', 4),
format: (value) => value && value.set('e', 5),
},
{
type: 'input',
label: '全格式化',
name: 'name',
deFormat: (value) => value && `${value}_deFormat`,
format: (value) => value && `${value}_format`,
},
{
type: 'datePicker',
label: '日期',
name: 'date',
deFormat: (value) => value && moment.unix(value),
format: (value) => value && `${moment(value).unix()}`,
},
{
type: 'rangePicker',
name: 'range',
label: '日期区间',
deFormat: (_, { start, end }) => {
return [start && moment.unix(start), end && moment.unix(end)];
},
format: [
{ name: 'range', isOmit: true },
{
name: 'start',
format: (_, { range = [] }) => range[0] && `${moment(range[0]).unix()}`,
},
{
name: 'end',
format: (_, { range = [] }) => range[1] && `${moment(range[1]).unix()}`,
},
],
},
{
type: 'list',
label: '动态数组日期',
name: 'phones',
componentProps: { isUseIconStyle: false },
items: ({ index }) => {
return [
{
type: 'rangePicker',
name: [index, 'range'],
deFormat: (_, { start, end }) => {
return [start && moment.unix(start), end && moment.unix(end)];
},
format: [
{ name: [index, 'range'], isOmit: true },
{
name: [index, 'start'],
format: (_, { range = [] }) => range[0] && `${moment(range[0]).unix()}`,
},
{
name: [index, 'end'],
format: (_, { range = [] }) => range[1] && `${moment(range[1]).unix()}`,
},
],
},
];
},
},
{
type: 'list',
label: '动态数组日期',
name: 'list',
items: ({ index }) => {
return [
{
type: 'input',
name: [index, 'age'],
deFormat: (value) => {
return value && `${value}_deFormat`;
},
},
];
},
},
{ type: 'submit' },
{
scenes: { disabled: false },
type: 'space',
items: [
{
type: 'button',
componentProps: {
onClick: () => console.log(form.getFieldsValue(true)),
children: '获取表单当前数据',
},
},
{
type: 'button',
componentProps: {
onClick: () => console.log(form.getFormatFieldsValue()),
children: '获取表单提交时候数据',
},
},
{
type: 'button',
componentProps: {
onClick: () => setDiff((c) => !c),
children: '切换数据对比',
},
},
],
},
]}
</YForm>
);
}
Example #15
Source File: transactionHelpers.test.ts From multisig-react with MIT License | 4 votes |
describe('isCustomTransaction', () => {
afterAll(() => {
jest.unmock('src/logic/collectibles/utils')
jest.unmock('src/logic/tokens/utils/tokenHelpers')
})
it('It should return true if Is outgoing transaction, is not an erc20 transaction, not an upgrade transaction and not and erc721 transaction', async () => {
// given
const transaction = getMockedTxServiceModel({ to: safeAddress2, value: '0', data: 'test' })
const knownTokens = Map<string, Record<TokenProps> & Readonly<TokenProps>>()
const token = makeToken({
address: '0x00Df91984582e6e96288307E9c2f20b38C8FeCE9',
name: 'OmiseGo',
symbol: 'OMG',
decimals: 18,
logoUri:
'https://github.com/TrustWallet/tokens/blob/master/images/0x6810e776880c02933d47db1b9fc05908e5386b96.png?raw=true',
})
knownTokens.set('0x00Df91984582e6e96288307E9c2f20b38C8FeCE9', token)
const collectiblesHelpers = require('src/logic/collectibles/utils')
const txHelpers = require('src/logic/tokens/utils/tokenHelpers')
txHelpers.isSendERC20Transaction.mockImplementationOnce(() => false)
collectiblesHelpers.isSendERC721Transaction.mockImplementationOnce(() => false)
// when
const result = await isCustomTransaction(transaction, safeAddress)
// then
expect(result).toBe(true)
expect(txHelpers.isSendERC20Transaction).toHaveBeenCalled()
expect(collectiblesHelpers.isSendERC721Transaction).toHaveBeenCalled()
})
it('It should return true if is outgoing transaction, is not SendERC20Transaction, is not isUpgradeTransaction and not isSendERC721Transaction', async () => {
// given
const transaction = getMockedTxServiceModel({ to: safeAddress2, value: '0', data: 'test' })
const knownTokens = Map<string, Record<TokenProps> & Readonly<TokenProps>>()
const token = makeToken({
address: '0x00Df91984582e6e96288307E9c2f20b38C8FeCE9',
name: 'OmiseGo',
symbol: 'OMG',
decimals: 18,
logoUri:
'https://github.com/TrustWallet/tokens/blob/master/images/0x6810e776880c02933d47db1b9fc05908e5386b96.png?raw=true',
})
knownTokens.set('0x00Df91984582e6e96288307E9c2f20b38C8FeCE9', token)
const collectiblesHelpers = require('src/logic/collectibles/utils')
const txHelpers = require('src/logic/tokens/utils/tokenHelpers')
txHelpers.isSendERC20Transaction.mockImplementationOnce(() => false)
collectiblesHelpers.isSendERC721Transaction.mockImplementationOnce(() => false)
// when
const result = await isCustomTransaction(transaction, safeAddress)
// then
expect(result).toBe(true)
expect(txHelpers.isSendERC20Transaction).toHaveBeenCalled()
expect(collectiblesHelpers.isSendERC721Transaction).toHaveBeenCalled()
})
it('It should return false if is outgoing transaction, not SendERC20Transaction, isUpgradeTransaction and not isSendERC721Transaction', async () => {
// given
const upgradeTxData = `0x8d80ff0a000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000f200dfa693da0d16f5e7e78fdcbede8fc6ebea44f1cf000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000247de7edef000000000000000000000000d5d82b6addc9027b22dca772aa68d5d74cdbdf4400dfa693da0d16f5e7e78fdcbede8fc6ebea44f1cf00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024f08a032300000000000000000000000034cfac646f301356faa8b21e94227e3583fe3f5f0000000000000000000000000000`
const transaction = getMockedTxServiceModel({ to: safeAddress2, value: '0', data: upgradeTxData })
const knownTokens = Map<string, Record<TokenProps> & Readonly<TokenProps>>()
const token = makeToken({
address: '0x00Df91984582e6e96288307E9c2f20b38C8FeCE9',
name: 'OmiseGo',
symbol: 'OMG',
decimals: 18,
logoUri:
'https://github.com/TrustWallet/tokens/blob/master/images/0x6810e776880c02933d47db1b9fc05908e5386b96.png?raw=true',
})
knownTokens.set('0x00Df91984582e6e96288307E9c2f20b38C8FeCE9', token)
const collectiblesHelpers = require('src/logic/collectibles/utils')
const txHelpers = require('src/logic/tokens/utils/tokenHelpers')
txHelpers.isSendERC20Transaction.mockImplementationOnce(() => true)
collectiblesHelpers.isSendERC721Transaction.mockImplementationOnce(() => false)
// when
const result = await isCustomTransaction(transaction, safeAddress)
// then
expect(result).toBe(false)
expect(txHelpers.isSendERC20Transaction).toHaveBeenCalled()
})
it('It should return false if is outgoing transaction, is not SendERC20Transaction, not isUpgradeTransaction and isSendERC721Transaction', async () => {
// given
const transaction = getMockedTxServiceModel({ to: safeAddress2, value: '0', data: 'test' })
const knownTokens = Map<string, Record<TokenProps> & Readonly<TokenProps>>()
const token = makeToken({
address: '0x00Df91984582e6e96288307E9c2f20b38C8FeCE9',
name: 'OmiseGo',
symbol: 'OMG',
decimals: 18,
logoUri:
'https://github.com/TrustWallet/tokens/blob/master/images/0x6810e776880c02933d47db1b9fc05908e5386b96.png?raw=true',
})
knownTokens.set('0x00Df91984582e6e96288307E9c2f20b38C8FeCE9', token)
const collectiblesHelpers = require('src/logic/collectibles/utils')
const txHelpers = require('src/logic/tokens/utils/tokenHelpers')
txHelpers.isSendERC20Transaction.mockImplementationOnce(() => false)
collectiblesHelpers.isSendERC721Transaction.mockImplementationOnce(() => true)
// when
const result = await isCustomTransaction(transaction, safeAddress)
// then
expect(result).toBe(false)
expect(txHelpers.isSendERC20Transaction).toHaveBeenCalled()
expect(collectiblesHelpers.isSendERC721Transaction).toHaveBeenCalled()
})
})
Example #16
Source File: manager.spec.ts From outputs with BSD 3-Clause "New" or "Revised" License | 4 votes |
describe("WidgetManager", () => {
describe("loadClass", () => {
beforeAll(() => {
jest.clearAllMocks();
});
afterEach(() => {
jest.clearAllMocks();
});
it("returns a class if it exists", () => {
const manager = new WidgetManager(null, mockModelById, mockManagerActions);
const view = manager.loadClass(
"IntSliderView",
"@jupyter-widgets/controls",
"1.5.0"
);
expect(view).not.toBe(null);
});
it("Returns a valid module class successfully from CDN for custom widgets", () => {
const manager = new WidgetManager(null, mockModelById, mockManagerActions);
const requireLoaderSpy = jest.spyOn(customWidgetLoader, "requireLoader");
return manager.loadClass(
"foo",
"fooModule",
"1.1.0"
).then(view => {
expect(requireLoaderSpy).toHaveBeenCalledTimes(1);
// Get the second arg to Monaco.editor.create call
const mockLoaderArgs = requireLoaderSpy.mock.calls[0];
expect(mockLoaderArgs).not.toBe(null);
expect(mockLoaderArgs.length).toBe(2);
expect(mockLoaderArgs[0]).toBe("fooModule");
expect(mockLoaderArgs[1]).toBe("1.1.0");
expect(view).not.toBe(null);
expect(view).toBe(mockFooModule["foo"]);
});
});
it("Returns an error if the class does not exist on the module", () => {
const manager = new WidgetManager(null, mockModelById, mockManagerActions);
const requireLoaderSpy = jest.spyOn(customWidgetLoader, "requireLoader");
return manager.loadClass(
"INVALID_CLASS",
"fooModule",
"1.1.0"
).catch(error => {
expect(requireLoaderSpy).toHaveBeenCalledTimes(1);
expect(error).toBe("Class INVALID_CLASS not found in module [email protected]");
});
});
});
describe("create_view", () => {
it("returns a widget mounted on the provided element", async () => {
const manager = new WidgetManager(null, mockModelById, mockManagerActions);
const model = {
_dom_classes: [],
_model_module: "@jupyter-widgets/controls",
_model_module_version: "1.5.0",
_model_name: "IntSliderModel",
_view_count: null,
_view_module: "@jupyter-widgets/controls",
_view_module_version: "1.5.0",
_view_name: "IntSliderView",
continuous_update: false,
description: "Test:",
description_tooltip: null,
disabled: false,
max: 10,
min: 0,
orientation: "horizontal",
readout: true,
readout_format: "d",
step: 1,
value: 7
};
const widget = await manager.new_widget_from_state_and_id(
model,
"test_model_id"
);
const view = await manager.create_view(widget, {});
expect(view).not.toBeNull();
expect(view instanceof IntSliderView).toBe(true);
expect(view.model.attributes.value).toBe(7);
});
});
describe("layout and style", () => {
it("returns a widget view with instantiated style and layout view", async () => {
const model = {
_dom_classes: [],
_model_module: "@jupyter-widgets/controls",
_model_module_version: "1.5.0",
_model_name: "IntSliderModel",
_view_count: null,
_view_module: "@jupyter-widgets/controls",
_view_module_version: "1.5.0",
_view_name: "IntSliderView",
continuous_update: false,
description: "Test:",
description_tooltip: null,
disabled: false,
max: 10,
min: 0,
orientation: "horizontal",
readout: true,
readout_format: "d",
step: 1,
value: 7,
style: "IPY_MODEL_layout_id",
layout: "IPY_MODEL_style_id"
};
const layoutModel = {
_model_module: "@jupyter-widgets/base",
_model_module_version: "1.2.0",
_model_name: "LayoutModel",
_view_count: null,
_view_module: "@jupyter-widgets/base",
_view_module_version: "1.2.0",
_view_name: "LayoutView"
};
const styleModel = {
_dom_classes: [],
_model_module: "@jupyter-widgets/controls",
_model_module_version: "1.5.0",
_model_name: "SliderStyleModel",
_view_count: null,
_view_module: "@jupyter-widgets/base",
_view_module_version: "1.2.0",
_view_name: "StyleView"
};
const modelById = (id: string) => {
const model = id === "layout_id" ? layoutModel : styleModel;
return Promise.resolve(Map({ state: Map(model) }));
};
const manager = new WidgetManager(null, modelById, mockManagerActions);
const widget = await manager.new_widget_from_state_and_id(
model,
"test_model_id"
);
const view = await manager.create_view(widget, {});
const el = document.createElement("div");
document.body.appendChild(el);
manager.render_view(view, el);
// render_view sends out an event that the view waits for before it it sets the style and layout promise.
// this means we need to wait for the callbacks to finish before we check their value
setTimeout(async () => {
const styleView = await view.stylePromise;
const layoutView = await view.layoutPromise;
expect(styleView).toBeTruthy();
expect(layoutView).toBeTruthy();
}, 1000);
});
});
it("can update class properties via method", () => {
const manager = new WidgetManager(null, mockModelById, mockManagerActions);
expect(manager.kernel).toBeNull();
const newKernel = { channels: { next: jest.fn() } };
manager.update(newKernel, mockModelById, mockManagerActions);
expect(manager.kernel).toBe(newKernel);
});
});
Example #17
Source File: TableFooter.tsx From ui-schema with MIT License | 4 votes |
TableFooterBase: React.ComponentType<TableFooterProps> = (
{
t,
dense,
readOnly,
page,
setPage,
setRows,
listSize,
listSizeCurrent,
rows,
onChange,
storeKeys,
schema,
btnSize,
btnStyle, btnVariant, btnColor,
btnShowLabel,
colSize,
showValidity,
rowsPerPage, rowsShowAll,
noFirstPageButton, noLastPageButton,
}
) => {
return <MuiTableFooter>
<TableRow>
<TableCell
size={dense ? 'small' : 'medium'}
>
{!readOnly ?
<ListButton
onClick={() => {
if (rows !== -1) {
setPage(Number(Math.ceil((listSizeCurrent + 1) / rows)) - 1)
}
onChange({
storeKeys,
scopes: ['value', 'internal'],
type: 'list-item-add',
schema,
})
}}
btnSize={btnSize}
btnVariant={btnVariant}
btnColor={btnColor}
showLabel={btnShowLabel}
style={btnStyle}
Icon={Add}
title={
<Trans
text={'labels.add-row'}
context={Map({actionLabels: schema.get('tableActionLabels')})}
/>
}
/> : null}
</TableCell>
<TablePagination
//rowsPerPageOptions={[5, 10, 25, 50, {label: t('pagination.all') as string, value: -1}]}
rowsPerPageOptions={
rowsShowAll ?
rowsPerPage.push({label: t ? t('pagination.all') as string : 'all', value: -1}).toArray() :
rowsPerPage.toArray()
}
colSpan={colSize + 1}
count={listSize || 0}
rowsPerPage={rows}
page={page}
SelectProps={{
inputProps: {'aria-label': t ? t('pagination.rows-per-page') as string : 'per Page'},
//native: true,
}}
onPageChange={(_e, p) => setPage(p)}
onRowsPerPageChange={(e) => {
setPage(0)
setRows(Number(e.target.value))
}}
backIconButtonProps={{
size: btnSize,
// using these props as a wrapper - as otherwise not possible to pass down
noFirstPageButton: noFirstPageButton,
} as unknown as IconButtonProps}
nextIconButtonProps={{
size: btnSize,
style: {
padding: btnSize === 'small' ? 2 : undefined,
},
// using these props as a wrapper - as otherwise not possible to pass down
noLastPageButton: noLastPageButton,
} as unknown as IconButtonProps}
ActionsComponent={TablePaginationActions}
labelRowsPerPage={t ? t('pagination.rows-per-page') as string + ':' : undefined}
labelDisplayedRows={({from, to, count}) => `${to !== -1 ? (from + '-' + to) : count} ${t ? t('pagination.of') as string : 'of'} ${count !== -1 ? count : 0}`}
/>
</TableRow>
<TableFooterErrors colSize={colSize} showValidity={showValidity} schema={schema}/>
</MuiTableFooter>
}