Files
status-app/ui/app/AppLayouts/Wallet/views/AssetsDetailView.qml
T
Alex Jbanca 754276d853 perf(wallet): build the wallet section around what the user is waiting for
A wallet section activation built everything it would ever need before it
showed anything: both panels inline, both detail views, every row of two
lists synchronously, and a set of subtrees that exist for cases that almost
never occur. This reorders that around a single rule - build what is on
screen first, build the rest in the incubation controller's metered bites,
and build the rest of the rest only when something asks for it.

Lists fill preemptibly. A ListView refill is one uninterruptible call inside
the window's polish phase, and QQuickItemView creates visible delegates with
AsynchronousIfNested - so a list first laid out after its enclosing Loader is
already Ready builds every visible row synchronously. On a warm load that was
one 34.7ms GUI-thread block against a 3.2ms budget for the assets list, and
8.7-13.5ms of post-content polish across both lists. The assets and accounts
delegates become TokenDelegateShell and WalletAccountDelegateShell: an Item
carrying the row's geometry and its placeholder tiles, with the real row
behind a nested asynchronous Loader. The refill builds shells; the rows
incubate afterwards.

Row height is the shell's, not the content's. StatusListItem.implicitHeight
is Math.max(64, titleArea.height + 16), and both a token row and an account
row resolve to that 64px floor, which is what placeholderHeight is.
tst_TokenDelegateShell and tst_WalletAccountDelegateShell gate the two
staying equal, so a change that makes a row taller fails a test rather than
moving contentHeight and the scroll position mid-fill. Each placeholder
mirrors the skeleton the per-tab loader showed a moment earlier, so the two
loading states read as one handoff.

Subtrees built for the exceptional case are latched off. The token row's two
warning buttons, the asset detail's four chain-tag warning buttons, its
header community tag and its "Minted by" tile were all built unconditionally
and merely hidden. Each now sits behind the condition that used to drive
`visible`. AssetsDetailsHeader loses its `communityTag` alias, which existed
only so callers could reach in and set the tag's contents; it takes
communityName/communityImage and builds the tag itself.

The two detail views move behind async Loaders keyed on the stack index. The
token to show becomes state held in `d` and bound into the view rather than
assigned into it, so a second click landing mid-incubation wins without a
queue-and-replay; the resets that hung off onVisibleChanged hang off
onActiveChanged, which fires on the same edges.

Panels build in the order the user sees them. WalletLayout declared both
panels as plain object bindings, so activation built LeftTabView and the
centre StackView inline and the chrome's two PanelSwapGates could not fire
independently - they opened 5ms apart because both panel properties resolve
when WalletLayout completes. Each panel now sits behind its own async Loader
with its own readiness, the primary one first, and once a skeleton is on
screen with no panel switch running the primary panel is built synchronously:
the pacing exists to protect section-switch animations, and here the only
thing a synchronous block could stutter is the skeleton it replaces.

Wrapping the panels in Loaders exposed three geometry defects. A Loader
reports its item's implicit size as its own, so the centre StackView's
content width propagated into the chrome and pushed the panel past the right
edge on a narrow screen; the loaders are bound to the chrome's geometry for
the unparented phase, the stack no longer anchors to its loader, and the side
inset moves onto the content where it belongs.

Panel geometry is coalesced across a rotation. A device rotation walks the
window through nine sizes over ~430ms and LayoutItemProxy forwarded every one
to the section's panels - a full relayout of a populated subtree each time -
and parked a panel at a degenerate box for ~148ms on the portrait/landscape
handoff. SectionPanelSlot replaces the panel proxies in both sub-layouts and
publishes the box each slot will give its panel, which is also what a section
building panels outside the tree needs: the centre slot cannot be guessed, as
it is short by the header and footer and narrow by the left column in
landscape. Wallet and chat both pre-size their incubating panels to it.

Two fixes fall out of that work. BaseProxyPanel looked its SwipeView page up
at a fixed implicitIndex, but SwipeView indices close up as pages come and
go, so hiding the right panel with no left panel present silently left its
page in the view, still swipeable; it now looks the page up by identity.
SectionPanelSlot also has to be listed in statusq.qrc - without it the type
is absent from the binary's resources, StatusSectionLayout becomes
unavailable and the UI process dies precompiling AppMain.

Measured on a whale profile, Release, arms alternated between rounds:

  warm t_first_asset_row       119-159ms -> 51-74ms
  warm max_stall_ms             31.7-42.6 -> 17.2-26.3ms
  section ready                     631ms -> 207ms
  visible panel promoted            609ms -> 338ms
  cold: skeleton shown -> visible  2272ms -> 1836ms
  objects_total (cold)               4602 -> 3344   (-27%)
  objects_settled                    9569 -> 8297   (-13%)
  token row QObjects                  326 -> 279
  panel geometry distinct sizes    24 -> 5 centre, 19 -> 2 left
  degenerate 0x0 box written    12 occurrences -> 0

Device numbers are only comparable once the app has settled; a run taken
while startup backend work is still in flight measured 925ms for a path that
measures ~520ms settled.

Measurements come from an offscreen storybook wallet bench that is not part
of this PR; see branch `feat/storybook-wallet-loader`.
2026-08-23 09:40:36 +03:00

578 lines
27 KiB
QML

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.Window
import StatusQ
import StatusQ.Components
import StatusQ.Core.Theme
import StatusQ.Core.Utils as SQUtils
import StatusQ.Core
import StatusQ.Controls
import utils
import shared.views
import shared.controls
import shared.stores as SharedStores
import AppLayouts.Wallet.helpers
import AppLayouts.Wallet.stores as WalletStores
import QtModelsToolkit
import SortFilterProxyModel
import "../controls"
/// \beware: heavy shortcuts here, refactor to match the requirements when touching this again
/// \todo split into token history and balance views; they have different requirements that introduce unnecessary complexity
/// \todo take a declarative approach, move logic into the typed backend and remove multiple source of truth (e.g. time ranges)
Item {
id: root
property var tokenGroup: ({})
property WalletStores.TokensStore tokensStore
property SharedStores.CurrenciesStore currencyStore
property SharedStores.NetworkConnectionStore networkConnectionStore
property var allNetworksModel
property var networkFilters
onNetworkFiltersChanged: d.forceRefreshBalanceStore = true
/*required*/ property string address: ""
TokenMarketValuesData {
id: marketValueData
}
// Clear stale price history whenever the displayed token changes so we never
// show data from the previous token while waiting for new responses.
onTokenGroupChanged: {
marketValueData.clear()
d.fetchedRanges = ({})
Qt.callLater(() => d.fetchRangeIfNeeded(ChartDataBase.TimeRange.All))
}
QtObject {
id: d
readonly property string symbol: !!root.tokenGroup? root.tokenGroup.symbol?? "" : ""
property bool marketDetailsLoading: !!root.tokenGroup? root.tokenGroup.marketDetailsLoading?? false : false
property bool tokenDetailsLoading: !!root.tokenGroup? root.tokenGroup.detailsLoading?? false: false
property bool isCommunityAsset: !!root.tokenGroup && !!tokenGroup.communityId
// Cache. Cleared on every tokenGroup change to avoid serving stale cached ranges.
property var fetchedRanges: ({})
function fetchRangeIfNeeded(range) {
const key = d.historicalDataTokenKey
if (!key || d.fetchedRanges[range])
return
d.fetchedRanges = Object.assign({}, d.fetchedRanges, {[range]: true})
root.tokensStore.getHistoricalDataForTokenByRange(key, root.currencyStore.currentCurrency, range)
}
// The key used when requesting historical data from the backend
readonly property string historicalDataTokenKey: {
if (!root.tokenGroup || !root.tokenGroup.tokens)
return ""
const ethereumToken = SQUtils.ModelUtils.getByKey(root.tokenGroup.tokens, "chainId", Constants.chains.mainnetChainId)
if (ethereumToken && ethereumToken.key)
return ethereumToken.key
const first = SQUtils.ModelUtils.get(root.tokenGroup.tokens, 0)
return first ? first.key ?? "" : ""
}
readonly property LeftJoinModel addressPerChainModel: LeftJoinModel {
leftModel: tokenGroup && tokenGroup.tokens ? tokenGroup.tokens: null
rightModel: root.allNetworksModel
joinRole: "chainId"
}
property bool forceRefreshBalanceStore: false
readonly property var splitAddresses: root.networkFilters.split(":")
readonly property SortFilterProxyModel enabledNetworksModel: SortFilterProxyModel {
sourceModel: root.allNetworksModel
filters: ValueFilter {
roleName: "isEnabled"
value: true
}
}
}
Connections {
target: walletSectionAllTokens
function onTokenHistoricalDataReady(tokenDetails: string) {
let response = JSON.parse(tokenDetails)
if (response === null) {
console.debug("error parsing json message for tokenHistoricalDataReady")
return
}
const expectedKey = d.historicalDataTokenKey
// Discard responses for tokens other than the one currently displayed
if (expectedKey !== "" && response.tokenKey !== expectedKey) {
return
}
if (response.historicalData === null || response.historicalData <= 0) {
return
}
marketValueData.setTimeAndValueData(response.historicalData, response.range)
}
}
AssetsDetailsHeader {
id: tokenDetailsHeader
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
asset.name: {
if (!tokenGroup)
return ""
if (tokenGroup.logoUri)
return tokenGroup.logoUri
return Constants.tokenIcon(tokenGroup.symbol)
}
asset.isImage: true
primaryText: tokenGroup && tokenGroup.name ? tokenGroup.name : Constants.dummyText
secondaryText: tokenGroup ? tokenGroup.balanceText : Constants.dummyText
tertiaryText: {
if (!d.isCommunityAsset) {
let totalCurrencyBalance = tokenGroup ? tokenGroup.balance * tokenGroup.marketPrice : 0
return root.currencyStore.formatCurrencyAmount(totalCurrencyBalance, root.currencyStore.currentCurrency)
}
return ""
}
decimals: tokenGroup && tokenGroup.decimals ? tokenGroup.decimals : 4
balances: tokenGroup && tokenGroup.balances ? tokenGroup.balances: null
networksModel: d.enabledNetworksModel
isLoading: d.marketDetailsLoading || !!(tokenGroup && tokenGroup.balanceLoading)
address: root.address
errorTooltipText: tokenGroup && tokenGroup.balances ? networkConnectionStore.getBlockchainNetworkDownTextForToken(tokenGroup.balances): ""
formatBalance: function(balance){
return LocaleUtils.currencyAmountToLocaleString(root.currencyStore.getCurrencyAmount(balance, tokenGroup.key))
}
communityName: d.isCommunityAsset && tokenGroup.communityName ? tokenGroup.communityName : ""
communityImage: d.isCommunityAsset && tokenGroup.communityImage ? tokenGroup.communityImage : ""
}
enum GraphType {
Price = 0
}
StatusScrollView {
id: scrollView
anchors.top: tokenDetailsHeader.bottom
anchors.bottom: parent.bottom
anchors.topMargin: Theme.padding
width: parent.width
contentWidth: availableWidth
padding: 0
ColumnLayout {
width: scrollView.availableWidth
spacing: 40
Loader {
id: graphDetailLoader
Layout.fillWidth: true
Layout.preferredHeight: 290
active: root.visible
sourceComponent: StatusChartPanel {
id: graphDetail
property int selectedGraphType: AssetsDetailView.GraphType.Price
property TokenMarketValuesData selectedStore: marketValueData
function dataReady() {
return typeof selectedStore != "undefined"
}
function timeRangeSelected() {
return dataReady() && graphDetail.timeRangeTabBarIndex >= 0 && graphDetail.selectedTimeRange.length > 0
}
readonly property var labelsData: {
return timeRangeSelected()
? selectedStore.timeRange[graphDetail.timeRangeTabBarIndex][graphDetail.selectedTimeRange]
: []
}
readonly property var dataRange: {
return timeRangeSelected()
? selectedStore.dataRange[graphDetail.timeRangeTabBarIndex][graphDetail.selectedTimeRange]
: []
}
readonly property var maxTicksLimit: {
return timeRangeSelected() && typeof selectedStore.maxTicks != "undefined"
? selectedStore.maxTicks[graphDetail.timeRangeTabBarIndex][graphDetail.selectedTimeRange]
: 0
}
graphsModel: [
{text: qsTr("Price"), enabled: true, id: AssetsDetailView.GraphType.Price, visible: !d.isCommunityAsset},
]
defaultTimeRangeIndexShown: ChartDataBase.TimeRange.All
timeRangeModel: dataReady() && selectedStore.timeRangeTabsModel
onHeaderTabClicked: (privateIdentifier, isTimeRange) => {
if(!isTimeRange && graphDetail.selectedGraphType !== privateIdentifier) {
graphDetail.selectedGraphType = privateIdentifier
}
if(!isTimeRange) {
graphDetail.selectedStore = marketValueData
} else {
const rangeEnum = marketValueData.timeRangeStrToEnum(privateIdentifier)
if (rangeEnum !== undefined)
d.fetchRangeIfNeeded(rangeEnum)
}
chart.refresh()
}
chart.type: 'line'
chart.labels: root.tokensStore.marketHistoryIsLoading ? [] : graphDetail.labelsData
chart.datasets: {
return [{
xAxisId: 'x-axis-1',
yAxisId: 'y-axis-1',
backgroundColor: (Theme.palette.name === "dark") ? 'rgba(136, 176, 255, 0.2)' : 'rgba(67, 96, 223, 0.2)',
borderColor: (Theme.palette.name === "dark") ? 'rgba(136, 176, 255, 1)' : 'rgba(67, 96, 223, 1)',
borderWidth: graphDetail.selectedGraphType === AssetsDetailView.GraphType.Price ? 3 : 2,
pointRadius: 0,
data: root.tokensStore.marketHistoryIsLoading ? [] : graphDetail.dataRange,
parsing: false,
}]
}
chart.options: {
return {
maintainAspectRatio: false,
responsive: true,
animation: {
duration: 0
},
legend: {
display: false
},
elements: {
line: {
cubicInterpolationMode: 'monotone' // without it interpolation makes the line too curvy that can extend horizontally farther then data points
}
},
//TODO enable zoom
//zoom: {
// enabled: true,
// drag: true,
// speed: 0.1,
// threshold: 2
//},
//pan:{enabled:true,mode:'x'},
tooltips: {
intersect: false,
displayColors: false,
callbacks: {
label: function(tooltipItem, data) {
let label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
const value = root.currencyStore.formatCurrencyAmount(
tooltipItem.yLabel, root.currencyStore.currentCurrency)
return label + value
}
}
},
scales: {
xAxes: [{
id: 'x-axis-1',
position: 'bottom',
type: graphDetail.selectedGraphType === AssetsDetailView.GraphType.Price ? 'category' : 'time',
gridLines: {
drawOnChartArea: false,
drawBorder: false,
drawTicks: false,
},
ticks: {
fontSize: Theme.asideTextFontSize,
fontColor: (Theme.palette.name === "dark") ? '#909090' : '#939BA1',
padding: 16,
maxRotation: 0,
minRotation: 0,
maxTicksLimit: graphDetail.maxTicksLimit,
},
time: {
minUnit: 'day' // for '7days' timeframe, otherwise labels are '10PM', '10AM', '10PM', etc
}
}],
yAxes: [{
position: 'left',
id: 'y-axis-1',
gridLines: {
borderDash: [8, 4],
drawBorder: false,
drawTicks: false,
color: (Theme.palette.name === "dark") ? '#909090' : '#939BA1'
},
beforeDataLimits: (axis) => {
axis.paddingTop = 25;
axis.paddingBottom = 0;
},
afterDataLimits: (axis) => {
if (axis.min < 0)
axis.min = 0;
},
ticks: {
fontSize: Theme.asideTextFontSize,
fontColor: (Theme.palette.name === "dark") ? '#909090' : '#939BA1',
padding: 8,
callback: function(value, index, ticks) {
return LocaleUtils.numberToLocaleString(value)
},
}
}]
}
}
}
LoadingGraphView {
anchors.fill: chart
active: root.tokensStore.marketHistoryIsLoading
}
}
}
Flow {
id: infoFlow
Layout.fillWidth: true
visible: !d.isCommunityAsset
spacing: 5
InformationTile {
id: i1
objectName: "marketCapInformationTile"
primaryText: qsTr("Market Cap")
secondaryText: tokenGroup && tokenGroup.marketDetails && tokenGroup.marketDetails.marketCap
? LocaleUtils.currencyAmountToLocaleString(tokenGroup.marketDetails.marketCap)
: Constants.dummyText
isLoading: d.marketDetailsLoading
}
InformationTile {
id: i2
objectName: "dayLowInformationTile"
primaryText: qsTr("Day Low")
secondaryText: tokenGroup && tokenGroup.marketDetails && tokenGroup.marketDetails.lowDay
? LocaleUtils.currencyAmountToLocaleString(tokenGroup.marketDetails.lowDay)
: Constants.dummyText
isLoading: d.marketDetailsLoading
}
// Wrapper for adding extra space in the middle of the Flow
Item {
readonly property int centralSpacing:
Math.max(0, infoFlow.width
- i1.width - i2.width - i3.width - i4.width - i5.width - i6.width
- (infoFlow.children.length - 1) * infoFlow.spacing)
width: i3.width + centralSpacing
height: i3.height
InformationTile {
id: i3
objectName: "dayHighInformationTile"
primaryText: qsTr("Day High")
secondaryText: tokenGroup && tokenGroup.marketDetails && tokenGroup.marketDetails.highDay
? LocaleUtils.currencyAmountToLocaleString(tokenGroup.marketDetails.highDay)
: Constants.dummyText
isLoading: d.marketDetailsLoading
}
}
InformationTile {
id: i4
readonly property double changePctHour: tokenGroup && tokenGroup.marketDetails
? tokenGroup.marketDetails.changePctHour : 0
objectName: "hourInformationTile"
primaryText: qsTr("Hour")
secondaryText: "%1%".arg(LocaleUtils.numberToLocaleString(changePctHour, 2))
secondaryLabel.customColor: changePctHour === 0 ? Theme.palette.directColor1 :
changePctHour < 0 ? Theme.palette.dangerColor1 :
Theme.palette.successColor1
isLoading: d.marketDetailsLoading
}
InformationTile {
id: i5
readonly property double changePctDay: tokenGroup && tokenGroup.marketDetails
? tokenGroup.marketDetails.changePctDay : 0
primaryText: qsTr("Day")
objectName: "dayInformationTile"
secondaryText: "%1%".arg(LocaleUtils.numberToLocaleString(changePctDay, 2))
secondaryLabel.customColor: changePctDay === 0 ? Theme.palette.directColor1 :
changePctDay < 0 ? Theme.palette.dangerColor1 :
Theme.palette.successColor1
isLoading: d.marketDetailsLoading
}
InformationTile {
id: i6
readonly property double changePct24hour: tokenGroup && tokenGroup.marketDetails
? tokenGroup.marketDetails.changePct24hour : 0
primaryText: qsTr("24 Hours")
objectName: "24HoursInformationTile"
secondaryText: "%1%".arg(LocaleUtils.numberToLocaleString(changePct24hour, 2))
secondaryLabel.customColor: changePct24hour === 0 ? Theme.palette.directColor1 :
changePct24hour < 0 ? Theme.palette.dangerColor1 :
Theme.palette.successColor1
isLoading: d.marketDetailsLoading
}
}
Flow {
id: detailsFlow
readonly property int rightSideWidth: 272
readonly property bool isOverflowing: !tokenDescriptionText.text || detailsFlow.width - detailsFlow.rightSideWidth - tokenDescriptionText.width < 24
Layout.fillWidth: true
spacing: 24
StatusTextWithLoadingState {
id: tokenDescriptionText
width: Math.max(536 , scrollView.availableWidth - detailsFlow.rightSideWidth - 24)
font.pixelSize: Theme.primaryTextFontSize
lineHeight: 22
lineHeightMode: Text.FixedHeight
text: tokenGroup && tokenGroup.description ? tokenGroup.description : d.tokenDetailsLoading ? Constants.dummyText: ""
customColor: Theme.palette.directColor1
elide: Text.ElideRight
wrapMode: Text.Wrap
textFormat: Qt.RichText
loading: d.tokenDetailsLoading
visible: !!text
}
GridLayout {
columnSpacing: 10
rowSpacing: 10
flow: detailsFlow.isOverflowing && detailsFlow.width > 400 ? GridLayout.LeftToRight: GridLayout.TopToBottom
// Latched, not hidden: a community asset has no website block
// and a plain asset has no minted-by block, so one of the two
// was always built and never shown.
Loader {
Layout.alignment: Qt.AlignTop
Layout.preferredWidth: detailsFlow.isOverflowing ? -1 : detailsFlow.rightSideWidth
active: !d.isCommunityAsset && !!tokenGroup.websiteUrl
visible: active
sourceComponent: InformationTileAssetDetails {
primaryText: qsTr("Website")
content: InformationTag {
asset.name : "browser"
tagPrimaryLabel.text: SQUtils.Utils.stripHttpsAndwwwFromUrl(tokenGroup.websiteUrl)
visible: typeof tokenGroup != "undefined" && tokenGroup && tokenGroup.websiteUrl !== ""
customBackground: Component {
Rectangle {
color: Theme.palette.baseColor2
border.width: 1
border.color: "transparent"
radius: 36
}
}
StatusMouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: Global.requestOpenLink(tokenGroup.websiteUrl)
}
}
}
}
Loader {
Layout.alignment: Qt.AlignTop
Layout.preferredWidth: detailsFlow.isOverflowing ? -1 : detailsFlow.rightSideWidth
active: d.isCommunityAsset
visible: active
sourceComponent: InformationTileAssetDetails {
primaryText: qsTr("Minted by")
content: InformationTag {
tagPrimaryLabel.text: tokenGroup && tokenGroup.communityName ? tokenGroup.communityName : ""
asset.name: tokenGroup && tokenGroup.communityImage ? tokenGroup.communityImage : ""
asset.isImage: true
customBackground: Component {
Rectangle {
color: Theme.palette.baseColor2
border.width: 1
border.color: "transparent"
radius: 36
}
}
StatusMouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: Global.switchToCommunity(tokenGroup.communityId)
}
}
}
}
InformationTileAssetDetails {
Layout.alignment: Qt.AlignTop
Layout.preferredWidth: detailsFlow.isOverflowing ? -1 : detailsFlow.rightSideWidth
primaryText: qsTr("Contract")
content: GridLayout {
columnSpacing: 10
rowSpacing: 10
flow: GridLayout.TopToBottom
Repeater {
model: SortFilterProxyModel {
sourceModel: d.addressPerChainModel
filters: FastExpressionFilter {
expression: d.splitAddresses.includes(model.chainId+"")
expectedRoles: ["chainId"]
}
}
delegate: InformationTag {
hoverEnabled: true
asset.name: Assets.svg(model.iconUrl)
asset.isImage: true
tagPrimaryLabel.text: model.chainName
tagSecondaryLabel.text: SQUtils.Utils.elideAndFormatWalletAddress(model.address)
customBackground: Component {
Rectangle {
color: Theme.palette.baseColor2
radius: 36
}
}
rightComponent: CopyButton {
width: 20
height: 20
textToCopy: model.address
}
StatusToolTip {
text: qsTr("Copy contract address")
visible: parent.hovered
}
}
}
}
}
}
}
}
}
}