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
5 changes: 5 additions & 0 deletions .env.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
# LocalWP: yoursite.local, Lando: yoursite.lndo.site, wp-env: localhost, WP Studio: localhost
WP_HOST=yoursite.local

# HMR / BrowserSync live reload master switch (default: on). Honoured by both
# the build (BrowserSync server) and PHP (client enqueue). Set to false to fully
# disable live reload. Off values: 0, false, no, off. Toggle from `npm run init`.
ENABLE_HMR=true

# BrowserSync port. Default: 3001. Change if port 3001 is already in use.
# Both the build and PHP read this value directly, so changing it here is
# enough. Define ELEMENTARY_THEME_BROWSER_SYNC_URL only to override the full
Expand Down
55 changes: 55 additions & 0 deletions bin/scaffold.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,63 @@ module.exports = {
onDisable: ( api ) => api.setDefine( tailwindEntry( api ), tailwindConst( api ), false ),
detect: ( api ) => true === api.readDefine( tailwindEntry( api ), tailwindConst( api ) ),
},
{
key: 'hmr',
label: 'HMR (BrowserSync live reload)',
description: 'Live reload in watch mode. Toggling flips ENABLE_HMR in .env.local, which webpack (BrowserSync server) and PHP (client enqueue) both honour. Default on; deps stay installed.',
// No files or deps: the code lives in webpack.config.js + Assets.php
// permanently and is gated on the flag. detect reads the live flag,
// defaulting on when .env.local (gitignored) has no ENABLE_HMR.
onEnable: ( api ) => api.setEnv( '.env.local', 'ENABLE_HMR', 'true' ),
onDisable: ( api ) => api.setEnv( '.env.local', 'ENABLE_HMR', 'false' ),
detect: ( api ) => {
const value = api.readEnv( '.env.local', 'ENABLE_HMR' );
return null === value || ! [ 'false', '0', 'no', 'off' ].includes( value.toLowerCase() );
},
},
],

// First-run "which example sets to remove?" prompt. The three module groups
// share inc/Main.php, so each scopes its own region with a keyed marker
// (wp:example:<key>); components and patterns are delete-only (auto-discovered,
// nothing to strip). Markers are stripped either way; code/files drop on remove.
examples: {
marker: 'wp:example',
groups: [
{
key: 'block-extension',
label: 'Media-text block extension',
marker: 'wp:example:block-extension',
strip: [ 'inc/Main.php' ],
remove: [ 'inc/Modules/BlockExtensions', 'patterns/media-text-interactive.php', 'src/js/frontend/modules/media-text.js' ],
},
{
key: 'settings',
label: 'Theme options settings page',
marker: 'wp:example:settings',
strip: [ 'inc/Main.php' ],
remove: [ 'inc/Modules/Settings' ],
},
{
key: 'shortcode',
label: 'Author bio shortcode',
marker: 'wp:example:shortcode',
strip: [ 'inc/Main.php' ],
remove: [ 'inc/Modules/Shortcodes', 'tests/php/inc/Modules/Shortcodes' ],
},
{
key: 'components',
label: 'Example components (button, card)',
remove: [ 'src/components/button', 'src/components/card' ],
},
{
key: 'patterns',
label: 'Page-creation pattern',
remove: [ 'patterns/page-creation-pattern.php' ],
},
],
},

cleanup: { targets: [ '.github', 'languages' ] },

docsUrl: 'https://github.com/rtCamp/theme-elementary/blob/main/README.md',
Expand Down
18 changes: 15 additions & 3 deletions docs/hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,15 +134,27 @@ This is required to avoid mixed content errors — the BrowserSync client script

## Advanced

### Disabling BrowserSync
### Enabling / disabling HMR

To disable BrowserSync without removing it from the webpack config, set this in `.env.local`:
HMR (BrowserSync live reload) is controlled by a single master switch in `.env.local`, honoured by both the build (BrowserSync server) and PHP (client enqueue):

```
ENABLE_HMR=false
```

Default is on — the key only needs setting to turn HMR off. Off values are `0`, `false`, `no`, and `off` (case-insensitive). With it off, `npm start` skips the BrowserSync server entirely and PHP skips the client, so there is no live reload and no console noise from a client pointing at a server that isn't running. The `browser-sync` dev dependencies stay installed, so flipping it back on needs no reinstall.

You can also toggle it from `npm run init` (manage mode → Toggle features → HMR), which just flips `ENABLE_HMR` in `.env.local` for you. Since `.env.local` is gitignored, this is a per-developer local setting.

### Disabling the BrowserSync client only

To keep the BrowserSync server running but stop PHP from enqueuing its client (e.g. when working purely in the block editor), set this in `.env.local`:

```
DISABLE_BS=true
```

This prevents PHP from enqueuing the BrowserSync client script. The BrowserSync server still starts (webpack still runs it), but the browser won't connect to it. Useful when working purely in the block editor and you don't want the BrowserSync client loading on the frontend.
This prevents PHP from enqueuing the BrowserSync client script. The BrowserSync server still starts (webpack still runs it), but the browser won't connect to it. For a full off switch (server included), use `ENABLE_HMR=false` above.

### Overriding the BrowserSync client URL

Expand Down
40 changes: 38 additions & 2 deletions inc/Core/Assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public function enqueue_assets(): void {
* @action wp_enqueue_scripts
*/
public function enqueue_browser_sync(): void {
if ( 'local' !== wp_get_environment_type() || $this->is_browser_sync_disabled() ) {
if ( 'local' !== wp_get_environment_type() || ! $this->is_hmr_enabled() || $this->is_browser_sync_disabled() ) {
return;
}
Comment on lines 146 to 149

Expand Down Expand Up @@ -188,6 +188,29 @@ private function get_browser_sync_port(): int {
return $default;
}

/**
* Whether HMR (BrowserSync live reload) is enabled via ENABLE_HMR in .env.local.
*
* Master switch for both sides: webpack only starts the BrowserSync server,
* and PHP only enqueues its client, when this is on. Defaults ON when the key
* is absent. Off values are `0`, `false`, `no`, and `off` (case-insensitive).
* DISABLE_BS still works as a finer client-only override. Toggle it from
* `npm run init` (manage mode) or by editing .env.local directly.
*
* THIS METHOD IS INTENDED FOR LOCAL DEVELOPMENT ENVIRONMENTS ONLY.
*
* @return bool True when HMR is enabled.
*/
private function is_hmr_enabled(): bool {
$value = $this->get_env_value( 'ENABLE_HMR' );

if ( null === $value ) {
return true;
}

return ! in_array( strtolower( $value ), [ '0', 'false', 'no', 'off' ], true );
}

/**
* Whether BrowserSync is disabled via DISABLE_BS in .env.local.
*
Expand Down Expand Up @@ -223,7 +246,7 @@ private function is_browser_sync_disabled(): bool {
* @return string|null The value, or null when not found.
*/
private function get_env_value( string $key ): ?string {
$env_file = $this->base_dir . '.env.local';
$env_file = $this->env_file_path();

if ( ! is_readable( $env_file ) ) {
return null;
Expand All @@ -242,4 +265,17 @@ private function get_env_value( string $key ): ?string {

return null;
}

/**
* Absolute path to the .env.local file read for local-dev flags.
*
* Isolated into its own method so tests can point the env lookup at a
* throwaway temp file (via a subclass) instead of touching the developer's
* real .env.local.
*
* @return string Absolute path to .env.local in the theme root.
*/
protected function env_file_path(): string {
return $this->base_dir . '.env.local';
}
}
16 changes: 15 additions & 1 deletion inc/Main.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@

use rtCamp\WPFramework\Contracts\Traits\{Singleton, Loader};
use rtCamp\Theme\Elementary\Core\{Assets, Components, Encryption, Menu, Templates, ThemeSetup};
use rtCamp\Theme\Elementary\Modules\{BlockExtensions\MediaTextInteractive, Settings\ThemeOptions, Shortcodes\AuthorBio};
// wp:example:block-extension
use rtCamp\Theme\Elementary\Modules\BlockExtensions\MediaTextInteractive;
// wp:example:block-extension:end
// wp:example:settings
use rtCamp\Theme\Elementary\Modules\Settings\ThemeOptions;
// wp:example:settings:end
// wp:example:shortcode
use rtCamp\Theme\Elementary\Modules\Shortcodes\AuthorBio;
// wp:example:shortcode:end

/**
* Class Main
Expand All @@ -33,9 +41,15 @@ class Main {
Components::class,
Templates::class,
Encryption::class,
// wp:example:block-extension
MediaTextInteractive::class,
// wp:example:block-extension:end
// wp:example:settings
ThemeOptions::class,
// wp:example:settings:end
// wp:example:shortcode
AuthorBio::class,
// wp:example:shortcode:end
];

/**
Expand Down
7 changes: 7 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@
<exclude-pattern>tests/*</exclude-pattern>
</rule>

<!-- The wp:example:* region markers in inc/Main.php are intentional scaffold tags
(stripped by `npm run init`), not prose comments, so exempt just those lines
from the inline-comment end-char rule. -->
<rule ref="Squiz.Commenting.InlineComment.InvalidEndChar">
<exclude-pattern>inc/Main.php</exclude-pattern>
</rule>

<rule ref="WordPress-VIP-Go">
<exclude-pattern>tests/*</exclude-pattern>
</rule>
Expand Down
152 changes: 152 additions & 0 deletions tests/php/inc/Core/AssetsHmrTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php
/**
* Test the HMR / BrowserSync gating in the Assets class.
*
* @package rtCamp\Theme\Elementary
*/

declare( strict_types = 1 );

use rtCamp\Theme\Elementary\Tests\TestCase;
use rtCamp\Theme\Elementary\Core\Assets;

/**
* Class AssetsHmrTest
*
* Covers is_hmr_enabled() (the ENABLE_HMR master switch) and
* is_browser_sync_disabled() (the independent DISABLE_BS override). Both read
* the env file resolved by Assets::env_file_path(); the suite overrides that
* seam to a throwaway temp file (one per test), so it never touches — or
* depends on — the developer's real .env.local.
*
* @since 1.0.0
*/
class AssetsHmrTest extends TestCase {

/**
* Absolute path to this test's throwaway env file.
*
* @var string
*/
private string $env_file = '';

/**
* Point each test at its own temp env file, starting from a clean slate.
*/
public function set_up(): void {
parent::set_up();

// Unique per test (parallel-safe); start with no file so defaults apply.
$this->env_file = tempnam( sys_get_temp_dir(), 'elementary-hmr-env-' );
$this->clear_env();
Comment thread
Adi-ty marked this conversation as resolved.
}

/**
* Remove the temp env file.
*/
public function tear_down(): void {
$this->clear_env();

parent::tear_down();
}

/**
* Delete the temp env file if present.
*/
private function clear_env(): void {
if ( file_exists( $this->env_file ) ) {
unlink( $this->env_file );
}
}

/**
* Write a single KEY=value line to the temp env file.
*
* @param string $key Variable name.
* @param string $value Value.
*/
private function write_env( string $key, string $value ): void {
file_put_contents( $this->env_file, "{$key}={$value}\n" );
}

/**
* Invoke a private Assets method on a fresh instance whose env-file lookup
* is redirected to this test's temp file.
*
* @param string $method Method name.
*
* @return mixed Return value.
*/
private function invoke( string $method ) {
$assets = new class( $this->env_file ) extends Assets {
/**
* Path returned by env_file_path().
*
* @var string
*/
private string $test_env_file;

/**
* Capture the throwaway env file, then build a normal Assets.
*
* @param string $env_file Throwaway env file to read instead of .env.local.
*/
public function __construct( string $env_file ) {
$this->test_env_file = $env_file;
parent::__construct();
}

/**
* Redirect the env lookup to the test's temp file.
*
* @return string
*/
protected function env_file_path(): string {
return $this->test_env_file;
}
};

// Private parent methods are invocable on the subclass instance;
// setAccessible() is a no-op (and deprecated) on PHP 8.1+, so it is omitted.
$ref = new \ReflectionMethod( Assets::class, $method );

return $ref->invoke( $assets );
}

/**
* HMR is on when ENABLE_HMR is absent.
*/
public function test_hmr_enabled_by_default(): void {
$this->assertTrue( $this->invoke( 'is_hmr_enabled' ) );
}

/**
* Off values switch HMR off.
*/
public function test_hmr_disabled_for_off_values(): void {
foreach ( [ 'false', '0', 'no', 'off', 'OFF' ] as $value ) {
$this->write_env( 'ENABLE_HMR', $value );
$this->assertFalse( $this->invoke( 'is_hmr_enabled' ), "ENABLE_HMR={$value}" );
}
}

/**
* Anything else keeps HMR on.
*/
public function test_hmr_enabled_for_on_values(): void {
foreach ( [ 'true', '1', 'yes', 'on' ] as $value ) {
$this->write_env( 'ENABLE_HMR', $value );
$this->assertTrue( $this->invoke( 'is_hmr_enabled' ), "ENABLE_HMR={$value}" );
}
}

/**
* DISABLE_BS is independent of HMR: off by default, on for truthy values.
*/
public function test_disable_bs_is_independent(): void {
$this->assertFalse( $this->invoke( 'is_browser_sync_disabled' ) );

$this->write_env( 'DISABLE_BS', 'true' );
$this->assertTrue( $this->invoke( 'is_browser_sync_disabled' ) );
}
}
9 changes: 8 additions & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ if ( isWatch ) {
require( 'dotenv' ).config( { path: '.env.local', quiet: true } );
}

// HMR (BrowserSync) master switch read from .env.local (ENABLE_HMR), defaulting
// on; only an explicit off value disables it. Mirrors is_hmr_enabled() in
// inc/Core/Assets.php so one flag controls both the BrowserSync server (here)
// and its client enqueue (PHP).
const hmrFlag = String( process.env.ENABLE_HMR || '' ).toLowerCase();
const isHmrEnabled = ! [ 'false', '0', 'no', 'off' ].includes( hmrFlag );

const DEFAULT_BS_PORT = 3001;

/**
Expand Down Expand Up @@ -471,7 +478,7 @@ const getCopyPlugin = () =>
* @return {Array} BrowserSync plugin instances.
*/
const getBrowserSyncPlugins = () => {
if ( ! isWatch ) {
if ( ! isWatch || ! isHmrEnabled ) {
return [];
}

Expand Down
Loading