Skip to content

Commit

Permalink
Add expose method
Browse files Browse the repository at this point in the history
  • Loading branch information
bencroker committed Dec 17, 2024
1 parent 8c5b603 commit 886e622
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Datastar.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
namespace putyourlightson\datastar;

use Craft;
use craft\web\View;
use nystudio107\autocomplete\events\DefineGeneratorValuesEvent;
use nystudio107\autocomplete\generators\AutocompleteTwigExtensionGenerator;
use putyourlightson\datastar\assets\DatastarAssetBundle;
Expand All @@ -27,6 +28,11 @@ class Datastar extends Module
*/
public const ID = 'datastar-module';

/**
* The URL of the script to expose, if one was registered.
*/
private ?string $exposeScriptUrl = null;

/**
* The module settings.
*/
Expand Down Expand Up @@ -71,6 +77,19 @@ public function init(): void
$this->registerAutocompleteEvent();
}

/**
* Expose the Datastar object by attaching it to the `window` element.
*/
public function expose(): void
{
if ($this->exposeScriptUrl !== null) {
Craft::$app->getView()->registerScript('import { Datastar } from "' . $this->exposeScriptUrl . '"; window.Datastar = Datastar', View::POS_END, ['type' => 'module']);

// Set to `null` so that it can only happen once.
$this->exposeScriptUrl = null;
}
}

public function getSettings(): SettingsModel
{
if ($this->_settings === null) {
Expand Down Expand Up @@ -103,6 +122,8 @@ private function registerScript(): void
// Register the JS file explicitly so that it will be output when using template caching.
$url = Craft::$app->getView()->getAssetManager()->getAssetUrl($bundle, $bundle->js[0]);
Craft::$app->getView()->registerJsFile($url, $bundle->jsOptions);

$this->exposeScriptUrl = $url;
}

private function registerAutocompleteEvent(): void
Expand Down

0 comments on commit 886e622

Please sign in to comment.