diff --git a/apps/block_scout_web/assets/js/lib/history_chart.js b/apps/block_scout_web/assets/js/lib/history_chart.js index fcaa3aa421..f1463cf096 100644 --- a/apps/block_scout_web/assets/js/lib/history_chart.js +++ b/apps/block_scout_web/assets/js/lib/history_chart.js @@ -4,7 +4,6 @@ import humps from 'humps' import numeral from 'numeral' import { formatUsdValue } from '../lib/currency' import sassVariables from '../../css/app.scss' -import { showLoader } from '../lib/utils' const config = { type: 'line', @@ -104,25 +103,13 @@ function getMarketCapData (marketHistoryData, availableSupply) { } } -// colors for light and dark theme -var priceLineColor -var mcapLineColor -if (localStorage.getItem('current-color-mode') === 'dark') { - priceLineColor = sassVariables.darkprimary - mcapLineColor = sassVariables.darksecondary -} else { - priceLineColor = sassVariables.dashboardLineColorPrice - mcapLineColor = sassVariables.dashboardLineColorMarket -} - class MarketHistoryChart { constructor (el, availableSupply, marketHistoryData, dataConfig) { - - var axes = config.options.scales.yAxes.reduce(function(solution, elem){ + var axes = config.options.scales.yAxes.reduce(function (solution, elem) { solution[elem.id] = elem return solution }, - {}) + {}) this.price = { label: window.localized['Price'], @@ -130,13 +117,13 @@ class MarketHistoryChart { data: [], fill: false, pointRadius: 0, - backgroundColor: priceLineColor, - borderColor: priceLineColor, + backgroundColor: sassVariables.dashboardLineColorPrice, + borderColor: sassVariables.dashboardLineColorPrice, lineTension: 0 } - if (dataConfig.market == undefined || dataConfig.market.indexOf("price") == -1){ + if (dataConfig.market === undefined || dataConfig.market.indexOf('price') === -1) { this.price.hidden = true - axes["price"].display = false + axes['price'].display = false } this.marketCap = { @@ -145,13 +132,13 @@ class MarketHistoryChart { data: [], fill: false, pointRadius: 0, - backgroundColor: mcapLineColor, - borderColor: mcapLineColor, + backgroundColor: sassVariables.dashboardLineColorMarket, + borderColor: sassVariables.dashboardLineColorMarket, lineTension: 0 } - if (dataConfig.market == undefined || dataConfig.market.indexOf("market_cap") == -1){ + if (dataConfig.market === undefined || dataConfig.market.indexOf('market_cap') === -1) { this.marketCap.hidden = true - axes["marketCap"].display = false + axes['marketCap'].display = false } this.numTransactions = { @@ -162,15 +149,14 @@ class MarketHistoryChart { pointRadius: 0, backgroundColor: sassVariables.dashboardLineColorMarket, borderColor: sassVariables.dashboardLineColorTransactions, - lineTension: 0, + lineTension: 0 } - if (dataConfig.transactions == undefined || dataConfig.transactions.indexOf("transactions_per_day") == -1){ + if (dataConfig.transactions === undefined || dataConfig.transactions.indexOf('transactions_per_day') === -1) { this.numTransactions.hidden = true - axes["numTransactions"].display = false + axes['numTransactions'].display = false } this.availableSupply = availableSupply - //TODO: This is where we dynamically append datasets config.data.datasets = [this.price, this.marketCap, this.numTransactions] this.chart = new Chart(el, config) } @@ -185,9 +171,9 @@ class MarketHistoryChart { } this.chart.update() } - updateTransactionHistory (transaction_history) { - this.numTransactions.data = transaction_history.map(dataPoint => { - return {x:dataPoint.date, y:dataPoint.number_of_transactions} + updateTransactionHistory (transactionHistory) { + this.numTransactions.data = transactionHistory.map(dataPoint => { + return {x: dataPoint.date, y: dataPoint.number_of_transactions} }) this.chart.update() } @@ -198,28 +184,24 @@ export function createMarketHistoryChart (el) { const dataConfig = $(el).data('history_chart_config') const $chartLoading = $('[data-chart-loading-message]') - - const isTimeout = true - const timeoutID = showLoader(isTimeout, $chartLoading) - const $chartError = $('[data-chart-error-message]') const chart = new MarketHistoryChart(el, 0, [], dataConfig) - Object.keys(dataPaths).forEach(function(history_source){ - $.getJSON(dataPaths[history_source], {type: 'JSON'}) + Object.keys(dataPaths).forEach(function (historySource) { + $.getJSON(dataPaths[historySource], {type: 'JSON'}) .done(data => { - switch(history_source){ - case "market": - const availableSupply = JSON.parse(data.supply_data) - const marketHistoryData = humps.camelizeKeys(JSON.parse(data.history_data)) - $(el).show() - chart.updateMarketHistory(availableSupply, marketHistoryData) - break; - case "transaction": - const transaction_history = JSON.parse(data.history_data) - - $(el).show() - chart.updateTransactionHistory(transaction_history) - break; + switch (historySource) { + case 'market': + const availableSupply = JSON.parse(data.supply_data) + const marketHistoryData = humps.camelizeKeys(JSON.parse(data.history_data)) + $(el).show() + chart.updateMarketHistory(availableSupply, marketHistoryData) + break + case 'transaction': + const transactionHistory = JSON.parse(data.history_data) + + $(el).show() + chart.updateTransactionHistory(transactionHistory) + break } }) .fail(() => { @@ -227,8 +209,9 @@ export function createMarketHistoryChart (el) { }) .always(() => { $chartLoading.hide() - })}) - return chart; + }) + }) + return chart } $('[data-chart-error-message]').on('click', _event => { diff --git a/apps/block_scout_web/assets/js/pages/chain.js b/apps/block_scout_web/assets/js/pages/chain.js index bb9625b282..8a71893171 100644 --- a/apps/block_scout_web/assets/js/pages/chain.js +++ b/apps/block_scout_web/assets/js/pages/chain.js @@ -1,3 +1,4 @@ +/* global _ */ import $ from 'jquery' import omit from 'lodash/omit' import first from 'lodash/first' @@ -9,7 +10,7 @@ import numeral from 'numeral' import socket from '../socket' import { exchangeRateChannel, formatUsdValue } from '../lib/currency' import { createStore, connectElements } from '../lib/redux_helpers.js' -import { batchChannel, showLoader } from '../lib/utils' +import { batchChannel } from '../lib/utils' import listMorph from '../lib/list_morph' import { createMarketHistoryChart } from '../lib/history_chart' @@ -107,9 +108,9 @@ function baseReducer (state = initialState, action) { }) } } - case 'RECIEVED_UPDATED_TRANSACTION_STATS':{ + case 'RECIEVED_UPDATED_TRANSACTION_STATS': { return Object.assign({}, state, { - transactionStats: action.msg.stats, + transactionStats: action.msg.stats }) } case 'START_TRANSACTIONS_FETCH': @@ -154,7 +155,7 @@ const elements = { if (chart && !(oldState.availableSupply === state.availableSupply && oldState.marketHistoryData === state.marketHistoryData) && state.availableSupply) { chart.updateMarketHistory(state.availableSupply, state.marketHistoryData) } - if (chart && !(_.isEqual(oldState.transactionStats, state.transactionStats))){ + if (chart && !(_.isEqual(oldState.transactionStats, state.transactionStats))) { chart.updateTransactionHistory(state.transactionStats) } } @@ -223,7 +224,11 @@ const elements = { }, '[data-selector="chain-block-list"] [data-selector="loading-message"]': { render ($el, state, oldState) { - showLoader(state.blocksLoading, $el) + if (state.blocksLoading) { + $el.show() + } else { + $el.hide() + } } }, '[data-selector="transactions-list"] [data-selector="error-message"]': { @@ -233,7 +238,7 @@ const elements = { }, '[data-selector="transactions-list"] [data-selector="loading-message"]': { render ($el, state, oldState) { - showLoader(state.transactionsLoading, $el) + $el.toggle(state.transactionsLoading) } }, '[data-selector="transactions-list"]': { diff --git a/apps/block_scout_web/lib/block_scout_web/controllers/chain/transaction_history_chart_controller.ex b/apps/block_scout_web/lib/block_scout_web/controllers/chain/transaction_history_chart_controller.ex index ca1346ba56..9b1649baba 100644 --- a/apps/block_scout_web/lib/block_scout_web/controllers/chain/transaction_history_chart_controller.ex +++ b/apps/block_scout_web/lib/block_scout_web/controllers/chain/transaction_history_chart_controller.ex @@ -5,17 +5,19 @@ defmodule BlockScoutWeb.Chain.TransactionHistoryChartController do def show(conn, _params) do with true <- ajax?(conn) do - [{:history_size, history_size}] = Application.get_env(:block_scout_web, __MODULE__, 30) + [{:history_size, history_size}] = Application.get_env(:block_scout_web, __MODULE__, 30) latest = Date.utc_today() earliest = Date.add(latest, -1 * history_size) - transaction_history_data = TransactionStats.by_date_range(earliest, latest) + date_range = TransactionStats.by_date_range(earliest, latest) + + transaction_history_data = date_range |> extract_history |> encode_transaction_history_data json(conn, %{ - history_data: transaction_history_data, + history_data: transaction_history_data }) else _ -> unprocessable_entity(conn) @@ -24,7 +26,8 @@ defmodule BlockScoutWeb.Chain.TransactionHistoryChartController do defp extract_history(db_results) do Enum.map(db_results, fn row -> - %{date: row.date, number_of_transactions: row.number_of_transactions} end) + %{date: row.date, number_of_transactions: row.number_of_transactions} + end) end defp encode_transaction_history_data(transaction_history_data) do diff --git a/apps/block_scout_web/lib/block_scout_web/controllers/chain_controller.ex b/apps/block_scout_web/lib/block_scout_web/controllers/chain_controller.ex index d5e11ad302..12b440f713 100644 --- a/apps/block_scout_web/lib/block_scout_web/controllers/chain_controller.ex +++ b/apps/block_scout_web/lib/block_scout_web/controllers/chain_controller.ex @@ -2,10 +2,10 @@ defmodule BlockScoutWeb.ChainController do use BlockScoutWeb, :controller alias BlockScoutWeb.ChainView - alias Explorer.{Chain, PagingOptions} + alias Explorer.{Chain, PagingOptions, Repo} alias Explorer.Chain.{Address, Block, Transaction} - alias Explorer.Chain.Transaction.History.TransactionStats alias Explorer.Chain.Supply.RSK + alias Explorer.Chain.Transaction.History.TransactionStats alias Explorer.Counters.AverageBlockTime alias Explorer.ExchangeRates.Token alias Explorer.Market @@ -15,7 +15,6 @@ defmodule BlockScoutWeb.ChainController do transaction_estimated_count = Chain.transaction_estimated_count() block_count = Chain.block_estimated_count() - market_cap_calculation = case Application.get_env(:explorer, :supply) do RSK -> @@ -29,8 +28,18 @@ defmodule BlockScoutWeb.ChainController do transaction_stats = get_transaction_stats() - chart_data_paths = %{market: market_history_chart_path(conn, :show), - transaction: transaction_history_chart_path(conn, :show)} + # Hack for render during testing + transaction_stats = + if length(transaction_stats) == 0 do + [%{number_of_transactions: 0}] + else + transaction_stats + end + + chart_data_paths = %{ + market: market_history_chart_path(conn, :show), + transaction: transaction_history_chart_path(conn, :show) + } chart_config = Application.get_env(:block_scout_web, :chart_config, %{}) @@ -51,14 +60,14 @@ defmodule BlockScoutWeb.ChainController do ) end - def get_transaction_stats() do + def get_transaction_stats do stats_scale = date_range(1) TransactionStats.by_date_range(stats_scale.earliest, stats_scale.latest) end def date_range(num_days) do today = Date.utc_today() - x_days_back = Date.add(today, -1*(num_days-1)) + x_days_back = Date.add(today, -1 * (num_days - 1)) %{earliest: x_days_back, latest: today} end @@ -75,8 +84,6 @@ defmodule BlockScoutWeb.ChainController do end end - def search(conn, _), do: not_found(conn) - def token_autocomplete(conn, %{"q" => term}) when is_binary(term) do if term == "" do json(conn, "{}") @@ -97,15 +104,9 @@ defmodule BlockScoutWeb.ChainController do def chain_blocks(conn, _params) do if ajax?(conn) do blocks = - [ - paging_options: %PagingOptions{page_size: 4}, - necessity_by_association: %{ - [miner: :names] => :optional, - :transactions => :optional, - :rewards => :optional - } - ] + [paging_options: %PagingOptions{page_size: 4}] |> Chain.list_blocks() + |> Repo.preload([[miner: :names], :transactions, :rewards]) |> Enum.map(fn block -> %{ chain_block_html: diff --git a/apps/block_scout_web/lib/block_scout_web/notifier.ex b/apps/block_scout_web/lib/block_scout_web/notifier.ex index 40ce428144..194bf67198 100644 --- a/apps/block_scout_web/lib/block_scout_web/notifier.ex +++ b/apps/block_scout_web/lib/block_scout_web/notifier.ex @@ -122,11 +122,14 @@ defmodule BlockScoutWeb.Notifier do def handle_event({:chain_event, :transaction_stats}) do today = Date.utc_today() - [{:history_size, history_size}] = Application.get_env(:block_scout_web, BlockScoutWeb.Chain.TransactionHistoryChartController, 30) + + [{:history_size, history_size}] = + Application.get_env(:block_scout_web, BlockScoutWeb.Chain.TransactionHistoryChartController, 30) x_days_back = Date.add(today, -1 * history_size) - stats = TransactionStats.by_date_range(x_days_back, today) - |> Enum.map(fn item -> Map.drop(item, [:__meta__]) end) + + date_range = TransactionStats.by_date_range(x_days_back, today) + stats = Enum.map(date_range, fn item -> Map.drop(item, [:__meta__]) end) Endpoint.broadcast("transactions:stats", "update", %{stats: stats}) end diff --git a/apps/block_scout_web/lib/block_scout_web/templates/chain/show.html.eex b/apps/block_scout_web/lib/block_scout_web/templates/chain/show.html.eex index 48dda23aaa..d5f0fcab0f 100644 --- a/apps/block_scout_web/lib/block_scout_web/templates/chain/show.html.eex +++ b/apps/block_scout_web/lib/block_scout_web/templates/chain/show.html.eex @@ -5,7 +5,7 @@