Add goal progress bar to donate form and [streamgoals_progress] shortcode
Test and Release / test (push) Successful in 1m17s
Test and Release / release (push) Successful in 13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 17:48:37 -08:00
1 parent 353f7ca5be
commit b80010f422
7 files changed
+397 -9

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
use StreamGoals\Core\GoalTargetPolicy;
use StreamGoals\Tiers\TierPolicy;
/**
* Pure, WordPress-free public progress view for the donate form / [streamgoals_progress] / GET /progress.
* Numbers come from Payloads::goal() so they match the overlay exactly. Public-safe fields only (no donor data).
*/
final class Progress {
/** Parse a shortcode yes/no attribute. Unknown or empty values fall back to $default. */
public static function flag( mixed $raw, bool $default ): bool {
if ( is_bool( $raw ) ) {
return $raw;
}
if ( is_array( $raw ) || null === $raw ) {
return $default;
}
$v = strtolower( trim( (string) $raw ) );
if ( in_array( $v, array( 'yes', 'true', '1', 'on' ), true ) ) {
return true;
}
if ( in_array( $v, array( 'no', 'false', '0', 'off' ), true ) ) {
return false;
}
return $default;
}
/**
* @param array<string,mixed> $goal sg_goals row
* @param array<int,array<string,mixed>>|null $tiers raw sg_goal_tiers rows
* @return array{goal_id:int,title:string,currency:string,raised_minor:int,target_minor:int,percent:int,raised_display:string,target_display:string,reached:bool,tier:?array}
*/
public static function payload( array $goal, int $raised, ?array $tiers = null ): array {
$g = Payloads::goal( $goal, $raised, $tiers ?: null );
$tier = null;
$reached = GoalTargetPolicy::isClosedAtTarget( $goal );
if ( isset( $g['tiers'] ) ) {
$cur = $g['tiers']['current'];
if ( null !== $cur ) {
$tier = array(
'index' => (int) $g['tiers']['index'],
'count' => (int) $g['tiers']['count'],
'title' => (string) $cur['title'],
'target_minor' => (int) $cur['target_minor'],
'target_display' => (string) $cur['target_display'],
);
}
$reached = $reached || ! empty( $g['tiers']['all_reached'] );
} else {
$reached = $reached || ( $g['target_minor'] > 0 && $g['raised_minor'] >= $g['target_minor'] );
}
return array(
'goal_id' => (int) ( $goal['id'] ?? 0 ),
'title' => $g['title'],
'currency' => $g['currency'],
'raised_minor' => $g['raised_minor'],
'target_minor' => $g['target_minor'],
'percent' => $reached ? 100 : $g['percent'],
'raised_display' => $g['raised_display'],
'target_display' => $g['target_display'],
'reached' => $reached,
'tier' => $tier,
);
}
/**
* Server-rendered bar (the JS updates this same markup in place). Labels are already translated.
*
* @param array<string,string> $labels reached, of (%1$s raised, %2$s target), tier (%1$s name, %2$s target), label (%s title)
*/
public static function html( array $p, array $labels ): string {
$e = static fn( string $s ): string => htmlspecialchars( $s, ENT_QUOTES, 'UTF-8' );
$pct = max( 0, min( 100, (int) $p['percent'] ) );
$sub = static fn( string $tpl, array $v ): string => (string) preg_replace_callback( '/%(\d)\$s/', static fn( array $m ): string => $v[ (int) $m[1] - 1 ] ?? '', $tpl );
$of = $sub( $labels['of'] ?? '%1$s / %2$s', array( $p['raised_display'], $p['target_display'] ) );
$out = '<div class="sg-progress' . ( $p['reached'] ? ' sg-progress-reached' : '' ) . '" data-goal="' . (int) $p['goal_id'] . '">';
$out .= '<div class="sg-progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' . $pct . '"'
. ' aria-valuetext="' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : $of . ' (' . $pct . '%)' ) . '"'
. ' aria-label="' . $e( str_replace( '%s', (string) $p['title'], $labels['label'] ?? '%s' ) ) . '">'
. '<span class="sg-progress-fill" style="width:' . $pct . '%"></span></div>';
$out .= '<div class="sg-progress-text"><span class="sg-progress-amounts">' . $e( $of ) . '</span> <span class="sg-progress-pct">' . $pct . '%</span></div>';
$out .= '<p class="sg-progress-tier"' . ( $p['tier'] ? '' : ' hidden' ) . '>'
. ( $p['tier'] ? $e( $sub( $labels['tier'] ?? '%1$s (%2$s)', array( $p['tier']['title'], $p['tier']['target_display'] ) ) ) : '' ) . '</p>';
$out .= '<p class="sg-progress-done"' . ( $p['reached'] ? '' : ' hidden' ) . '>' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : '' ) . '</p>';
return $out . '</div>';
}
}
+91 -4
View File
@@ -6,6 +6,7 @@ namespace StreamGoals\Rest;
use StreamGoals\Core\GoalTargetPolicy;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
use StreamGoals\Overlay\Progress;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
@@ -27,6 +28,7 @@ final class DonateController {
public static function register(): void {
add_action( 'rest_api_init', array( self::class, 'routes' ) );
add_shortcode( 'streamgoals_donate', array( self::class, 'shortcode' ) );
add_shortcode( 'streamgoals_progress', array( self::class, 'progress_shortcode' ) );
}
public static function routes(): void {
@@ -57,10 +59,35 @@ final class DonateController {
'permission_callback' => '__return_true',
)
);
register_rest_route(
self::NS,
'/progress',
array(
'methods' => 'GET',
'callback' => array( self::class, 'progress_route' ),
'permission_callback' => '__return_true',
'args' => array( 'goal' => array( 'sanitize_callback' => 'absint' ) ),
)
);
}
/* ---------------------------------------------------------------- REST */
/** Public, read-only totals for the progress bar. Whitelisted goal figures only; never donor data. */
public static function progress_route( \WP_REST_Request $req ) {
if ( $limited = self::limit( 'progress', 60, 60 ) ) {
return $limited;
}
$goal = DonationStore::goal( (int) $req->get_param( 'goal' ) );
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) );
}
$res = rest_ensure_response( self::progress_for( $goal ) );
// Short shared cache lets a CDN collapse bursts; the page JS adds a cache-busting parameter after a donation.
$res->header( 'Cache-Control', 'public, max-age=10, s-maxage=10' );
return $res;
}
public static function create_order( \WP_REST_Request $req ) {
if ( $limited = self::limit( 'order', 10, 300 ) ) {
return $limited;
@@ -159,8 +186,9 @@ final class DonateController {
/* ----------------------------------------------------------- Shortcode */
public static function shortcode( $atts ): string {
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_donate' );
$atts = shortcode_atts( array( 'goal' => '', 'show_progress' => 'yes' ), (array) $atts, 'streamgoals_donate' );
$pinned = (int) $atts['goal'];
$showP = Progress::flag( $atts['show_progress'], true );
$s = Settings::all();
if ( '' === (string) $s['paypal_client_id'] ) {
return '<p class="sg-donate-unavailable">' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '</p>';
@@ -179,13 +207,15 @@ final class DonateController {
'currency' => strtoupper( (string) $g['currency'] ),
'exp' => Money::exponent( (string) $g['currency'] ),
'actions' => $actions[ (int) $g['id'] ] ?? array(),
);
) + ( $showP ? array( 'progress' => self::progress_for( $g ) ) : array() );
}
if ( ! $goals ) {
$reached = $pinned ? DonationStore::goal( $pinned ) : null;
$reached = $pinned ? ( $reached && GoalTargetPolicy::isClosedAtTarget( $reached ) ) : (bool) DonationStore::reached_goals();
if ( $reached ) {
return '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '</p>';
$rg = $pinned ? DonationStore::goal( $pinned ) : ( DonationStore::reached_goals()[0] ?? null );
$bar = ( $showP && $rg ) ? self::progress_markup( self::progress_for( $rg ) ) : '';
return $bar . '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '</p>';
}
return '<p class="sg-donate-unavailable">' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '</p>';
}
@@ -231,11 +261,68 @@ final class DonateController {
);
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsDonate=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"></div>';
self::enqueue_progress();
$first = $showP ? $goals[0]['progress'] : null;
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"' . ( $showP ? ' data-progress="1"' : '' ) . '>'
. ( $first ? self::progress_markup( $first ) : '' ) . '</div>';
}
/** [streamgoals_progress goal=""]: the same bar without the form. Server-rendered; JS refreshes it. */
public static function progress_shortcode( $atts ): string {
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_progress' );
$id = (int) $atts['goal'];
$goal = $id ? DonationStore::goal( $id ) : ( DonationStore::active_goals()[0] ?? ( DonationStore::reached_goals()[0] ?? null ) );
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
return '';
}
self::enqueue_progress();
return '<div class="sg-donate sg-progress-only">' . self::progress_markup( self::progress_for( $goal ) ) . '</div>';
}
/* ------------------------------------------------------------- Helpers */
/** @return array<string,mixed> Progress::payload() for a goal row (same raised basis and tiers as the overlay). */
private static function progress_for( array $goal ): array {
global $wpdb;
$id = (int) $goal['id'];
$tiers = array();
try {
$tiers = ( new \StreamGoals\Tiers\TierRepository( $wpdb ) )->forGoal( $id );
} catch ( \Throwable $e ) {
$tiers = array();
}
return Progress::payload( $goal, ( new \StreamGoals\Overlay\WpdbDataSource() )->raisedMinor( $goal ), $tiers ?: null );
}
private static function progress_i18n(): array {
return array(
'reached' => __( 'Goal reached', 'streamgoals-donate' ),
/* translators: 1: formatted amount raised, 2: formatted target */
'of' => __( '%1$s of %2$s', 'streamgoals-donate' ),
/* translators: 1: current tier name, 2: formatted tier target */
'tier' => __( 'Current tier: %1$s (target %2$s)', 'streamgoals-donate' ),
/* translators: %s: goal title */
'label' => __( 'Progress towards %s', 'streamgoals-donate' ),
);
}
private static function progress_markup( array $p ): string {
return Progress::html( $p, self::progress_i18n() );
}
/** Enqueue assets and the (once per page) config the bar's JS needs. */
private static function enqueue_progress(): void {
static $done = false;
wp_enqueue_style( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.css', array(), STREAMGOALS_VERSION );
wp_enqueue_script( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.js', array(), STREAMGOALS_VERSION, true );
if ( $done ) {
return;
}
$done = true;
$cfg = array( 'restUrl' => esc_url_raw( rest_url( self::NS ) ), 'i18n' => self::progress_i18n(), 'pollMs' => 30000 );
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsProgress=' . wp_json_encode( $cfg, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
}
/**
* "Next unlock" hint for a tiered goal: the current (first unreached) tier's title and the amount still needed, in minor units.
* Null for goals without tiers or with every tier reached. Computed when the page renders.