Sha256: e91277992e074a166f4ff24f87403e1edfb7eab86e931f9931caf16fed6b73f3

Contents?: true

Size: 1.24 KB

Versions: 2

Compression:

Stored size: 1.24 KB

Contents

import "@hotwired/stimulus"

const registeredControllers = {}

// Eager load all controllers registered beneath the `under` path in the import map to the passed application instance.
export function eagerLoadComponents(application, { under, suffix }) {
  const paths = Object.keys(parseImportmapJson()).filter((path) => path.match(new RegExp(`^${under}/.*${suffix}$`)))
  paths.forEach((path) => registerComponent(path, under, application, suffix))
}

function parseImportmapJson() {
  return JSON.parse(document.querySelector("script[type=importmap]").text).imports
}

function registerComponent(path, under, application, suffix) {
  const name = path
    .replace(new RegExp(`^${under}/(.*)${suffix}$`), '$1')
    .replace(/\//g, "--")
    .replace(/_/g, "-")

  application.logDebugActivity(name, 'registerComponent', { path, under, suffix })

  if (!(name in registeredControllers)) {
    import(path)
      .then(module => registerController(name, module, application))
      .catch(error => console.error(`Failed to register controller: ${name} (${path})`, error))
  }
}

function registerController(name, module, application) {
  if (!(name in registeredControllers)) {
    application.register(name, module.default)
    registeredControllers[name] = true
  }
};

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
solidus_admin-0.0.2 app/javascript/solidus_admin/controllers/components.js
solidus_admin-0.0.1 app/javascript/solidus_admin/controllers/components.js