Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 3 additions & 3 deletions app/src/app/pages/[username].page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
simpleBluesky, simpleFacebook, simpleGithub, simpleInstagram, simpleMastodon, simpleNpm, simpleReddit, simpleThreads, simpleTwitch, simpleX,
simpleYoutube,
} from '@ng-icons/simple-icons';
import { badgeQuery, parseBadgeOptions } from '../profile/card-badges';
import { cardOptionsQuery, parseCardOptions } from '../profile/card-options';
import { BADGE_ICONS, earnedBadges } from '../profile/earned-badges';
import { BadgePill } from '../profile/badge-pill';
import { injectParams } from 'ngxtension/inject-params';
Expand Down Expand Up @@ -84,7 +84,7 @@ export default class Profile {
private readonly fromCountry = injectQueryParams(params => countryCode(params['country']));
/** The country the owner picked for the shared card, for this link's preview image. */
private readonly cardFlag = injectQueryParams(params => countryCode(params['flag']));
private readonly cardBadges = injectQueryParams(params => parseBadgeOptions(params['hide'], params['names']));
private readonly cardOptions = injectQueryParams(params => parseCardOptions(params));
/** Every period is in the profile: switching period needs no request. */
protected readonly profile = injectSeededServerFn(getContributor, () => ({ username: this.username() }));

Expand Down Expand Up @@ -237,7 +237,7 @@ export default class Profile {
const { title, description } = profileHead(person, this.current(), this.period());
this.title.setTitle(`${title} · Angularians`);
this.meta.removeTag('name="robots"');
const cardQuery = shareQuery(this.period(), this.cardFlag(), badgeQuery(this.cardBadges()));
const cardQuery = shareQuery(this.period(), this.cardFlag(), cardOptionsQuery(this.cardOptions()));
setShareMeta(this.meta, this.document, {
title,
description,
Expand Down
2 changes: 1 addition & 1 deletion app/src/app/profile/card-design.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/** Raise it when the card's design changes, so the preview does not show a copy the browser kept. */
export const CARD_DESIGN = 18
export const CARD_DESIGN = 19
15 changes: 15 additions & 0 deletions app/src/app/profile/card-identity.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { identityQuery, parseCardIdentity } from './card-identity'

describe('card identity options', () => {
it('shows the avatar and the username unless the query says off', () => {
expect(parseCardIdentity(undefined, undefined)).toEqual({ avatar: true, username: true })
expect(parseCardIdentity(['off'], 'on')).toEqual({ avatar: true, username: true })
expect(parseCardIdentity('off', 'off')).toEqual({ avatar: false, username: false })
})

it('writes an option only when it is off', () => {
expect(identityQuery({ avatar: true, username: true })).toEqual({})
expect(identityQuery({ avatar: false, username: true })).toEqual({ avatar: 'off' })
expect(identityQuery({ avatar: true, username: false })).toEqual({ username: 'off' })
})
})
11 changes: 11 additions & 0 deletions app/src/app/profile/card-identity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export interface CardIdentity {
avatar: boolean
username: boolean
}

export const parseCardIdentity = (avatar: unknown, username: unknown): CardIdentity => ({ avatar: avatar !== 'off', username: username !== 'off' })

export const identityQuery = ({ avatar, username }: CardIdentity): Record<string, string> => ({
...(avatar ? {} : { avatar: 'off' }),
...(username ? {} : { username: 'off' }),
})
16 changes: 16 additions & 0 deletions app/src/app/profile/card-options.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { cardOptionsQuery, parseCardOptions } from './card-options'

describe('card options', () => {
it('reads the badge and identity options from one query', () => {
expect(parseCardOptions({ hide: 'reviewer', names: 'official', avatar: 'off', username: 'off' })).toEqual({
badges: { hidden: ['reviewer'], names: 'official' },
identity: { avatar: false, username: false },
})
})

it('writes them back as the same query', () => {
const query = { hide: 'reviewer', names: 'official', avatar: 'off', username: 'off' }
expect(cardOptionsQuery(parseCardOptions(query))).toEqual(query)
expect(cardOptionsQuery(parseCardOptions({}))).toEqual({})
})
})
14 changes: 14 additions & 0 deletions app/src/app/profile/card-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { badgeQuery, parseBadgeOptions, type BadgeOptions } from './card-badges'
import { identityQuery, parseCardIdentity, type CardIdentity } from './card-identity'

export interface CardOptions {
badges: BadgeOptions
identity: CardIdentity
}

export const parseCardOptions = (query: Record<string, unknown>): CardOptions => ({
badges: parseBadgeOptions(query['hide'], query['names']),
identity: parseCardIdentity(query['avatar'], query['username']),
})

export const cardOptionsQuery = ({ badges, identity }: CardOptions): Record<string, string> => ({ ...badgeQuery(badges), ...identityQuery(identity) })
16 changes: 13 additions & 3 deletions app/src/app/profile/share.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,19 @@
</ng-template>

<ng-template #preview>
@if (cardPeriods().length > 1) {
<app-period-tabs class="self-start" [period]="cardPeriod()" [periods]="cardPeriods()" label="Period of the card" (periodChange)="pickPeriod($event)" />
}
<div class="flex flex-wrap items-center justify-between gap-2">
@if (cardPeriods().length > 1) {
<app-period-tabs [period]="cardPeriod()" [periods]="cardPeriods()" label="Period of the card" (periodChange)="pickPeriod($event)" />
}
<div class="flex gap-1">
<button hlmBtn variant="ghost" size="sm" type="button" (click)="toggleAvatar()">
<ng-icon [name]="showAvatar() ? 'remixUserForbidLine' : 'remixUserLine'" aria-hidden="true" /> {{ avatarLabel() }}
</button>
<button hlmBtn variant="ghost" size="sm" type="button" (click)="toggleUsername()">
<ng-icon [name]="showUsername() ? 'remixEyeOffLine' : 'remixEyeLine'" aria-hidden="true" /> {{ usernameLabel() }}
</button>
</div>
</div>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
<app-country-select class="shrink-0" [countries]="allCountries" [value]="flag()" [allLabel]="flagLabel()" ariaLabel="Country on the card" [showCounts]="false" (valueChange)="pickFlag($event)" />
<p class="text-xs text-pretty text-muted-foreground">
Expand Down
31 changes: 24 additions & 7 deletions app/src/app/profile/share.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { NgTemplateOutlet } from '@angular/common'
import { Component, computed, input, linkedSignal, signal } from '@angular/core'
import { periodPhrase, sortPeriods, type Period, COUNTRIES, countryName } from '@angularians/shared'
import { NgIcon, provideIcons } from '@ng-icons/core'
import { remixCheckLine, remixDownloadLine, remixFileCopyLine, remixImageLine, remixLinkedinBoxFill, remixLinkM, remixMarkdownLine, remixShareLine } from '@ng-icons/remixicon'
import { remixCheckLine, remixDownloadLine, remixEyeLine, remixEyeOffLine, remixFileCopyLine, remixImageLine, remixLinkedinBoxFill, remixLinkM, remixMarkdownLine, remixShareLine, remixUserForbidLine, remixUserLine } from '@ng-icons/remixicon'
import { simpleBluesky, simpleX } from '@ng-icons/simple-icons'
import { HlmButton } from '@spartan-ng/helm/button'
import { HlmDialogImports } from '@spartan-ng/helm/dialog'
Expand All @@ -13,8 +13,9 @@ import { HlmSkeleton } from '@spartan-ng/helm/skeleton'
import { SITE_URL } from '../site'
import { shareQuery } from './share-query'
import { CardBadgeOptions } from './card-badge-options'
import { badgeQuery, type BadgeNameStyle } from './card-badges'
import type { BadgeNameStyle } from './card-badges'
import { CARD_DESIGN } from './card-design'
import { cardOptionsQuery } from './card-options'
import type { EarnedBadge } from './earned-badges'

/** The skeleton shows at least this long, so a fast card does not flicker it. */
Expand All @@ -30,7 +31,7 @@ export const SHARE_BUTTONS = { link: 'Copy profile link', card: 'Share card', re
@Component({
selector: 'app-share',
imports: [CardBadgeOptions, CountrySelect, HlmButton, HlmDialogImports, HlmSkeleton, NgIcon, NgTemplateOutlet, PeriodTabs],
providers: [provideIcons({ remixCheckLine, remixDownloadLine, remixFileCopyLine, remixImageLine, remixLinkedinBoxFill, remixShareLine, simpleBluesky, simpleX, remixLinkM, remixMarkdownLine })],
providers: [provideIcons({ remixCheckLine, remixDownloadLine, remixFileCopyLine, remixImageLine, remixLinkedinBoxFill, remixShareLine, simpleBluesky, simpleX, remixLinkM, remixMarkdownLine, remixUserForbidLine, remixUserLine, remixEyeLine, remixEyeOffLine })],
templateUrl: './share.html',
styleUrl: './share.css',
})
Expand Down Expand Up @@ -62,6 +63,10 @@ export class Share {
protected readonly flag = signal<string | null>(null)
protected readonly hiddenBadges = signal<readonly string[]>([])
protected readonly names = signal<BadgeNameStyle>('fun')
protected readonly showAvatar = signal(true)
protected readonly showUsername = signal(true)
protected readonly avatarLabel = computed(() => (this.showAvatar() ? 'Hide picture' : 'Show picture'))
protected readonly usernameLabel = computed(() => (this.showUsername() ? 'Hide name' : 'Show name'))
protected readonly allCountries = Object.keys(COUNTRIES).map(code => ({ code, count: 0, top: [] }))
protected readonly name = countryName
protected readonly flagLabel = computed(() => {
Expand All @@ -70,13 +75,13 @@ export class Share {
})
protected readonly cardPeriods = computed(() => sortPeriods(['all', ...this.periods()]))

private readonly badgeOptions = computed(() => badgeQuery({ hidden: this.hiddenBadges(), names: this.names() }))
private readonly cardOptions = computed(() => cardOptionsQuery({ badges: { hidden: this.hiddenBadges(), names: this.names() }, identity: { avatar: this.showAvatar(), username: this.showUsername() } }))
private readonly profileUrl = computed(() => `${SITE_URL}/${this.username()}${shareQuery(this.period())}`)
/** The profile with the card's period and flag: what a post links to, and the README card's link. */
private readonly cardProfileUrl = computed(() => `${SITE_URL}/${this.username()}${shareQuery(this.cardPeriod(), this.flag(), this.badgeOptions())}`)
private readonly cardUrl = computed(() => `${SITE_URL}/${this.username()}/card.png${shareQuery(this.cardPeriod(), this.flag(), this.badgeOptions())}`)
private readonly cardProfileUrl = computed(() => `${SITE_URL}/${this.username()}${shareQuery(this.cardPeriod(), this.flag(), this.cardOptions())}`)
private readonly cardUrl = computed(() => `${SITE_URL}/${this.username()}/card.png${shareQuery(this.cardPeriod(), this.flag(), this.cardOptions())}`)
/** The same card from this site: right on a preview deploy or locally too. The Markdown keeps the public address. */
protected readonly previewUrl = computed(() => `/${this.username()}/card.png${shareQuery(this.cardPeriod(), this.flag(), { v: String(CARD_DESIGN), ...this.badgeOptions() })}`)
protected readonly previewUrl = computed(() => `/${this.username()}/card.png${shareQuery(this.cardPeriod(), this.flag(), { v: String(CARD_DESIGN), ...this.cardOptions() })}`)
protected readonly fileName = computed(() => `${this.username()}-angularian${this.cardPeriod() === 'all' ? '' : `-${this.cardPeriod()}`}.png`)
/** The profile's link preview is this card, so a post only needs the link. */
protected readonly shareLinks = computed(() => {
Expand Down Expand Up @@ -104,6 +109,8 @@ export class Share {
this.flag.set(null)
this.hiddenBadges.set([])
this.names.set('fun')
this.showAvatar.set(true)
this.showUsername.set(true)
this.shownUrl.set(null)
this.startLoading()
}
Expand All @@ -120,6 +127,16 @@ export class Share {
this.startLoading()
}

protected toggleAvatar(): void {
this.showAvatar.update(shown => !shown)
this.startLoading()
}

protected toggleUsername(): void {
this.showUsername.update(shown => !shown)
this.startLoading()
}

protected showLoadedCard(url: string): void {
clearTimeout(this.loadedTimer)
this.loadedTimer = setTimeout(() => {
Expand Down
29 changes: 21 additions & 8 deletions app/src/server/card/card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { formatMonth } from '../../app/text/date-format'
import { formatNumber, formatPoints, formatRank } from '../../app/text/number-format'
import { statWord } from '../../app/text/stat-names'
import { TAG_FONT_SIZE, TAG_GAP, TAG_HEIGHT, TAG_ICON_SIZE, TAG_ICON_WIDTH, TAG_LARGE_ICON, TAG_LARGE_SIZE, TAG_PADDING, type CardTag } from './card-tags'
import type { CardIdentity } from '../../app/profile/card-identity'
import type { TagColors } from './tag-colors'
import { TAG_FONTS } from './tag-fonts'

Expand Down Expand Up @@ -105,11 +106,23 @@ export function cardPeriod(profile: ContributorProfile, requested: unknown): Per
return period !== 'all' && profile.periods.some(row => row.period === period) ? period : 'all'
}

/** `avatar`: a data URL, or `null` when GitHub did not send it (a grey circle instead). */
export function cardTree(profile: ContributorProfile, period: Period, avatar: string | null, flag: { src: string, name: string } | null = null, tags: readonly CardTag[] = []): Node {
function cardHead({ avatar, username }: CardIdentity) {
const bare = !avatar && !username
return {
justify: avatar && username ? 'flex-start' : 'center',
usernameTop: avatar ? 12 : 0,
rankTop: username ? 6 : avatar ? 12 : 0,
rankSize: bare ? 128 : 84,
pointsSize: bare ? 36 : 30,
}
}

/** `avatar`: a data URL, or `null` when GitHub did not send it (a grey circle instead). `identity`: what the owner left on. */
export function cardTree(profile: ContributorProfile, period: Period, avatar: string | null, flag: { src: string, name: string } | null = null, tags: readonly CardTag[] = [], identity: CardIdentity = { avatar: true, username: true }): Node {
const tiles = !tags.length ? TILES : tags.some(tag => tag.row === 3) ? TILES_WITH_THREE_ROWS : TILES_WITH_TAGS
const stats = period === 'all' ? profile : profile.periods.find(row => row.period === period)!
const since = profile.firstContributionAt ? formatMonth(profile.firstContributionAt) : null
const head = cardHead(identity)
const rows = [
[
{ label: statWord('pullRequests', stats.pullRequests.all), value: stats.pullRequests.all, color: COLORS.pullRequests, icon: ICONS.pullRequests },
Expand All @@ -122,13 +135,13 @@ export function cardTree(profile: ContributorProfile, period: Period, avatar: st
]
return h('div', { width: '100%', height: '100%', flexDirection: 'column', justifyContent: 'space-between', backgroundColor: '#0a0a0a', color: '#ffffff', paddingTop: 44, paddingRight: 64, paddingBottom: 36, paddingLeft: 64, fontFamily: 'Manrope' }, [
h('div', { flexDirection: 'row', gap: 64 }, [
h('div', { flexDirection: 'column', width: 380 }, [
avatar
h('div', { flexDirection: 'column', width: 380, justifyContent: head.justify }, [
...(!identity.avatar ? [] : [avatar
? h('img', { width: 108, height: 108, borderRadius: 9999, border: '4px solid #262626' }, undefined, { src: avatar, width: 108, height: 108 })
: h('div', { width: 108, height: 108, borderRadius: 9999, backgroundColor: '#262626' }),
h('div', { fontSize: 40, fontWeight: 600, marginTop: 12, maxWidth: 380, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, profile.username),
h('div', { fontFamily: 'Norse', fontWeight: 700, fontSize: 84, lineHeight: 1, letterSpacing: 2, color: BRAND, marginTop: 6 }, formatRank(period === 'all' ? profile.rank : stats.rank)),
h('div', { fontSize: 30, fontWeight: 600, color: BRAND, marginTop: 4 }, formatPoints(stats.score)),
: h('div', { width: 108, height: 108, borderRadius: 9999, backgroundColor: '#262626' })]),
...(identity.username ? [h('div', { fontSize: 40, fontWeight: 600, marginTop: head.usernameTop, maxWidth: 380, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, profile.username)] : []),
h('div', { fontFamily: 'Norse', fontWeight: 700, fontSize: head.rankSize, lineHeight: 1, letterSpacing: 2, color: BRAND, marginTop: head.rankTop }, formatRank(period === 'all' ? profile.rank : stats.rank)),
h('div', { fontSize: head.pointsSize, fontWeight: 600, color: BRAND, marginTop: 4 }, formatPoints(stats.score)),
...(period !== 'all' ? [h('div', { fontSize: 24, color: '#a3a3a3', marginTop: 4 }, periodPhrase(period))] : []),
...(flag ? [h('div', { flexDirection: 'row', alignItems: 'center', gap: 10, marginTop: period === 'all' ? 10 : 4, fontSize: 24, color: '#a3a3a3' }, [
h('img', { width: 30, height: 30 }, undefined, { src: flag.src, width: 30, height: 30 }),
Expand Down
9 changes: 5 additions & 4 deletions app/src/server/routes/[username]/card.png.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { sendPng } from '../../data/http'
import { createError, defineEventHandler, getQuery, getRouterParam } from 'h3'
import * as v from 'valibot'
import { countryCode, countryName } from '@angularians/shared'
import { parseBadgeOptions } from '../../../app/profile/card-badges'
import { parseCardOptions } from '../../../app/profile/card-options'
import { avatarData, cardFonts, flagData } from '../../card/assets'
import { cardBadgeTags } from '../../card/badges'
import { cardPeriod, cardTree, renderCard } from '../../card/card'
import { UsernameSchema } from '../../data/schemas'
import { contributorsData } from '../../data/store'

/**
* `GET /:username/card.png?period=2025&flag=TR`: the Angularian card, for GitHub profile READMEs and the profile's link
* `GET /:username/card.png?period=2025&flag=TR&avatar=off&username=off`: the Angularian card, for GitHub profile READMEs and the profile's link
* preview. The URL never changes; the numbers do, every night.
*/
export default defineEventHandler(async (event) => {
Expand All @@ -22,8 +22,9 @@ export default defineEventHandler(async (event) => {
const period = cardPeriod(profile, getQuery(event)['period'])
// `?flag=TR`: the country the owner picked for this card. Otherwise their GitHub location.
const code = countryCode(getQuery(event)['flag']) ?? profile.country ?? null
const [avatar, flagSrc, fonts, tags] = await Promise.all([avatarData(profile.githubId), code ? flagData(code) : null, cardFonts(), cardBadgeTags(profile, parseBadgeOptions(getQuery(event)['hide'], getQuery(event)['names']))])
const png = await renderCard(cardTree(profile, period, avatar, code && flagSrc ? { src: flagSrc, name: countryName(code) } : null, tags), fonts)
const { badges, identity } = parseCardOptions(getQuery(event))
const [avatar, flagSrc, fonts, tags] = await Promise.all([identity.avatar ? avatarData(profile.githubId) : null, code ? flagData(code) : null, cardFonts(), cardBadgeTags(profile, badges)])
const png = await renderCard(cardTree(profile, period, avatar, code && flagSrc ? { src: flagSrc, name: countryName(code) } : null, tags, identity), fonts)
// A day in shared caches (GitHub's image proxy too): each night's deploy clears the CDN.
return sendPng(event, png)
})
2 changes: 1 addition & 1 deletion app/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export default defineConfig(() => ({
// country). Any other one (`?utm_source=`) shares the page's copy. A route reading a new parameter must add it here.
// and per value of the signed-in hint cookie (app/src/app/auth/hint.ts), whose pages start with the signed-in
// card's skeleton. Every other cookie is ignored by the cache.
'/**': { headers: { 'cache-control': 'public, max-age=0, s-maxage=86400, stale-while-revalidate=86400', 'netlify-cdn-cache-control': 'public, durable, s-maxage=86400, stale-while-revalidate=86400', 'netlify-vary': 'query=period|country|badges|match|page|q|flag|hide|names|v,cookie=angularians-signed-in' } },
'/**': { headers: { 'cache-control': 'public, max-age=0, s-maxage=86400, stale-while-revalidate=86400', 'netlify-cdn-cache-control': 'public, durable, s-maxage=86400, stale-while-revalidate=86400', 'netlify-vary': 'query=period|country|badges|match|page|q|flag|hide|names|avatar|username|v,cookie=angularians-signed-in' } },
// Sign-in: per person, with cookies. Never in a shared cache.
'/api/auth/**': { headers: { 'cache-control': 'private, no-store', 'netlify-cdn-cache-control': 'no-store' } },
// Server functions are POSTs whose input is in the body, which no cache key sees: never cached.
Expand Down
Loading
Loading