Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 26 additions & 9 deletions app/components/Package/TrendsChart.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script setup lang="ts">
import type { VueUiXyConfig, VueUiXyDatasetItem } from 'vue-data-ui'
import type { Theme as VueDataUiTheme, VueUiXyConfig, VueUiXyDatasetItem } from 'vue-data-ui'
import { VueUiXy } from 'vue-data-ui/vue-ui-xy'
import { useDebounceFn, useElementSize } from '@vueuse/core'
import { useCssVariables } from '~/composables/useColors'
Expand Down Expand Up @@ -50,6 +50,8 @@ const props = withDefaults(

const { locale } = useI18n()
const { accentColors, selectedAccentColor } = useAccentColor()
const { copy, copied } = useClipboard()

const colorMode = useColorMode()
const resolvedMode = shallowRef<'light' | 'dark'>('light')
const rootEl = shallowRef<HTMLElement | null>(null)
Expand Down Expand Up @@ -321,6 +323,7 @@ const {
fetchPackageLikesEvolution,
fetchRepoContributorsEvolution,
fetchRepoRefsForPackages,
copyAltTextForTrendLineChart,
} = useCharts()

const repoRefsByPackage = shallowRef<Record<string, RepoRef | null>>({})
Expand Down Expand Up @@ -1406,7 +1409,7 @@ function drawSvgPrintLegend(svg: Record<string, any>) {
// VueUiXy chart component configuration
const chartConfig = computed<VueUiXyConfig>(() => {
return {
theme: isDarkMode.value ? 'dark' : '',
theme: isDarkMode.value ? 'dark' : ('' as VueDataUiTheme),
chart: {
height: isMobile.value ? 950 : 600,
backgroundColor: colors.value.bg,
Expand All @@ -1418,14 +1421,14 @@ const chartConfig = computed<VueUiXyConfig>(() => {
fullscreen: false,
table: false,
tooltip: false,
altCopy: false, // TODO: set to true to enable the alt copy feature
altCopy: true,
},
buttonTitles: {
csv: $t('package.trends.download_file', { fileType: 'CSV' }),
img: $t('package.trends.download_file', { fileType: 'PNG' }),
svg: $t('package.trends.download_file', { fileType: 'SVG' }),
annotator: $t('package.trends.toggle_annotator'),
altCopy: undefined, // TODO: set to proper translation key
altCopy: $t('package.trends.copy_alt.button_label'), // Do not make this text dependant on the `copied` variable, since this would re-render the component, which is undesirable if the minimap was used to select a time frame.
},
callbacks: {
img: args => {
Expand Down Expand Up @@ -1458,10 +1461,21 @@ const chartConfig = computed<VueUiXyConfig>(() => {
loadFile(url, buildExportFilename('svg'))
URL.revokeObjectURL(url)
},
// altCopy: ({ dataset: dst, config: cfg }: { dataset: Array<VueUiXyDatasetItem>; config: VueUiXyConfig}) => {
// // TODO: implement a reusable copy-alt-text-to-clipboard feature based on the dataset & configuration
// console.log({ dst, cfg})
// }
altCopy: ({ dataset: dst, config: cfg }) =>
copyAltTextForTrendLineChart({
dataset: dst,
config: {
...cfg,
Comment thread
alexdln marked this conversation as resolved.
formattedDatasetValues: (dst?.lines || []).map(d =>
d.series.map(n => compactNumberFormatter.value.format(n ?? 0)),
),
hasEstimation:
supportsEstimation.value && !isEndDateOnPeriodEnd.value && !isZoomed.value,
granularity: displayedGranularity.value,
copy,
$t,
},
}),
},
},
grid: {
Expand Down Expand Up @@ -1870,7 +1884,10 @@ watch(selectedMetric, value => {
</template>
<template #optionAltCopy>
<span
class="i-lucide:person-standing w-6 h-6 text-fg-subtle"
class="w-6 h-6"
:class="
copied ? 'i-lucide:check text-accent' : 'i-lucide:person-standing text-fg-subtle'
"
style="pointer-events: none"
aria-hidden="true"
/>
Expand Down
100 changes: 100 additions & 0 deletions app/composables/useCharts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ import { parseRepoUrl } from '#shared/utils/git-providers'
import type { PackageMetaResponse } from '#shared/types'
import { encodePackageName } from '#shared/utils/npm'
import { fetchNpmDownloadsRange } from '~/utils/npm/api'
import type { AltCopyArgs } from 'vue-data-ui'
import {
computeLineChartAnalysis,
type TrendLineConfig,
type TrendLineDataset,
} from '../utils/charts'

export type PackumentLikeForTime = {
time?: Record<string, string>
Expand Down Expand Up @@ -405,6 +411,8 @@ export function getNpmPackageCreationDate(packument: PackumentLikeForTime): stri
}

export function useCharts() {
const compactNumberFormatter = useCompactNumberFormatter()

function resolveDateRange(
evolutionOptions: EvolutionOptions,
packageCreatedIso: string | null,
Expand Down Expand Up @@ -615,11 +623,103 @@ export function useCharts() {
return next
}

function createAltTextForTrendLineChart({
dataset,
config,
}: AltCopyArgs<TrendLineDataset, TrendLineConfig>): string {
if (!dataset) return ''

const analysis = dataset.lines.map(({ name, series }) => ({
name,
...computeLineChartAnalysis(series),
dates: config.formattedDates,
hasEstimation: config.hasEstimation,
}))

const granularityKeyByGranularity: Record<string, string> = {
daily: 'package.trends.granularity_dayly',
weekly: 'package.trends.granularity_weekly',
monthly: 'package.trends.granularity_monthly',
yearly: 'package.trends.granularity_yearly',
}

const granularityKey =
granularityKeyByGranularity[config.granularity as unknown as string] ??
'package.trends.granularity_day'

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
const granularity = String(config.$t(granularityKey)).toLocaleLowerCase()

const packages_analysis = analysis
.map((pkg, i) => {
const trendText = (() => {
switch (pkg.interpretation.trend) {
case 'none':
return config.$t('package.trends.copy_alt.trend_none')
case 'weak':
return config.$t('package.trends.copy_alt.trend_weak')
case 'strong':
return config.$t('package.trends.copy_alt.trend_strong')
case 'undefined':
default:
return config.$t('package.trends.copy_alt.trend_undefined')
}
})()

return config.$t('package.trends.copy_alt.analysis', {
package_name: pkg.name,
start_value: config.formattedDatasetValues[i]?.[0] ?? 0,
end_value: config.formattedDatasetValues[i]?.at(-1) ?? 0,
trend: trendText,
downloads_slope: compactNumberFormatter.value.format(pkg.slope),
growth_percentage: `${pkg.progressionPercent?.toFixed(1)}%`,
})
Comment thread
graphieros marked this conversation as resolved.
Outdated
})
.join(', ')

const isSinglePackage = analysis.length === 1

const estimation_notice = config.hasEstimation
? ` ${
isSinglePackage
? config.$t('package.trends.copy_alt.estimation')
: config.$t('package.trends.copy_alt.estimations')
}`
: ''

const compareText = `${config.$t('package.trends.copy_alt.compare', {
packages: analysis.map(a => a.name).join(', '),
})} `

const singlePackageText = `${config.$t('package.trends.copy_alt.single_package', {
package: analysis?.[0]?.name ?? '',
})} `

const generalAnalysis = config.$t('package.trends.copy_alt.general_description', {
start_date: analysis?.[0]?.dates[0]?.text,
end_date: analysis?.[0]?.dates.at(-1)?.text,
granularity,
packages_analysis,
watermark: config.$t('package.trends.copy_alt.watermark'),
estimation_notice,
})

return (isSinglePackage ? singlePackageText : compareText) + generalAnalysis
}

async function copyAltTextForTrendLineChart({
dataset,
config,
}: AltCopyArgs<TrendLineDataset, TrendLineConfig>) {
const altText = createAltTextForTrendLineChart({ dataset, config })
await config.copy(altText)
}

return {
fetchPackageDownloadEvolution,
fetchPackageLikesEvolution,
fetchRepoContributorsEvolution,
fetchRepoRefsForPackages,
getNpmPackageCreationDate,
copyAltTextForTrendLineChart,
}
}
Loading
Loading