-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.tsx
More file actions
506 lines (450 loc) · 18 KB
/
Copy pathindex.tsx
File metadata and controls
506 lines (450 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// Copyright 2017-2022 @polkadot/apps, UseTech authors & contributors
// SPDX-License-Identifier: Apache-2.0
import './styles.scss';
import type { AttributeItemType, ProtobufAttributeType } from '@polkadot/react-components/util/protobufUtils';
import _maxBy from 'lodash/maxBy';
import React, { memo, ReactElement, useCallback, useContext, useEffect, useState } from 'react';
import { useHistory } from 'react-router';
import Confirm from 'semantic-ui-react/dist/commonjs/addons/Confirm';
import { CollectionFormContext, defaultAttributesWithTokenIpfs } from '@polkadot/app-builder/CollectionFormContext';
import { useCollectionFees } from '@polkadot/app-builder/hooks';
import TransactionContext from '@polkadot/app-builder/TransactionContext/TransactionContext';
import { Checkbox, HelpTooltip, Input, UnqButton } from '@polkadot/react-components';
import { fillAttributes, fillProtobufJson } from '@polkadot/react-components/util/protobufUtils';
import { useCollection, useIsMountedRef } from '@polkadot/react-hooks';
import { CreateCollectionEx, NftCollectionInterface } from '@polkadot/react-hooks/useCollection';
import { str2vec } from '@polkadot/react-hooks/utils';
import expanderIcon from '../../images/expanderIcon.svg';
import plusIcon from '../../images/plusIcon.svg';
import AttributesRowEditable, { ArtificialAttributeItemType, ArtificialFieldRuleType, ArtificialFieldType } from '../TokenAttributes/AttributesRowEditable';
import WarningText from '../WarningText';
import AttributesRow from './AttributesRow';
interface TokenAttributes {
account: string;
collectionId?: string;
collectionInfo?: NftCollectionInterface;
}
const stepTexts = [
'Setting collection traits',
'Setting image location'
];
const creatingCollectionText = 'Creating collection';
const maxTokenLimit = 4294967295;
function TokenAttributes ({ account, collectionId, collectionInfo }: TokenAttributes): ReactElement {
const { createCollectionEx, getCollectionOnChainSchema, setCollectionProperties } = useCollection();
const [isSaveConfirmationOpen, setIsSaveConfirmationOpen] = useState<boolean>(false);
const [formErrors, setFormErrors] = useState<number[]>([]);
const [emptyEnums, setEmptyEnums] = useState<number[]>([]);
const [opened, setOpened] = useState(false);
const history = useHistory();
const { calculateFeeEx, calculatePropertiesFee, fees } = useCollectionFees(account, collectionId);
const isOwner = collectionInfo?.owner === account;
const canSaveAttributes = isOwner || !collectionId;
const { setTransactions } = useContext(TransactionContext);
const { attributes, description, imgAddress, name, ownerCanDestroy, ownerCanTransfer, setAttributes, setOwnerCanDestroy, setTokenLimit, tokenLimit, tokenPrefix } = useContext(CollectionFormContext);
const mountedRef = useIsMountedRef();
const onAddItem = useCallback(() => {
const newAttributes = [...attributes];
const findNextId = (_maxBy(newAttributes, 'id') as AttributeItemType)?.id ?? 0;
newAttributes.push({
fieldType: 'string',
id: findNextId + 1,
name: `attribute${findNextId}`,
rule: 'required',
values: []
});
mountedRef.current && setAttributes(newAttributes);
}, [attributes, mountedRef, setAttributes]);
const closeSaveConfirmation = useCallback(() => {
setIsSaveConfirmationOpen(false);
}, []);
const getCollectionPropertyValueByKey = useCallback((key: string) => {
return collectionInfo?.properties.find((property) => property.key === key)?.value;
}, [collectionInfo?.properties]);
const onSuccess = useCallback(() => {
if (collectionId) {
const transactions = [
{
state: 'finished',
text: stepTexts[0]
}
];
if (getCollectionPropertyValueByKey('_old_schemaVersion') !== 'Unique') {
transactions.push({
state: 'finished',
text: stepTexts[1]
});
}
mountedRef.current && setTransactions(transactions);
} else {
mountedRef.current && setTransactions([
{
state: 'finished',
text: creatingCollectionText
}
]);
}
setTimeout(() => {
mountedRef.current && setTransactions([]);
history.push('/builder');
}, 3000);
}, [collectionId, getCollectionPropertyValueByKey, mountedRef, setTransactions, history]);
const convertArtificialAttributesToProtobuf = useCallback((attributes: ArtificialAttributeItemType[]): AttributeItemType[] => {
return attributes.map((attr: ArtificialAttributeItemType): AttributeItemType => {
if (attr.fieldType === 'repeated') {
return { ...attr, fieldType: 'enum', rule: 'repeated' };
}
return { ...attr } as AttributeItemType;
});
}, []);
const convertProtobufToArtificialAttributes = useCallback((attributes: AttributeItemType[]): ArtificialAttributeItemType[] => {
return attributes.map((attr: AttributeItemType): ArtificialAttributeItemType => {
/*
type: 'string' | 'enum' -> 'string' | 'enum' | 'repeated';
rule: 'optional' | 'required' | 'repeated' -> 'optional' | 'required';
*/
if (attr.rule === 'repeated') {
return { ...attr, fieldType: 'repeated', rule: 'optional' };
}
return attr as ArtificialAttributeItemType;
});
}, []);
const onSaveForm = useCallback(() => {
setIsSaveConfirmationOpen(false);
try {
const converted: AttributeItemType[] = convertArtificialAttributesToProtobuf(attributes);
const protobufJson: ProtobufAttributeType = fillProtobufJson(converted);
if (account) {
if (collectionId) {
const transactions = [
{
state: 'active',
text: stepTexts[0]
}
];
if (getCollectionPropertyValueByKey('_old_schemaVersion') !== 'Unique') {
transactions.push({
state: 'not-active',
text: stepTexts[1]
});
}
setTransactions(transactions);
setCollectionProperties({
account,
collectionId,
properties: [
...collectionInfo?.properties ?? [],
{ key: '_old_schemaVersion', value: 'Unique' }
]
});
} else {
setTransactions([
{
state: 'active',
text: creatingCollectionText
}
]);
const collectionData: CreateCollectionEx = {
account,
description: str2vec(description),
limits: {
ownerCanDestroy,
ownerCanTransfer,
tokenLimit
},
mode: { nft: null },
name: str2vec(name),
permissions: {
access: 'Normal',
mintMode: false,
nesting: {
owner: null
}
},
properties: [
{ key: '_old_offchainSchema', value: '' },
{ key: '_old_schemaVersion', value: 'Unique' },
{ key: '_old_variableOnChainSchema', value: JSON.stringify({ collectionCover: imgAddress ?? null }) },
{ key: '_old_constOnChainSchema', value: JSON.stringify(protobufJson) }
],
tokenPrefix: str2vec(tokenPrefix),
tokenPropertyPermissions: [
{
key: '_old_constData', permission: { collectionAdmin: true, mutable: false, tokenOwner: false }
}
]
};
createCollectionEx({
...collectionData
}, {
onFailed: (result) => {
console.log('Collection creation failed', result);
setTransactions([]);
},
onSuccess
});
}
}
} catch (e) {
console.log('save onChain schema error', e);
}
}, [convertArtificialAttributesToProtobuf, attributes, account, collectionId, getCollectionPropertyValueByKey, setTransactions, setCollectionProperties, collectionInfo?.properties, description, ownerCanDestroy, ownerCanTransfer, tokenLimit, name, imgAddress, tokenPrefix, createCollectionEx, onSuccess]);
const deleteAttribute = useCallback((id: number) => {
setAttributes(attributes.filter((attribute: ArtificialAttributeItemType) => attribute.id !== id));
}, [attributes, setAttributes]);
const onSaveAll = useCallback(() => {
// user didn't fill attributes, we have only default ipfsJson attribute
if (attributes.length === 1) {
setIsSaveConfirmationOpen(true);
} else {
onSaveForm();
}
}, [attributes, onSaveForm]);
const setAttributeCountType = useCallback((countType: ArtificialFieldRuleType, id: number) => {
setAttributes((prevAttributes: ArtificialAttributeItemType[]) => prevAttributes.map((item) => item.id === id ? { ...item, rule: countType } : item));
}, [setAttributes]);
const setAttributeName = useCallback((name: string, id: number) => {
setAttributes((prevAttributes: ArtificialAttributeItemType[]) => prevAttributes.map((item) => item.id === id ? { ...item, name } : item));
}, [setAttributes]);
const setAttributeType = useCallback((type: ArtificialFieldType, id: number) => {
setAttributes((prevAttributes: ArtificialAttributeItemType[]) => prevAttributes.map((item) => item.id === id ? { ...item, fieldType: type } : item));
}, [setAttributes]);
const setAttributeValues = useCallback((values: string[], id: number) => {
setAttributes((prevAttributes: ArtificialAttributeItemType[]) => prevAttributes.map((item) => item.id === id ? { ...item, values: values } : item));
}, [setAttributes]);
const fillCollectionAttributes = useCallback(() => {
if (collectionInfo?.properties) {
const onChainSchema = getCollectionOnChainSchema(collectionInfo);
let previousAttributes: AttributeItemType[] = [];
let converted: ArtificialAttributeItemType[] = [];
if (onChainSchema) {
const { constSchema } = onChainSchema;
if (constSchema) {
previousAttributes = fillAttributes(constSchema);
}
}
if (previousAttributes.find((attr) => attr.name === 'ipfsJson')) {
converted = convertProtobufToArtificialAttributes(previousAttributes);
setAttributes(converted);
} else {
setAttributes([...converted, ...defaultAttributesWithTokenIpfs]);
}
} else {
setAttributes([...defaultAttributesWithTokenIpfs]);
}
}, [collectionInfo, convertProtobufToArtificialAttributes, getCollectionOnChainSchema, setAttributes]);
const toggleAdvanced = useCallback(() => {
mountedRef.current && setOpened((prevOpen) => !prevOpen);
}, [mountedRef]);
const onLimitKeyDown = useCallback((event: React.KeyboardEvent) => {
((event.key === ',' || event.key === '.') && tokenLimit > 0) && event.preventDefault();
['e', 'E', '+', '-'].includes(event.key) && event.preventDefault();
}, [tokenLimit]);
const onLimitChange = useCallback((value: string) => {
if (!value) {
setTokenLimit(0);
return;
}
const numVal = Number(value);
if (numVal > maxTokenLimit || numVal < 0) {
return;
}
setTokenLimit(numVal);
}, [setTokenLimit]);
useEffect(() => {
fillCollectionAttributes();
}, [fillCollectionAttributes]);
useEffect(() => {
if (collectionId) {
void calculatePropertiesFee();
} else {
void calculateFeeEx();
}
}, [calculateFeeEx, calculatePropertiesFee, collectionId]);
// if we have no collection name filled, lets fill in in
useEffect(() => {
if (!collectionId && !name) {
history.push('/builder/new-collection/main-information');
}
}, [collectionId, history, name]);
return (
<div className='token-attributes shadow-block'>
<div className='token-attributes-header'>
<p className='header-title'>Token attributes</p>
<p className='header-text'>This functionality allows you to customize the token. You can set any traits that will help you create unique NFT: name, accessory, gender, background, face, body, tier etc.</p>
</div>
<div className='attributes-title'>
<div className='row-title'>
<p>Attribute</p>
<HelpTooltip
className={'help attributes'}
content={<span>Textual traits that show up on Token</span>}
defaultPosition={'bottom left'}
/>
</div>
<div className='row-title'>
<p>Type</p>
<HelpTooltip
className={'help attributes'}
content={<span>Select type of information you want to create</span>}
defaultPosition={'bottom left'}
/>
</div>
<div className='row-title'>
<p>Rule</p>
<HelpTooltip
className={'help attributes'}
content={<span>Set a rule for your attribute</span>}
defaultPosition={'bottom left'}
/>
</div>
<div className='row-title'>
<p>Possible values</p>
<HelpTooltip
className={'help attributes'}
content={<span>Write down all the options you have </span>}
defaultPosition={'bottom left'}
/>
</div>
</div>
{ !canSaveAttributes && attributes.map((attribute: ArtificialAttributeItemType, index: number) => {
if (attribute.name !== 'ipfsJson') {
return (
<AttributesRow
attributeCountType={attribute.rule}
attributeName={attribute.name}
attributeType={attribute.fieldType}
attributeValues={attribute.values}
key={`${attribute.name}-${index}`}
/>
);
} else {
return null;
}
})}
{ canSaveAttributes && attributes.map((attribute: ArtificialAttributeItemType) => {
if (attribute.name !== 'ipfsJson') {
return (
<AttributesRowEditable
attributeCountType={attribute.rule}
attributeName={attribute.name}
attributeType={attribute.fieldType}
attributeValues={attribute.values}
attributes={attributes}
canSaveAttributes={canSaveAttributes}
formErrors={formErrors}
id={attribute.id}
key={`${attribute.id}`}
removeItem={deleteAttribute}
setAttributeCountType={setAttributeCountType}
setAttributeName={setAttributeName}
setAttributeType={setAttributeType}
setAttributeValues={setAttributeValues}
setEmptyEnums={setEmptyEnums}
setFormErrors={setFormErrors}
/>
);
} else {
return null;
}
})}
<UnqButton
className='add-field '
onClick={onAddItem}
size='medium'
>
Add field
<img
alt='plus'
src={plusIcon as string}
/>
</UnqButton>
{ !collectionId && (
<div className='custom-expander'>
<div
className='custom-expander--header'
onClick={toggleAdvanced}
>
<span>Advanced settings</span>
<img
alt='expander'
className={opened ? 'expanded' : ''}
src={expanderIcon as string}
>
</img>
</div>
{ opened && (
<div className='custom-expander--inner'>
<span>These settings are intended for users who want to place their collection on the marketplace. Take note: once set, these parameters cannot be modified later on.</span>
<form>
<div className='form-item'>
<div className='form-item--with-tooltip'>
<Checkbox
label='Owner can destroy collection'
onChange={setOwnerCanDestroy}
value={ownerCanDestroy}
/>
<HelpTooltip
className={'help'}
content={
<span>
Should you decide to keep the right to destroy the collection, a marketplace could reject it depending on its policies as it gives the author the power to arbitrarily destroy a collection at any moment in the future
</span>
}
/>
</div>
</div>
<div className='form-item'>
<div className='form-item--with-tooltip'>
Token limit
<HelpTooltip
className={'help'}
content={
<span>
The token limit (collection size) is a mandatory parameter if you want to list your collection on a marketplace.
</span>
}
/>
</div>
<br />
<Input
className='isSmall'
max={maxTokenLimit}
onChange={onLimitChange}
onKeyDown={onLimitKeyDown}
placeholder='Token limit'
type='number'
value={tokenLimit?.toString()}
/>
</div>
</form>
</div>
)}
</div>
)}
{ fees && (
<WarningText fee={fees} />
)}
<div className='attributes-button'>
<Confirm
cancelButton='No, return'
className='unique-modal'
confirmButton='Yes, I am sure'
content='You cannot return to editing the attributes in this product version.'
header='You have not entered attributes. Are you sure that you want to create the collection without them?'
onCancel={closeSaveConfirmation}
onConfirm={onSaveForm}
open={isSaveConfirmationOpen}
/>
<UnqButton
content='Confirm'
isDisabled={formErrors?.length > 0 || emptyEnums?.length > 0 || tokenLimit === 0}
isFilled
onClick={onSaveAll}
size='medium'
/>
</div>
</div>
);
}
export default memo(TokenAttributes);