Sha256: 9a694c27d6e73c129c1c13585ff3b541939b073642505ac03ae0b78a5a9fa15d

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

import { Application } from "stimulus"

const application = Application.start()
const { controllerAttribute } = application.schema
const registeredControllers = {}

function autoloadControllersWithin(element) {
  queryControllerNamesWithin(element).forEach(loadController)
}

function queryControllerNamesWithin(element) {
  return Array.from(element.querySelectorAll(`[${controllerAttribute}]`)).map(extractControllerNamesFrom).flat()
}

function extractControllerNamesFrom(element) {
  return element.getAttribute(controllerAttribute).split(/\s+/).filter(content => content.length)
}

function loadController(name) {
  import(controllerFilename(name))
    .then(module => registerController(name, module))
    .catch(error => console.log(`Failed to autoload controller: ${name}`, error))
}

function controllerFilename(name) {
  return `${name.replace(/--/g, "/").replace(/-/g, "_")}_controller`
}

function registerController(name, module) {
  if (name in registeredControllers) return

  application.register(name, module.default)
  registeredControllers[name] = true
}


new MutationObserver((mutationsList) => {
  for (const { attributeName, target } of mutationsList) {
    if (attributeName == controllerAttribute && target.hasAttribute(controllerAttribute)) {
      autoloadControllersWithin(target)
    }
  }
}).observe(document.body, { attributeFilter: [controllerAttribute], subtree: true, childList: true })

autoloadControllersWithin(document)

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
stimulus-rails-0.2.0 app/assets/javascripts/stimulus/loaders/autoloader.js