Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support more filenames + folders #10

Merged
merged 4 commits into from
Dec 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -10,3 +10,4 @@ gem "puma"
gem "debug", ">= 1.0.0"
gem "capybara"
gem "selenium-webdriver"
gem "sqlite3", "~> 1.4"
29 changes: 27 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -49,8 +49,33 @@ custom_elements/hello_element.js // will register <app-hello> automatically

Your `*_element.js` files have to `export default` custom elements for this to work properly.

> [!WARNING]
> Only single word elements are supported currently. See https://github.com/codergeek121/custom_elements-rails/issues/1
### Naming Convention for Custom Elements

When defining custom elements from files, their filenames are used to generate the element names automatically. The following rules and examples clarify how file paths are converted to custom element names:

#### Usage

Register all files in the `custom_elements` folder as custom elements using a prefix (e.g., `app`):

```js
eagerDefineCustomElementsFrom("custom_elements", { prefix: "app" });
```

#### Conversion Rules

- Filenames are transformed into kebab-case (lowercase with hyphens).
- Words are separated by underscores (`_`) or hyphens (`-`) in the filename.
- The folder structure is reflected in the name using double hyphens (`--`) to separate folder names from the file name.
- A prefix (e.g., `app`) is added to the beginning of each custom element name.

#### Examples

| Filepath | Generated Custom Element Name |
|-------------------------------------|--------------------------------|
| `custom_elements/demo_element.js` | `<app-demo>` |
| `custom_elements/demo-element.js` | `<app-demo>` |
| `custom_elements/foo_bar_element.js`| `<app-foo-bar>` |
| `custom_elements/folder/foo_bar_element.js` | `<app-folder--foo-bar>` |

## Add a custom element with the built-in generator

10 changes: 7 additions & 3 deletions app/assets/javascript/custom_elements-rails.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
export function eagerDefineCustomElementsFrom(namespace, options = {}) {
const pathToElementName = (path) => {
const parts = path.split('/').map(p => p.replace(/_/g, '-'));
return `${options.prefix}-${parts.slice(0, -1).join('--')}${parts.length > 1 ? '--' : ''}${parts.at(-1)}`;
}
const importmap = document.querySelector('script[type="importmap"]')
const { imports } = JSON.parse(importmap.textContent)
const regex = new RegExp(`${namespace}\/(.*?)_element`)
const regex = new RegExp(`${namespace}/(.*?)[-_]element`)
Object.entries(imports)
.filter(([name, _]) => name.match(regex) )
.map(([name, importPath]) => [name.match(regex)[1], importPath])
.map(([name, importPath]) => { return [pathToElementName(name.match(regex)[1]), importPath] })
.forEach(([name, importPath]) => {
import(importPath)
.then((module) => {
customElements.define(`${options.prefix}-${name}`, module.default)
customElements.define(name, module.default)
})
.catch((error) => {
console.error(`custom_elements-rails: Could not import custom element <${options.prefix}-${name}>`)
18 changes: 18 additions & 0 deletions test/custom_elements/integration_test.rb
Original file line number Diff line number Diff line change
@@ -6,4 +6,22 @@ class CustomElements::IntegrationTest < ApplicationSystemTestCase

assert_text "connectedCallback(): hello_element.js"
end

test "foo_bar_element.js connects" do
visit elements_path

assert_text "connectedCallback(): foo_bar_element.js"
end

test "some-name-element.js connects" do
visit elements_path

assert_text "connectedCallback(): some-name-element.js"
end

test "namespace/demo_element.js connects" do
visit elements_path

assert_text "connectedCallback(): demo_element.js"
end
end
9 changes: 9 additions & 0 deletions test/dummy/app/javascript/custom_elements/foo_bar_element.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default class extends HTMLElement {
constructor() {
super()
}

connectedCallback() {
this.textContent = "connectedCallback(): foo_bar_element.js"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default class extends HTMLElement {
constructor() {
super()
}

connectedCallback() {
this.textContent = "connectedCallback(): demo_element.js"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default class extends HTMLElement {
constructor() {
super()
}

connectedCallback() {
this.textContent = "connectedCallback(): some-name-element.js"
}
}
3 changes: 3 additions & 0 deletions test/dummy/app/views/elements/show.html.erb
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
<h1>Elements#show</h1>

<app-hello></app-hello>
<app-foo-bar></app-foo-bar>
<app-some-name></app-some-name>
<app-namespace--demo></app-namespace--demo>