MongoDB query with Mongoose – Matching subdocument attribute within an array

I am trying to solve an issue with the format of documents in a MongoDB depicted below.

{
  "_id": {
    "$oid": "68dc4f78e11553b3647231e2"
  },
  "name": "Dutch Bros",
  "address": "25 Down Street, Salt Lake City, UT",
  "facilities": [
    "Hot drinks",
    "Food"
  ],
  "coords": [
    -0.9690884,
    51.455041
  ],
  "reviews": [
    {
      "author": "John Smith",
      "rating": {
        "$numberDecimal": "5"
      },
      "createdOn": {
        "$date": "2025-09-30T06:00:00.000Z"
      },
      "reviewText": "Great Place. Would come back again!"
    },
    {
      "author": "Jane Doe",
      "rating": {
        "$numberDecimal": "4"
      },
      "createdOn": {
        "$date": "2025-09-30T06:00:00.000Z"
      },
      "reviewText": "Okay Place. Would come back again!"
    }
  ]
}

My goal is to match review sub-document(s) based on an attribute it has such as ratings being equal to five. I know that I could take the reviews array as a whole and iterate over them to search the attributes for what I need, but I want to be able to find it directly in the MongoDB query so the MongoDB server does the work while it saves my express server any additional workload.

I guess what I am asking is how do I reference the iterable objects in the reviews array. I hope that was clear enough and I apologize if it wasn’t!

I’ve successfully implemented a version that iterates in a for loop on the express server in the controller, but this is what I want to avoid. I’ve also tried using a .get() method on the returned array because I saw that it was an available method for the object, but that yielded an error. I’ve also tried to build a query which was close to what I believe the solution is going to be but I can’t understand how MongoDB element matches an array item, see below for my failed attempt.

const monReview = await Loc
            .findById(req.params.locationid)
            .select('name reviews')
            .where('reviews')
            .elemMatch({$eq: req.params.reviewRating})
            .exec();  

Update total in Stripe payments upon shipping rate change (Amazon, Google Pay etc)

Here is some infromation about shippingratechange for Stripe express checkout.
https://docs.stripe.com/js/elements_object/express_checkout_element_shippingratechange_event

which implemented and when the Stripe payment button is clicked the modal window properly displayed:
enter image description here

Then, as you see on the image, there are several shipping options properly passed and rendered. Once another shipping option (with another price) is chosen, it triggers ‘shippingratechange’. How to update the Total because the shipping price was changed?

When I change the shipping option, it changes fine, but the Total remains unchanged, although shippingratechange gets triggered with no questions. How to set another totals value, for example 99.90 (let’s say the math calculated).

What should be added to here?

expressCheckoutElement.on('shippingratechange', function(event) {
  var resolve = event.resolve;
  var shippingRate = event.shippingRate;
  // handle shippingratechange event

  // define payload and pass it into resolve
  var payload = {
    shippingRates: [
      shippingRate
    ]
  };

  // call event.resolve within 20 seconds
  resolve(payload);
});

Why does a small React dynamic import file (~3.7 KB) take 650 ms on first load but only 45 ms on refresh with AWS S3 + CloudFront?

I have a React app deployed on AWS S3 + CloudFront.

One of my routes uses a dynamic import (import()), and the corresponding JS chunk is very small (~3.7 KB).

On the first load, the request for this file takes about 650 ms, but if I refresh the page immediately afterward, it only takes about 45 ms.

Here’s the request and response details from Chrome DevTools for the file:

Request URL: https://admin.simprosysapis.com/assets/RolesList-DVgRFD0k.js
Request Method: GET
Status Code: 200 OK
Remote Address: 18.66.57.77:443
Referrer Policy: strict-origin-when-cross-origin

Response headers

cache-control: max-age=3600, must-revalidate
content-encoding: br
content-type: text/javascript
server: SimprosysAPI
via: 1.1 ...cloudfront.net (CloudFront)
x-cache: Miss from cloudfront

Request headers

accept-encoding: gzip, deflate, br, zstd
cache-control: no-cache
pragma: no-cache
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...

My questions

  1. Why does a 3.7 KB file take ~650 ms to load the first time?

    • Is this mostly TLS/handshake + CloudFront latency rather than file size?
    • Is the x-cache: Miss from cloudfront header responsible?
  2. Why does it become so much faster (~45 ms) on refresh?

    • Is the browser using disk/memory cache or a CloudFront cached copy?
  3. Is there a way to improve the first load time for these small dynamic chunks (e.g., preloading, prefetching, or CloudFront settings)?


What I tried

  • Checked headers: content-encoding: br confirms compression is working.
  • Cache headers look reasonable (max-age=3600).
  • Behavior is consistent across multiple builds.

Expected / Desired

I want to understand if this latency difference is normal for CloudFront + S3 dynamic imports, and whether I can optimize the first-load latency further.

How to achieve an “inset carved” gallery card effect inside an image container with CSS clip-path or masks? [closed]

Reference
my trial

I’m trying to replicate a hero section design where the gallery card looks like it is carved into the main image container (instead of floating on top).

I attempted using an SVG clipPath with an organic shape applied to the .main-image, but the gallery card still appears as a separate overlay. It doesn’t blend with the container as expected.

<div class="organic-gallery">
  <!-- Clip path definition -->
  <svg width="0" height="0">
    <defs>
      <clipPath id="organic-carved-shape" clipPathUnits="objectBoundingBox">
        <path d="M 0.06,0 L 0.94,0 C 0.97,0 1,0.03 1,0.06 L 1,0.94 C 1,0.97 0.97,1 0.94,1 L 0.7,1 C 0.68,1 0.66,0.998 0.64,0.995 L 0.05,0.82 C 0.02,0.815 0,0.8 0,0.78 L 0,0.06 C 0,0.03 0.03,0 0.06,0 Z" />
      </clipPath>
    </defs>
  </svg>

  <div class="gallery-container">
    <!-- Main image background -->
    <div class="main-image">
      <img src="circuit.jpg" class="circuit-bg" />
      
      <!-- floating labels -->
      <div class="feature-label" style="top: 3rem; right: 3rem;">On-Device Analysis</div>
      <div class="feature-label" style="top: 8rem; right: 6rem;">Smart App</div>
    </div>

    <!-- supposed to be carved into the main container -->
    <div class="gallery-card">
      <div class="gallery-images">
        <div class="gallery-item">Thumb 1</div>
        <div class="gallery-item">Thumb 2</div>
      </div>
    </div>
  </div>
</div>
.gallery-container {
  position: relative;
  height: 600px;
}

.main-image {
  position: absolute;
  inset: 0;
  border-radius: 3rem;
  overflow: hidden;
  clip-path: url(#organic-carved-shape);
}

.circuit-bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.gallery-card {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 380px;
  padding: 1.5rem;
  border-radius: 2rem;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(12px);
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}

Current result:
The gallery card simply overlaps the main image.

Expected result:
The gallery card should appear as if it’s part of (or cut into) the main container — following the same organic shape, not just sitting on top.

Question:
What’s the correct way (CSS clip-path, mask, pseudo-elements, or another technique) to make the gallery card look “carved into” the image container?

HTML Canvas lineTo() draws with incorrect y coordinates

Achieving clear lines in HTML canvas requires setting the CSS canvas height and width to be the canvas height and width / device pixel ratio:

this.element.style.height = this.element.height / dpr + "px";
this.element.style.height = this.element.height / dpr + "px";

An unfortunate outcome of this is that the lineTo command will now be incorrect. For example, if I draw a square as:

ctx.lineTo(113.395,54.233);
ctx.lineTo(120.791,54.233);
ctx.stroke();

ctx.lineTo(120.791,54.233);
ctx.lineTo(120.791,46.837);
ctx.stroke();

ctx.lineTo(120.791,46.837);
ctx.lineTo(113.395,46.837);
ctx.stroke();

ctx.lineTo(113.395,46.837);
ctx.lineTo(113.395,54.233);
ctx.stroke();

The result is not square:

enter image description here

Anti-aliasing aside, if we average the placement of each line to its darker side, the width is approximately 7px (correct), while the height is approximately 8px (incorrect).

Does anyone have a solution for this?

using polylang , how to move all the translation po files directly (using a plugin) instead of migrating them manually

HI I am working on a creating of a plugin where site is built using child of a classic theme In my site i am already using polylang (free) version now i tried to build a plugin

where I need to Ensure all French translations from the theme .po files are imported into the Polylang database automatically

Current status:I Manual conversion of _()/e() to pll()/pll_e() in the theme is done and working.

So Now i my requirement is to Create a one-time plugin to import existing .po translations into Polylang GUI/database.

The Purpose of it is to Avoid manual entry errors, reduce deployment downtime, and ensure translations work correctly in live/production.

Scope: Use existing .pot, .po, .mo files from the theme. No additional files are required. in my wp-contents/Language contain the theme and plugin folders where the all .po, .mo files are present

so on enabling this plugin all French translations must be verified and confirmed functional before task completion.

Also English strings may appear on French pages if the import is not done properly. The plugin is single-use, not continuous.

Requirement:
Create a one-time plugin that imports all French translations from theme .po files into Polylang’s database.

Site: child of a classic theme
Polylang (free) active
Manual conversion of _() / e() → pll() / pll_e() is already done
Goal: avoid manual errors, ensure translations work correctly in production
Plugin draft (current code):

<?php
/**
 * Plugin Name: Polylang French Translation Importer - DEBUG
 * Description: Debug version to import French translations from .po files into Polylang database
 * Version: 1.3
 * Author: Your Name
 */

if (!defined('ABSPATH')) exit;

class PolylangFrenchImporter {
    private $import_path;

    public function __construct() {
        $this->import_path = WP_CONTENT_DIR . '/languages/themes/';
        add_action('admin_menu', [$this, 'add_admin_page']);
    }

    public function add_admin_page() {
        add_management_page(
            'Polylang Import',
            'Polylang Import',
            'manage_options',
            'polylang-import',
            [$this, 'render_import_page']
        );
    }

    public function render_import_page() {
        if (isset($_POST['run_import'])) {
            $this->run_import();
        }

        echo '<div class="wrap"><h1>Polylang PO Import Debug</h1>';
        echo '<form method="post">';
        submit_button('Run Import', 'primary', 'run_import');
        echo '</form></div>';
    }

    private function run_import() {
        if (!function_exists('pll_get_the_language')) {
            echo '<p style="color:red;">Polylang not active!</p>';
            return;
        }

        require_once ABSPATH . 'wp-admin/includes/translation-install.php';

        $files = glob($this->import_path . '*.po');
        if (!$files) {
            echo '<p style="color:red;">No .po files found in: ' . esc_html($this->import_path) . '</p>';
            return;
        }

        foreach ($files as $file) {
            $locale = basename($file, '.po');
            echo '<h3>Processing: ' . esc_html($locale) . '</h3>';

            $translations = $this->parse_po_file($file);
            if (!$translations) {
                echo '<p style="color:red;">Failed to load PO file or no translations found.</p>';
                continue;
            }

            global $wpdb;
            $table = $wpdb->prefix . 'polylang_strings';

            $count = 0;
            foreach ($translations as $msgid => $msgstr) {
                if (!$msgid || !$msgstr) continue;

                $wpdb->insert($table, [
                    'string'  => $msgid,
                    'context' => 'theme',
                    'name'    => md5($msgid),
                    'value'   => $msgstr,
                    'group'   => 'po-import',
                    'multiline' => 0,
                ]);
                $count++;
            }

            echo '<p style="color:green;">Imported ' . intval($count) . ' strings from ' . esc_html($file) . '</p>';
        }
    }

    private function parse_po_file($file) {
        if (!class_exists('PO')) {
            require_once ABSPATH . 'wp-includes/pomo/po.php';
        }

        $po = new PO();
        $loaded = $po->import_from_file($file);
        if (!$loaded) {
            error_log('Failed to load PO file: ' . $file);
            return false;
        }

        $translations = [];
        foreach ($po->entries as $entry) {
            if (!empty($entry->translations[0])) {
                $translations[$entry->singular] = $entry->translations[0];
            }
        }

        error_log('Parsed ' . count($translations) . ' strings from ' . $file);
        return $translations;
    }
}

new PolylangFrenchImporter();
Error while testing:

PO files are detected (fr_CA.po, en_CA.po) ✅
But import_from_file fails → Failed to load PO file ❌
Results: Strings Found = 0, Strings Imported = 0
Debug log shows PO files exist but cannot be parsed

Getting “page over page” problem in laravel 11+ using inertia react for frontend

I have been struggling with this error for 2 weeks. Project setup is basically simple:

  • docker-compose for building app, redis and mariadb containers
  • nginx on production server for serving app and build assets from react

After a while, especially while submitting login or any POST request handling from react jsx template (using inertia router.post method), it opens up a new window inside current one with redirect.

Here is my login controller method

public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (Auth::guard('client')->attempt($credentials, $request->boolean('remember'))) {
        $client = Auth::guard('client')->user();

        if ($client->status) {
            $request->session()->regenerate();

            return Inertia::location(route('client.admin'));
        }

        Auth::guard('client')->logout();

        throw ValidationException::withMessages([
            'email' => 'Your account is inactive.',
        ]);
    }

    throw ValidationException::withMessages([
        'email' => 'The provided credentials do not match our records.',
    ]);
}

Attaching screenshots:

plaintext JSON output of login form followed by "Redirecting to" login form with "Email" and "Password" fields, "Remember me" checkbox, and "LOG IN" button

I would appreciate any help in resolving this. Thanks.

Call to undefined function readline()

When i try to write
$choice = readline();
it shows me

Fatal error: Uncaught Error: Call to undefined function readline()

But for other readlines, like $title = readline("Enter title: ") it doesn’t show me errors. What is the cause? I’m using php version 8.4.0

How can i fix it without needing to write longer codes (if possible) ?

I tried to make a do..while loop where there are multiple choices – cases, but it doesn’t seem to like it

do {
    echo "nn";
    echo "1 - show all booksn";
    echo "2 - show a bookn";
    echo "3 - add a bookn";
    echo "4 - delete a bookn";
    echo "5 - quitnn";
    $choice = readline();

    switch ($choice) {
        case 1:
            foreach ($books as $id => $book) {
                displayBook($id, $book);
            }

            break;
        case 2:
            $id = readline("Enter book id: ");
            displayBook($id, $books[$id]);

            break;
        case 3:
            addBook($books);
            break;
        case 4:
            deleteBook($books);
            break;
        case 5:
            echo "Goodbye!n";
            $continue = false;
            break;
        case 13:
            print_r($books); // hidden option to see full $books content
            break;
        default:
            echo "Invalid choicen";
    };

} while ($continue == true);

Laravel installer error – Could not scan for classes vendor/sebastian/code-unit-reverse-lookup/src/ which does not appear to be a file [duplicate]

When trying to create a new Laravel project, the Laravel installer throws the following error:

Could not scan for classes inside "/home/aes256/test/vendor/sebastian/code-unit-reverse-lookup/src/" which does not appear to be a file nor a folder
> pre-package-uninstall: IlluminateFoundationComposerScripts::prePackageUninstall
Script IlluminateFoundationComposerScripts::prePackageUninstall handling the pre-package-uninstall event terminated with an exception

In ComposerScripts.php line 66:

  [ErrorException]
  Constant LARAVEL_START already defined

Re-running the Laravel installer with verbose mode shows the following additional info:

Executing async command (CWD): 'rm' '-rf' '/home/aes256/test/vendor/sebastian/code-unit-reverse-lookup'
Could not scan for classes inside "/home/aes256/test/vendor/sebastian/code-unit-reverse-lookup/src/" which does not appear to be a file nor a folder
> pre-package-uninstall: IlluminateFoundationComposerScripts::prePackageUninstall
Script IlluminateFoundationComposerScripts::prePackageUninstall handling the pre-package-uninstall event terminated with an exception

In ComposerScripts.php line 66:

  [ErrorException]
  Constant LARAVEL_START already defined


Exception trace:
  at /home/aes256/test/vendor/laravel/framework/src/Illuminate/Foundation/ComposerScripts.php:66
 IlluminateFoundationBootstrapHandleExceptions->handleError() at /home/aes256/test/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php:258
 IlluminateFoundationBootstrapHandleExceptions->{closure:IlluminateFoundationBootstrapHandleExceptions::forwardsTo():257}() at n/a:n/a
 define() at /home/aes256/test/vendor/laravel/framework/src/Illuminate/Foundation/ComposerScripts.php:66
 IlluminateFoundationComposerScripts::prePackageUninstall() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:508
 ComposerEventDispatcherEventDispatcher->executeEventPhpScript() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:284
 ComposerEventDispatcherEventDispatcher->doDispatch() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:158
 ComposerEventDispatcherEventDispatcher->dispatchPackageEvent() at phar:///usr/bin/composer/src/Composer/Installer/InstallationManager.php:369
 ComposerInstallerInstallationManager->executeBatch() at phar:///usr/bin/composer/src/Composer/Installer/InstallationManager.php:322
 ComposerInstallerInstallationManager->downloadAndExecuteBatch() at phar:///usr/bin/composer/src/Composer/Installer/InstallationManager.php:221
 ComposerInstallerInstallationManager->execute() at phar:///usr/bin/composer/src/Composer/Installer.php:839
 ComposerInstaller->doInstall() at phar:///usr/bin/composer/src/Composer/Installer.php:649
 ComposerInstaller->doUpdate() at phar:///usr/bin/composer/src/Composer/Installer.php:298
 ComposerInstaller->run() at phar:///usr/bin/composer/src/Composer/Command/UpdateCommand.php:281
 ComposerCommandUpdateCommand->execute() at phar:///usr/bin/composer/vendor/symfony/console/Command/Command.php:298
 SymfonyComponentConsoleCommandCommand->run() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:1040
 SymfonyComponentConsoleApplication->doRunCommand() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:301
 SymfonyComponentConsoleApplication->doRun() at phar:///usr/bin/composer/src/Composer/Console/Application.php:400
 ComposerConsoleApplication->doRun() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:171
 SymfonyComponentConsoleApplication->run() at phar:///usr/bin/composer/src/Composer/Console/Application.php:137
 ComposerConsoleApplication->run() at phar:///usr/bin/composer/bin/composer:98
 require() at /usr/bin/composer:29

Is it something to be concerned about?

Tried a different Linux machine with fresh PHP + Composer install, same error.

edit: trying to create new project using PHPUnit instead of Pest works fine.

Doctrine ORM: Transaction commit fails after rollback in batch loop (Symfony 5.4, PHP 7.4)

I’m running a batch process in Symfony 5.4.48 (PHP 7.4.30, Doctrine ORM 2.20.3) where I need to handle database transactions per iteration. If a business condition fails, I want to rollback the transaction and continue to the next item. However, after a rollback, the next iteration fails with:

Transaction commit failed because the transaction has been marked for rollback only.

Here’s a simplified version of my code:

<?php
foreach ($items as $item) {
    $em = $doctrine->getManager();
    $connection = $em->getConnection();
    $connection->beginTransaction();
    try {
        // ... business logic ...
        if ($shouldRollback) {
            $connection->rollBack();
            $doctrine->resetManager();
            continue;
        }
        $connection->commit();
    } catch (Throwable $e) {
        if ($connection->isTransactionActive()) {
            $connection->rollBack();
        }
        $doctrine->resetManager();
        continue;
    }
}

Even after calling $doctrine->resetManager(), the next $em and $connection seem to be in a “rollback only” state, and commit() fails.

Environment:

  • Symfony: 5.4.48
  • Doctrine ORM: 2.20.3
  • PHP: 7.4.30
  • OS: Windows

What I’ve tried:

  • Resetting the EntityManager with $doctrine->resetManager()
  • Reacquiring the EntityManager and Connection after rollback
  • Checking transaction state with $connection->isRollbackOnly()

Questions:

  • Is this the expected behavior for Doctrine ORM?
  • How can I fully reset the EntityManager/Connection so that the next transaction works?
  • Is there a recommended pattern for batch processing with per-iteration transactions in Doctrine?

What will happen if Node.js cannot read a directory (or a part of a file) due to bad/problematic sectors on disk or corrupted file system?

I want to use the directory- and file-reading functions from 'node:fs' to merge multiple files into one file. For example, I have the following script:

import fs from 'node:fs';
import { readdir, readFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
var myStream = fs.createWriteStream('path/to/output.txt', {flags: 'a'});
var dirPath = 'path/to/mydirectory';
try {
    const entries = await readdir(dirPath, { recursive: true, withFileTypes: true });
    for (const entry of entries) {
        if (entry.isFile()) {
        const myPath = join(entry.parentPath, entry.name);
        const { size } = await stat(myPath);
        const contents = await readFile(myPath);
        myStream.write('<path>' + myPath + '</path>' + '<size>' + size.toString(10) + '</size>n' + contents + 'n');
     }
};
} catch (err) {
    console.error(err);
}; 
myStream.end()

My question is: what will happen if a directory cannot be opened or some part of a file cannot be read (due to bad/problematic sectors on disk, corrupted file system, etc.)? Will the program just freeze, so I will need to terminate it manually? Or only the corresponding file/directory will be skipped? Will the program skip a file in its entirety or only the unreadable part of it? What type of error, if any, will the program report? I have not found any information on this topic. Would it be possible to use Node.js to make the full list of problematic directories and files that are located in a given directory?

How to persist uploaded photos in a multi-step React form across page refresh?

I’m building a multi-step form in React where users can upload photos along with other inputs.

Currently:

I store all the form values in a formData state object.

To persist progress across refreshes, I save formData in localStorage.

Problem:

Uploaded photos are stored using URL.createObjectURL(file).

These object URLs don’t survive a page refresh, so the images are lost even though the rest of the form data is restored from localStorage.

Question:

Is there a way to persist uploaded photos across page refreshes without just dumping everything into localStorage?

What are the common patterns for handling this in React multi-step forms?

Should I use IndexedDB for files?

Should I upload files immediately to a temporary backend storage (and store only the reference in localStorage)?

Or is there another best practice for this use case?

Render Issues within animated PNG inside a SVG

I saw this tutorial that teaches how to do complex multilayer parallax scrolls and implemented on my website. While prototyping I found some weird lines that would appear while manipulating the PNG’s (I know the file size is big, I will fix it later). I thought it could be just some white pixels that just needed to be cleaned, but after cleaning all edges the problem persisted. Any idea why browsers are with this render issue?

https://codepen.io/Ramoses-Hofmeister-Ferreira/pen/wBMWBvZ

I was trying to manipulate some images inside an SVG so I could have a responsive multilayer parallax scroll, yet browsers are rendering strange white lines on the edge of the PNG’s that are inside of the SVG.

HTML:

<body>
    <div class="banner">
        <div id="mountain"></div>
    </div>
</body>

CSS:

body {
    margin: 0;
    background-color: #000000;
}

#mountain {
    width: 100%;
    height: 100vh;
    overflow: hidden;
}

#mountain svg {
    width: 100%;
    height: 100%;
    object-position: center;
}

JS:

function loadSVG() {
    fetch("https://raw.githubusercontent.com/astronaut954/pedro/main/img/parallax_scroll.svg")
        .then(res => res.text())
        .then(svg => {
            const mountain = document.getElementById("mountain");
            mountain.innerHTML = svg;

            const svgEl = mountain.querySelector("svg");
            svgEl.setAttribute("preserveAspectRatio", "xMidYMid slice");

            createWrapper("#layer_1");
            createWrapper("#layer_2");

            setAnimationScroll();
            setCloudAnimation();

        });
}

function createWrapper(layerId) {
    const layer = document.querySelector(`#mountain svg ${layerId}`);
    if (!layer) return;

    const wrapper = document.createElementNS("http://www.w3.org/2000/svg", "g");
    wrapper.setAttribute("id", `${layerId.slice(1)}_wrapper`);

    layer.parentNode.insertBefore(wrapper, layer);
    wrapper.appendChild(layer);
}


loadSVG();

function setAnimationScroll() {
    gsap.registerPlugin(ScrollTrigger);

    let runAnimation = gsap.timeline({
        scrollTrigger: {
            trigger: ".banner",
            start: "top top",
            end: "+=1000",
            scrub: true,
            pin: true
        }
    });

    runAnimation.add([
        gsap.to("#cloud10_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud9_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud8_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud7_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud6_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud5_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud4_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud3_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud2_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud1_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud2b", { y: -1500, duration: 2 }),
        gsap.to("#cloud1b", { y: -1500, duration: 2 }),
        gsap.to("#cloud10", { y: -1500, duration: 2 }),
        gsap.to("#cloud9", { y: -1500, duration: 2 }),
        gsap.to("#cloud8", { y: -1500, duration: 2 }),
        gsap.to("#cloud7", { y: -1500, duration: 2 }),
        gsap.to("#cloud6", { y: -1500, duration: 2 }),
        gsap.to("#cloud5", { y: -1500, duration: 2 }),
        gsap.to("#cloud4", { y: -1500, duration: 2 }),
        gsap.to("#cloud3", { y: -1500, duration: 2 }),
        gsap.to("#cloud2", { y: -1500, duration: 2 }),
        gsap.to("#cloud1", { y: -1500, duration: 2 })
    ])
    .add([
        gsap.to("#layer_1", {
            scale: 1.4,
            x: -250,
            y: 0,
            transformOrigin: "50% 0%",
            duration: 2
        }),
        gsap.to("#layer_2", {
            scale: 1.2,
            transformOrigin: "50% 0%",
            duration: 2
        })
    ]);
}

How can I detect when the AG Grid filter dialog closes?

I have an AG Grid, implemented in React/Typescript. It automatically updates with new data, and the columns have filters. When new data comes in, the grid reloads with the changes, which closes the filter dialog if it’s open. That’s not ideal. It seems like a viable solution would be to track when the dialog is open, and hold off on updates while it’s open. I can track when the filter dialog opens (onFilterOpened), or when it changes (onFilterChanged), but I’m not certain how to detect closing the dialog without making a change by clicking off of it so that I can resume changes.

Here’s the event code (which is basically just console logs right now) based on what an AI model suggested:

const onFilterOpened = () => {
  console.log("Filter opened.");
  setIsFilterDialogOpen(true);
};

const onSortChanged = () => {
  if (gridApiRef.current) {
    columnState.current = gridApiRef.current.getColumnState();
  }
};

const onFilterChanged = (event: { api: GridApi; }) => {
  if (
    event.api.getFilterModel() &&
    Object.keys(event.api.getFilterModel()).length > 0
  ) {
    console.log("Filter dialog is opened");
    setIsFilterDialogOpen(true);
  } else {
    console.log("Filter closed.");
    setIsFilterDialogOpen(false);
  }

  console.log("Filter changed");
};

And set up here:

<AgGridReact  
  className={"ag-theme-astro"}  
  columnDefs={colDefGrouped}  
  defaultColDef={defaultColDef}  
  rowData={groupedRowData}  
  domLayout="autoHeight"  
  pagination={true}  
  paginationPageSize={20}  
  isFullWidthRow={isFullWidthRow}  
  fullWidthCellRenderer={fullWidthCellRenderer}  
  getRowHeight={getRowHeight}  
  onGridReady={onGridReady}  
  onFilterChanged={onFilterChanged}
  onFilterOpened={onFilterOpened}
  data-testid="groupedGrid"
/>

I get the “Filter opened” message when it opens, and “Filter dialog is opened” as I type in changes in the filter. But nothing when it closes.