Skip to content

Instantly share code, notes, and snippets.

@watzon
Last active June 14, 2019 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watzon/798d4ba0c3afcb8c681859adc2245435 to your computer and use it in GitHub Desktop.
Save watzon/798d4ba0c3afcb8c681859adc2245435 to your computer and use it in GitHub Desktop.
Toggle password field with Lucky and stimulus
import { Application } from 'stimulus'
import PasswordController from './controllers/password_controller'
const application = Application.start()
application.register("password", PasswordController)
import { Controller } from 'stimulus'
export default class extends Controller {
static targets = ["field", "icon"]
connect() {
const field = this.fieldTarget
const icon = this.iconTarget
icon.addEventListener('click', () => {
this.toggleIcon(icon)
this.toggleFieldState(field)
})
}
toggleIcon(icon) {
icon.classList.toggle('fa-eye')
icon.classList.toggle('fa-eye-slash')
}
toggleFieldState(field) {
const type = field.getAttribute('type')
if (type == 'password') {
field.setAttribute('type', 'input')
} else {
field.setAttribute('type', 'password')
}
}
}
class Shared::Field::Password < BaseComponent
needs field : Avram::FillableField(String | Nil)
def render
div class: "field", data_controller: "password" do
label_for @field, class: "label"
div class: "control has-icons-right" do
with_defaults class: field_class, data_target: "password.field", field: @field do |input_builder|
yield input_builder
end
span class: "icon is-small is-right password-field-toggle" do
i class: "fas fa-eye", data_target: "password.icon"
end
mount Shared::FieldErrors.new(@field)
end
end
end
private def field_class
@field.valid? ? "input" : "input is-danger"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment