unfoldadmin / django-unfold

Modern Django admin theme for seamless interface development
https://unfoldadmin.com
MIT License
1.87k stars 187 forks source link

`fileInputUpdatePath` stopped applying to exisiting file inputs (introduced in 0.41.0) #855

Open yardensachs opened 3 hours ago

yardensachs commented 3 hours ago

Versions: Django 5 + Unfold 0.41 + latest Chrome

Are you able to replicate the bug in the demo site? It looks like no. I am not sure that the demo site has 0.41.0 yet

Description

There's an issue with the fileInputUpdatePath implementation that prevents it from working with file inputs that exist when the page initially loads. This was introduced in #846.

Currently, the MutationObserver only watches for newly added elements (childList mutations) and attaches the change event handler to file inputs after they're dynamically added to the DOM. However, this means any file inputs that are part of the initial page HTML are missed completely.

Suggested Fix

We should modify the function to:

  1. Immediately attach handlers to existing file inputs when the function is called
  2. Keep the MutationObserver for handling dynamically added inputs

Here's how the code could be restructured:

const fileInputUpdatePath = () => {
  const handleFileInput = (input) => {
    input.addEventListener("change", (e) => {
      const parts = e.target.value.split("\\");
      const placeholder = input.parentNode.parentNode.parentNode.querySelector(
        "input[type=text]"
      );
      placeholder.setAttribute("value", parts[parts.length - 1]);
    });
  };

  // Handle existing inputs
  document.querySelectorAll("input[type=file]").forEach(handleFileInput);

  // Watch for new inputs
  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type === "childList") {
        document.querySelectorAll("input[type=file]").forEach(handleFileInput);
      }
    }
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });
};
yardensachs commented 3 hours ago

Addressed in #856