-
Notifications
You must be signed in to change notification settings - Fork 103
/
ProposalDetailsView.svelte
303 lines (280 loc) · 12.4 KB
/
ProposalDetailsView.svelte
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
<script lang="ts">
import {
Button,
KeyValueBox,
Pane,
ProposalDetailsButton,
ProposalQuestion,
ProposalStatusPill,
Text,
TextType,
TextHint,
MarkdownBlock,
} from '@ui'
import { ProposalInformationPane } from '@components'
import { onMount, onDestroy } from 'svelte'
import { VotingEventPayload, ParticipationEventType, TrackedParticipationOverview } from '@iota/wallet/out/types'
import { localize } from '@core/i18n'
import { openPopup } from '@auxiliary/popup/actions'
import { selectedAccount, selectedAccountIndex } from '@core/account/stores'
import { getVotingEvent } from '@contexts/governance/actions'
import { ABSTAIN_VOTE_VALUE } from '@contexts/governance/constants'
import { ProposalStatus } from '@contexts/governance/enums'
import {
hasPendingGovernanceTransaction,
selectedProposal,
updateParticipationOverview,
participationOverviewForSelectedAccount,
selectedParticipationEventStatus,
clearSelectedParticipationEventStatus,
} from '@contexts/governance/stores'
import {
calculateTotalVotesForTrackedParticipations,
getActiveParticipation,
isProposalVotable,
isVotingForSelectedProposal,
} from '@contexts/governance/utils'
import { getBestTimeDuration, milestoneToDate } from '@core/utils'
import { networkStatus } from '@core/network/stores'
import { formatTokenAmountBestMatch } from '@core/wallet/utils'
import { visibleSelectedAccountAssets } from '@core/wallet/stores'
import { handleError } from '@core/error/handlers'
import {
clearParticipationEventStatusPoll,
pollParticipationEventStatus,
} from '@contexts/governance/actions/pollParticipationEventStatus'
import { PopupId } from '@auxiliary/popup'
const { metadata } = $visibleSelectedAccountAssets?.baseCoin
let selectedAnswerValues: number[] = []
let votedAnswerValues: number[] = []
let votingPayload: VotingEventPayload
let totalVotes = 0
let hasMounted = false
let textHintString = ''
let proposalQuestions: HTMLElement
let isVotingForProposal: boolean = false
let statusLoaded: boolean = false
$: selectedProposalOverview = $participationOverviewForSelectedAccount?.participations?.[$selectedProposal?.id]
$: overviewLoaded = !!$participationOverviewForSelectedAccount
$: trackedParticipations = Object.values(selectedProposalOverview ?? {})
$: currentMilestone = $networkStatus.currentMilestone
// Reactively start updating votes once component has mounted and participation overview is available.
$: hasMounted &&
$selectedParticipationEventStatus &&
trackedParticipations &&
currentMilestone &&
setVotedAnswerValuesAndTotalVotes()
$: hasMounted && selectedProposalOverview && updateIsVoting()
$: questions = votingPayload?.questions
$: if (questions?.length > 0 && selectedAnswerValues?.length === 0) {
selectedAnswerValues = [
...(getActiveParticipation($selectedProposal?.id)?.answers ?? Array.from({ length: questions?.length })),
]
}
$: isVotingDisabled =
!isProposalVotable($selectedParticipationEventStatus?.status) ||
!hasChangedAnswers(selectedAnswerValues) ||
hasSelectedNoAnswers(selectedAnswerValues)
$: isTransferring = $hasPendingGovernanceTransaction?.[$selectedAccountIndex]
$: $selectedParticipationEventStatus, (textHintString = getTextHintString())
function hasSelectedNoAnswers(_selectedAnswerValues: number[]): boolean {
return (
_selectedAnswerValues.length === 0 ||
_selectedAnswerValues.every((answerValue) => answerValue === undefined)
)
}
function hasChangedAnswers(_selectedAnswerValues: number[]): boolean {
const activeParticipationAnswerValues = getActiveParticipation($selectedProposal?.id)?.answers
if (activeParticipationAnswerValues) {
/**
* NOTE: If any of the values between what's active and selected differ, it means
* that the user has changed at least one answer.
*/
return _selectedAnswerValues.some(
(selectedAnswerValue, idx) => selectedAnswerValue !== activeParticipationAnswerValues[idx]
)
} else {
/**
* NOTE: If the user hasn't voted for the participation yet, the user has not changed (all) answers
* yet until every value is not undefined.
*/
return _selectedAnswerValues.some((selectedAnswerValue) => selectedAnswerValue !== undefined)
}
}
async function setVotingEventPayload(eventId: string): Promise<void> {
const event = await getVotingEvent(eventId)
if (event) {
if (event.data?.payload?.type === ParticipationEventType.Voting) {
votingPayload = event.data.payload
} else {
throw new Error('Event is a staking event')
}
} else {
throw new Error('Event not found')
}
}
async function updateIsVoting(): Promise<void> {
try {
isVotingForProposal = await isVotingForSelectedProposal()
} catch (err) {
handleError(err)
}
}
function setVotedAnswerValuesAndTotalVotes(): void {
let lastActiveOverview: TrackedParticipationOverview
switch ($selectedParticipationEventStatus?.status) {
case ProposalStatus.Upcoming:
totalVotes = 0
break
case ProposalStatus.Commencing:
lastActiveOverview = trackedParticipations?.find((overview) => overview.endMilestoneIndex === 0)
totalVotes = 0
break
case ProposalStatus.Holding:
lastActiveOverview = trackedParticipations?.find((overview) => overview.endMilestoneIndex === 0)
totalVotes = calculateTotalVotesForTrackedParticipations(trackedParticipations)
break
case ProposalStatus.Ended:
lastActiveOverview = trackedParticipations?.find(
(overview) => overview.endMilestoneIndex > $selectedProposal.milestones.ended
)
totalVotes = calculateTotalVotesForTrackedParticipations(trackedParticipations)
break
}
votedAnswerValues = lastActiveOverview?.answers ?? []
}
let openedQuestionIndex = 0
function handleQuestionClick(event: CustomEvent): void {
const { questionIndex } = event.detail
openedQuestionIndex = questionIndex === openedQuestionIndex ? null : questionIndex
}
function onStopVotingClick(): void {
openPopup({
id: PopupId.StopVoting,
})
}
function onVoteClick(): void {
const chosenAnswerValues = selectedAnswerValues.map((answerValue) =>
answerValue === undefined ? ABSTAIN_VOTE_VALUE : answerValue
)
openPopup({
id: PopupId.VoteForProposal,
props: { selectedAnswerValues: chosenAnswerValues },
})
}
function handleAnswerClick(event: CustomEvent): void {
const { answerValue, questionIndex } = event.detail
selectedAnswerValues[questionIndex] = answerValue
openedQuestionIndex = questionIndex + 1
const selectedQuestionElement: HTMLElement = proposalQuestions?.querySelector(
`proposal-question:nth-child(${openedQuestionIndex})`
)
setTimeout(() => {
proposalQuestions.scrollTo({ top: selectedQuestionElement?.offsetTop, behavior: 'smooth' })
}, 250)
}
function getTextHintString(): string {
const millis =
milestoneToDate(
$networkStatus.currentMilestone,
$selectedProposal.milestones[ProposalStatus.Commencing]
).getTime() - new Date().getTime()
const timeString = getBestTimeDuration(millis, 'second')
return localize('views.governance.details.hintVote', { values: { time: timeString } })
}
onMount(async () => {
pollParticipationEventStatus($selectedProposal?.id).then(() => (statusLoaded = true))
// TODO: this api call gets all overviews, we need to change it so that we just get one
// We then need to update the latest overview manually if we perform an action
void updateParticipationOverview($selectedAccountIndex)
await setVotingEventPayload($selectedProposal?.id)
await updateIsVoting()
hasMounted = true
})
onDestroy(() => {
clearParticipationEventStatusPoll()
clearSelectedParticipationEventStatus()
})
</script>
<div class="w-full h-full flex flex-nowrap p-8 relative flex-1 space-x-4 bg-gray-50 dark:bg-gray-900">
<div class="w-2/5 flex flex-col space-y-4">
<Pane classes="p-6 flex flex-col h-fit">
<header-container class="flex justify-between items-center mb-4">
<ProposalStatusPill status={$selectedProposal?.status} />
<ProposalDetailsButton />
</header-container>
<div class="flex flex-1 flex-col justify-between">
<Text type={TextType.h2}>{$selectedProposal?.title}</Text>
<div class="mt-4 max-h-40 overflow-hidden">
{#if $selectedProposal?.additionalInfo}
<MarkdownBlock text={$selectedProposal?.additionalInfo} />
{/if}
</div>
</div>
</Pane>
<Pane classes="p-6 h-fit">
<Text smaller classes="mb-5">
{localize('views.governance.details.yourVote.title')}
</Text>
<ul class="space-y-2">
<li>
<KeyValueBox
keyText={localize('views.governance.details.yourVote.total')}
valueText={formatTokenAmountBestMatch(totalVotes, metadata)}
isLoading={!overviewLoaded}
/>
</li>
<li>
<KeyValueBox
keyText={localize('views.governance.details.yourVote.power')}
valueText={formatTokenAmountBestMatch(parseInt($selectedAccount?.votingPower), metadata)}
/>
</li>
</ul>
</Pane>
<ProposalInformationPane />
</div>
<Pane classes="w-3/5 h-full p-6 pr-3 flex flex-col justify-between">
<proposal-questions
class="relative flex flex-1 flex-col space-y-5 overflow-y-scroll pr-3"
bind:this={proposalQuestions}
>
{#if questions}
{#each questions as question, questionIndex}
<ProposalQuestion
{question}
{questionIndex}
isOpened={openedQuestionIndex === questionIndex}
selectedAnswerValue={selectedAnswerValues[questionIndex]}
votedAnswerValue={votedAnswerValues[questionIndex]}
answerStatuses={$selectedParticipationEventStatus?.questions?.[questionIndex]?.answers}
isLoading={!overviewLoaded || !statusLoaded}
on:clickQuestion={handleQuestionClick}
on:clickAnswer={handleAnswerClick}
/>
{/each}
{/if}
</proposal-questions>
{#if $selectedProposal?.status === ProposalStatus.Upcoming}
<TextHint info text={textHintString} />
{:else if [ProposalStatus.Commencing, ProposalStatus.Holding].includes($selectedParticipationEventStatus?.status)}
<buttons-container class="flex w-full space-x-4 mt-6">
<Button
outline
classes="w-full"
onClick={onStopVotingClick}
disabled={!isVotingForProposal || isTransferring}
isBusy={isVotingForProposal && isTransferring}>{localize('actions.stopVoting')}</Button
>
<Button
classes="w-full"
disabled={isVotingDisabled || isTransferring}
isBusy={isTransferring}
onClick={onVoteClick}
>
{localize('actions.vote')}
</Button>
</buttons-container>
{/if}
</Pane>
</div>