π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
β¨ Add Live Tennis widget
Bend39e322c31d6
diff --git a/docs/widgets.md b/docs/widgets.mdindex e3394ee5..0e2cadcb 100644--- a/docs/widgets.md+++ b/docs/widgets.md@@ -24,6 +24,7 @@ Dashy has support for displaying dynamic content in the form of widgets. There a- [Public Holidays](#public-holidays)- [Covid-19 Status](#covid-19-status)- [Sports Scores](#sports-scores)+ - [Live Tennis](#live-tennis)- [News Headlines](#news-headlines)- [TFL Status](#tfl-status)- [Stock Price History](#stock-price-history)@@ -860,6 +861,51 @@ Show recent scores and upcoming matches from your favorite sports team. Data is---+### Live Tennis++Live tennis scores from the ATP and WTA tours, updating in place. Each match shows both players with their per-set game scores, the current game points, and a marker against whoever is serving. Set the `status` option to show upcoming or recently finished matches instead. Data is from [LiveTennisAPI](https://livetennisapi.com/).++#### Options++**Field** | **Type** | **Required** | **Description**+--- | --- | --- | ---+**`apiKey`** | `string` | Required | Your LiveTennisAPI key. The [free plan](https://livetennisapi.com/subscribe/free) needs no card, and is enough for this widget+**`status`** | `string` | _Optional_ | Which matches to show: `live`, `upcoming` or `completed`. Defaults to `live`+**`limit`** | `number` | _Optional_ | Maximum number of matches to show, defaults to `5`+**`hideRankings`** | `boolean` | _Optional_ | Set to `true` to hide each player's world ranking, defaults to `false`+**`hideTournament`** | `boolean` | _Optional_ | Set to `true` to hide the tournament name, defaults to `false`++#### Example++```yaml+- type: live-tennis+ options:+ apiKey: twjp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+ limit: 5+```++Showing the next matches due on court, instead of those in play:++```yaml+- type: live-tennis+ options:+ apiKey: twjp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+ status: upcoming+ hideRankings: true+```++#### Info++- **CORS**: π’ Enabled (no proxy needed)+- **Auth**: π΄ Required+- **Price**: π Free plan (30 requests / minute)+- **Host**: Managed Instance Only+- **Privacy**: [LiveTennisAPI Privacy Policy](https://livetennisapi.com/privacy)++The widget refreshes every 60 seconds by default, which sits comfortably inside the free plan's rate limit. You can change this with the standard `updateInterval` option, but note that several widgets sharing one key all count against the same limit.++---+### News HeadlinesDisplays the latest news, click to read full article. Date is fetched from various news sources using [Currents API](https://currentsapi.services/en)diff --git a/src/components/Widgets/LiveTennis.vue b/src/components/Widgets/LiveTennis.vuenew file mode 100644index 00000000..994c7d7f--- /dev/null+++ b/src/components/Widgets/LiveTennis.vue@@ -0,0 +1,285 @@+<template>+ <div class="live-tennis">+ <!-- Nothing on court right now -->+ <p class="no-matches" v-if="matches && !matches.length">+ No {{ status }} matches+ </p>+ <!-- One block per match -->+ <div class="match" v-for="match in matches" :key="match.id">+ <!-- Tournament, round and match state -->+ <div class="match-meta">+ <span class="tournament" v-if="!hideTournament">{{ match.tournament }}</span>+ <span class="round" v-if="match.round">{{ match.round }}</span>+ <span :class="`status status-${match.status}`">{{ match.statusLabel }}</span>+ </div>+ <!-- A row per player, with their set scores and current game points -->+ <div+ :class="['player', { serving: player.isServing, winner: player.isWinner }]"+ v-for="player in match.players"+ :key="player.id"+ >+ <span class="serve-indicator" aria-hidden="true">{{ player.isServing ? 'β' : '' }}</span>+ <span class="name">+ {{ player.name }}+ <span class="ranking" v-if="player.ranking && !hideRankings">#{{ player.ranking }}</span>+ </span>+ <span class="sets">+ <span+ :class="['set', { current: index === match.currentSet }]"+ v-for="(games, index) in player.games"+ :key="index"+ >{{ games }}</span>+ </span>+ <span :class="['points', { tiebreak: match.isTiebreak }]" v-if="match.isLive">+ {{ player.point }}+ </span>+ </div>+ </div>+ </div>+</template>++<script>+import WidgetMixin from '@/mixins/WidgetMixin';+import { widgetApiEndpoints } from '@/utils/config/defaults';++/* Human-readable label for each of the API's match states */+const STATUS_LABELS = {+ live: 'Live',+ upcoming: 'Upcoming',+ completed: 'Finished',+};++export default {+ mixins: [WidgetMixin],+ data() {+ return {+ matches: null, // Array of processed matches, null until first response+ };+ },+ computed: {+ /* API key, from livetennisapi.com. Required */+ apiKey() {+ return this.parseAsEnvVar(this.options.apiKey) || '';+ },+ /* Which matches to show: live, upcoming or completed */+ status() {+ const status = this.options.status || 'live';+ return Object.keys(STATUS_LABELS).includes(status) ? status : 'live';+ },+ limit() {+ return parseInt(this.options.limit, 10) || 5;+ },+ hideRankings() {+ return this.options.hideRankings || false;+ },+ hideTournament() {+ return this.options.hideTournament || false;+ },+ endpoint() {+ const url = `${widgetApiEndpoints.liveTennis}/matches`;+ return `${url}?status=${this.status}&limit=${this.limit}`;+ },+ headers() {+ return { Authorization: `Bearer ${this.apiKey}` };+ },+ },+ methods: {+ fetchData() {+ if (!this.apiKey) {+ this.error('An apiKey is required, get one free at livetennisapi.com');+ this.finishLoading();+ return;+ }+ if (this.options.status && this.options.status !== this.status) {+ this.error(`Invalid status '${this.options.status}', showing live matches instead`);+ }+ this.makeRequest(this.endpoint, this.headers)+ .then(this.processData)+ .catch(() => { /* Error already surfaced by the mixin */ });+ },+ processData(data) {+ const results = (data && data.data) || [];+ this.matches = results.map((match) => this.makeMatch(match));+ },+ /* Flatten a single match from the API into everything the template renders */+ makeMatch(match) {+ const score = match.score || {};+ const games = Array.isArray(score.games) ? score.games : [];+ // Sets are only over when both players have a game count recorded for them+ const setCount = Math.max(+ (games[0] || []).length,+ (games[1] || []).length,+ );+ const sets = Array.isArray(score.sets) ? score.sets : [];+ const isLive = match.status === 'live';+ return {+ id: match.id,+ tournament: match.tournament,+ round: match.round,+ status: match.status,+ statusLabel: STATUS_LABELS[match.status] || match.status,+ isLive,+ isTiebreak: !!score.is_tiebreak,+ // Only a live match has a set in progress to highlight+ currentSet: isLive ? setCount - 1 : -1,+ players: [+ this.makePlayer(match.players, 'p1', 0, score, setCount, sets, match.status),+ this.makePlayer(match.players, 'p2', 1, score, setCount, sets, match.status),+ ],+ };+ },+ /* Flatten one side of a match. `index` is 0 for p1, 1 for p2 */+ makePlayer(players, key, index, score, setCount, sets, status) {+ const player = (players || {})[key] || {};+ const games = ((score.games || [])[index] || []);+ const points = score.points || [];+ const opponentSets = sets[index === 0 ? 1 : 0];+ return {+ id: player.id || key,+ name: player.name || 'Unknown',+ ranking: player.ranking,+ // The API numbers the server 1 or 2, matching p1 / p2.+ // It keeps the last server on a finished match, so only show it while live+ isServing: status === 'live' && score.server === index + 1,+ // Pad short rows so both players' set columns stay aligned+ games: this.padGames(games, setCount),+ point: points[index] !== undefined ? points[index] : '',+ // Only a finished match has a winner to highlight+ isWinner: status === 'completed' && sets.length > 0 && sets[index] > opponentSets,+ };+ },+ /* Right-pad a player's per-set game counts so both rows are the same length */+ padGames(games, setCount) {+ const padded = games.slice(0, setCount);+ while (padded.length < setCount) padded.push('');+ return padded;+ },+ },+ created() {+ this.overrideUpdateInterval = 60;+ },+};+</script>++<style scoped lang="scss">+.live-tennis {+ color: var(--widget-text-color);++ p.no-matches {+ font-size: 1rem;+ margin: 0.5rem auto;+ text-align: center;+ opacity: var(--dimming-factor);+ }++ .match {+ padding: 0.25rem 0;++ &:not(:last-child) {+ border-bottom: 1px dashed var(--widget-text-color);+ }++ // Tournament name, round and match state+ .match-meta {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ font-size: 0.7rem;+ opacity: var(--dimming-factor);++ .tournament {+ font-weight: bold;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .round {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .status {+ margin-left: auto;+ padding: 0 0.3rem;+ border-radius: var(--curve-factor);+ background: var(--widget-accent-color);+ white-space: nowrap;++ &.status-live {+ color: var(--success, var(--widget-text-color));+ font-weight: bold;+ }+ }+ }++ // One row per player+ .player {+ display: flex;+ align-items: center;+ font-size: 0.9rem;+ padding: 0.1rem 0;++ .serve-indicator {+ width: 0.7rem;+ flex-shrink: 0;+ font-size: 0.5rem;+ line-height: 1;+ }++ .name {+ flex: 1;+ min-width: 0;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;++ .ranking {+ font-size: 0.7rem;+ opacity: var(--dimming-factor);+ margin-left: 0.2rem;+ }+ }++ .sets {+ display: flex;+ flex-shrink: 0;+ font-family: var(--font-monospace);++ .set {+ width: 1.1rem;+ text-align: center;+ opacity: var(--dimming-factor);++ &.current {+ opacity: 1;+ font-weight: bold;+ }+ }+ }++ .points {+ width: 1.6rem;+ flex-shrink: 0;+ text-align: right;+ font-family: var(--font-monospace);+ font-weight: bold;++ &.tiebreak {+ font-style: italic;+ }+ }++ // The player currently serving, and the winner of a finished match+ &.serving .serve-indicator {+ color: var(--success, var(--widget-text-color));+ }++ &.winner .name {+ font-weight: bold;+ }+ }+ }+}+</style>diff --git a/src/components/Widgets/WidgetBase.vue b/src/components/Widgets/WidgetBase.vueindex 242cf0d3..34144e68 100644--- a/src/components/Widgets/WidgetBase.vue+++ b/src/components/Widgets/WidgetBase.vue@@ -103,6 +103,7 @@ const COMPAT = {image: 'ImageWidget',joke: 'Jokes',linkding: 'Linkding',+ 'live-tennis': 'LiveTennis','minecraft-status': 'MinecraftStatus','mullvad-status': 'MullvadStatus',mvg: 'Mvg',diff --git a/src/utils/config/defaults.js b/src/utils/config/defaults.jsindex efd63647..946c0b33 100644--- a/src/utils/config/defaults.js+++ b/src/utils/config/defaults.js@@ -229,6 +229,7 @@ const defaults = {healthChecks: 'https://healthchecks.io/api/v1/checks',holidays: 'https://kayaposoft.com/enrico/json/v2.0/?action=getHolidaysForDateRange',jokes: 'https://v2.jokeapi.dev/joke/',+ liveTennis: 'https://api.livetennisapi.com/api/public/v1',news: 'https://api.currentsapi.services/v1/latest-news',minecraftPlayerIcon: 'https://mc-heads.net/avatar/',minecraftPlayerLink: 'https://minecraftuuid.com/?search=',diff --git a/tests/components/livetennis.test.js b/tests/components/livetennis.test.jsnew file mode 100644index 00000000..979cef23--- /dev/null+++ b/tests/components/livetennis.test.js@@ -0,0 +1,258 @@+import {+ describe, it, expect, afterEach, vi,+} from 'vitest';+import { shallowMount, flushPromises } from '@vue/test-utils';+import LiveTennis from '@/components/Widgets/LiveTennis.vue';++/* Trimmed from a real api.livetennisapi.com /matches?status=live response */+const liveResponse = {+ data: [+ {+ id: 21443,+ format: 'BO3',+ is_doubles: false,+ round: 'M15 Brisbane - 1/16-finals',+ scheduled_time: '2026-07-22T04:00:00Z',+ status: 'live',+ surface: 'hard',+ tournament: 'M15 Brisbane',+ players: {+ p1: { id: 1011, name: 'Matthew Dellavedova', country: 'aus', ranking: 310 },+ p2: { id: 8048, name: 'Hayden Jones', country: 'aus', ranking: 1235 },+ },+ score: {+ games: [[7, 1], [5, 0]],+ is_tiebreak: false,+ points: ['40', '15'],+ server: 2,+ sets: [1, 0],+ },+ },+ ],+ meta: { count: 1, limit: 5, offset: 0 },+};++/* An upcoming match carries a null score */+const upcomingResponse = {+ data: [+ {+ id: 21487,+ status: 'upcoming',+ round: 'W15 Brisbane 2 - 1/16-finals',+ tournament: 'W15 Brisbane 2 (Australia)',+ scheduled_time: '2026-07-22T04:30:00Z',+ players: {+ p1: { id: 2485, name: 'Mutsumi Uemura', ranking: 1022 },+ p2: { id: 9001, name: 'Jane Doe', ranking: null },+ },+ score: null,+ },+ ],+ meta: { count: 1, limit: 5, offset: 0 },+};++const completedResponse = {+ data: [+ {+ id: 21494,+ status: 'completed',+ round: 'W15 Brisbane 2 - 1/16-finals',+ tournament: 'W15 Brisbane 2 (Australia)',+ players: {+ p1: { id: 8134, name: 'Belle Thompson', ranking: 717 },+ p2: { id: 8135, name: 'Amy Roe', ranking: 980 },+ },+ score: {+ games: [[6, 6], [4, 0]], is_tiebreak: false, points: ['0', '0'], server: 2, sets: [2, 0],+ },+ },+ ],+ meta: { count: 1, limit: 5, offset: 0 },+};++let mockResponse = liveResponse;++vi.mock('@/utils/request', () => {+ const fn = vi.fn(() => Promise.resolve({ data: mockResponse }));+ fn.get = fn; fn.post = fn; fn.put = fn;+ return { default: fn };+});+vi.mock('@/utils/logging/ErrorHandler', () => ({ default: vi.fn() }));++/* WidgetBase always passes these through, so mirror it for a realistic mount */+const baseOptions = {+ timeout: null, ignoreErrors: false, label: null, useProxy: false, updateInterval: null,+};++/** Mount LiveTennis with the given options, stubbing the global tooltip directive */+function mountWidget(options = {}) {+ return shallowMount(LiveTennis, {+ props: { options: { ...baseOptions, apiKey: 'twjp_test', ...options } },+ global: { directives: { tooltip: {} } },+ });+}++describe('LiveTennis widget', () => {+ let wrapper;+ afterEach(() => {+ mockResponse = liveResponse;+ if (wrapper) wrapper.unmount();+ });++ it('renders a block per match, with a row per player', async () => {+ wrapper = mountWidget();+ await flushPromises();+ expect(wrapper.findAll('.match')).toHaveLength(1);+ expect(wrapper.findAll('.player')).toHaveLength(2);+ expect(wrapper.text()).toContain('Matthew Dellavedova');+ expect(wrapper.text()).toContain('Hayden Jones');+ });++ it('shows the tournament, round and a live status label', async () => {+ wrapper = mountWidget();+ await flushPromises();+ expect(wrapper.find('.tournament').text()).toBe('M15 Brisbane');+ expect(wrapper.find('.round').text()).toBe('M15 Brisbane - 1/16-finals');+ expect(wrapper.find('.status').text()).toBe('Live');+ expect(wrapper.find('.status').classes()).toContain('status-live');+ });++ it('renders per-set game scores for both players', async () => {+ wrapper = mountWidget();+ await flushPromises();+ const rows = wrapper.findAll('.player');+ const setsOf = (row) => row.findAll('.set').map((s) => s.text());+ expect(setsOf(rows[0])).toEqual(['7', '1']);+ expect(setsOf(rows[1])).toEqual(['5', '0']);+ });++ it('marks the set in progress as current', async () => {+ wrapper = mountWidget();+ await flushPromises();+ const sets = wrapper.findAll('.player')[0].findAll('.set');+ expect(sets[0].classes()).not.toContain('current');+ expect(sets[1].classes()).toContain('current');+ });++ it('flags the serving player, and only that player', async () => {+ wrapper = mountWidget();+ await flushPromises();+ const rows = wrapper.findAll('.player');+ // The fixture has server: 2, so p2 (the second row) is serving+ expect(rows[0].classes()).not.toContain('serving');+ expect(rows[1].classes()).toContain('serving');+ });++ it('shows current game points for a live match', async () => {+ wrapper = mountWidget();+ await flushPromises();+ const points = wrapper.findAll('.points').map((p) => p.text());+ expect(points).toEqual(['40', '15']);+ });++ it('shows rankings, and hides them when hideRankings is set', async () => {+ wrapper = mountWidget();+ await flushPromises();+ expect(wrapper.find('.ranking').text()).toBe('#310');+ wrapper.unmount();++ wrapper = mountWidget({ hideRankings: true });+ await flushPromises();+ expect(wrapper.find('.ranking').exists()).toBe(false);+ });++ it('handles an upcoming match, which has a null score', async () => {+ mockResponse = upcomingResponse;+ wrapper = mountWidget({ status: 'upcoming' });+ await flushPromises();+ expect(wrapper.findAll('.player')).toHaveLength(2);+ expect(wrapper.find('.status').text()).toBe('Upcoming');+ // No score means no set columns and no points shown+ expect(wrapper.findAll('.set')).toHaveLength(0);+ expect(wrapper.findAll('.points')).toHaveLength(0);+ });++ it('bolds the winner only once a match is completed', async () => {+ mockResponse = completedResponse;+ wrapper = mountWidget({ status: 'completed' });+ await flushPromises();+ const rows = wrapper.findAll('.player');+ expect(rows[0].classes()).toContain('winner');+ expect(rows[1].classes()).not.toContain('winner');+ // A finished match shows no in-progress point score+ expect(wrapper.findAll('.points')).toHaveLength(0);+ });++ it('does not show a serve indicator on a finished match', async () => {+ mockResponse = completedResponse;+ wrapper = mountWidget({ status: 'completed' });+ await flushPromises();+ // The API keeps the last server (2) on a completed match; nobody is serving now+ expect(wrapper.findAll('.player.serving')).toHaveLength(0);+ expect(wrapper.find('.serve-indicator').text()).toBe('');+ });++ it('does not mark a set leader as the winner while still live', async () => {+ wrapper = mountWidget();+ await flushPromises();+ // p1 leads the live fixture 1-0 on sets, but has not won it+ expect(wrapper.findAll('.player')[0].classes()).not.toContain('winner');+ });++ it('shows an empty state when no matches are in play', async () => {+ mockResponse = { data: [], meta: { count: 0 } };+ wrapper = mountWidget();+ await flushPromises();+ expect(wrapper.find('.no-matches').text()).toBe('No live matches');+ expect(wrapper.findAll('.match')).toHaveLength(0);+ });++ it('tolerates a malformed response without throwing', async () => {+ mockResponse = {};+ wrapper = mountWidget();+ await flushPromises();+ expect(wrapper.findAll('.match')).toHaveLength(0);+ });++ describe('configuration', () => {+ it('builds the endpoint from status and limit', () => {+ wrapper = mountWidget({ status: 'upcoming', limit: 3 });+ expect(wrapper.vm.endpoint).toBe(+ 'https://api.livetennisapi.com/api/public/v1/matches?status=upcoming&limit=3',+ );+ });++ it('defaults to 5 live matches', () => {+ wrapper = mountWidget();+ expect(wrapper.vm.status).toBe('live');+ expect(wrapper.vm.limit).toBe(5);+ });++ it('falls back to live for an unrecognised status', () => {+ wrapper = mountWidget({ status: 'nonsense' });+ expect(wrapper.vm.status).toBe('live');+ });++ it('sends the api key as a bearer token', () => {+ wrapper = mountWidget({ apiKey: 'twjp_abc' });+ expect(wrapper.vm.headers).toEqual({ Authorization: 'Bearer twjp_abc' });+ });++ it('refreshes every 60s by default, to stay inside the free rate limit', () => {+ wrapper = mountWidget();+ expect(wrapper.vm.updateInterval).toBe(60000);+ });++ it('errors, and makes no request, when the apiKey is missing', async () => {+ const request = (await import('@/utils/request')).default;+ request.mockClear();+ wrapper = shallowMount(LiveTennis, {+ props: { options: { ...baseOptions } },+ global: { directives: { tooltip: {} } },+ });+ await flushPromises();+ expect(request).not.toHaveBeenCalled();+ expect(wrapper.emitted().error).toBeTruthy();+ });+ });+});