| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import { Controller } from '@hotwired/stimulus';
- export default class extends Controller {
- static values = {
- value: { type: Number, default: 0 },
- max: { type: Number, default: 5 },
- step: { type: Number, default: 1 },
- disabled: { type: Boolean, default: false },
- size: { type: String, default: 'md' }
- };
- connect() {
- this.updateDisplay();
-
- if (!this.disabledValue) {
- this.element.style.cursor = 'pointer';
- }
- }
- valueValueChanged() {
- this.updateDisplay();
- }
- updateDisplay() {
- const stars = this.element.querySelectorAll('.star');
- const value = this.valueValue;
- const max = this.maxValue;
-
- stars.forEach((star, index) => {
- const starValue = index + 1;
-
- // Pour les étapes de 0.5
- if (this.stepValue === 0.5) {
- if (value >= starValue) {
- star.classList.remove('fa-regular', 'fa-star-half-stroke');
- star.classList.add('fa-solid');
- } else if (value >= starValue - 0.5) {
- star.classList.remove('fa-solid', 'fa-regular');
- star.classList.add('fa-star-half-stroke');
- } else {
- star.classList.remove('fa-solid', 'fa-star-half-stroke');
- star.classList.add('fa-regular');
- }
- } else {
- // Pour les étapes de 1
- if (value >= starValue) {
- star.classList.remove('fa-regular');
- star.classList.add('fa-solid');
- } else {
- star.classList.remove('fa-solid');
- star.classList.add('fa-regular');
- }
- }
- });
- }
- handleClick(event) {
- if (this.disabledValue) return;
-
- const clickedStar = event.target.closest('.star');
- if (!clickedStar) return;
-
- const stars = Array.from(this.element.querySelectorAll('.star'));
- const clickedIndex = stars.indexOf(clickedStar);
- const starValue = clickedIndex + 1;
-
- // Gérer les demi-étoiles pour step=0.5
- if (this.stepValue === 0.5) {
- const rect = clickedStar.getBoundingClientRect();
- const clickX = event.clientX - rect.left;
- const starWidth = rect.width;
-
- // Si on clique sur la moitié gauche, on met une demi-étoile
- if (clickX < starWidth / 2 && starValue <= this.maxValue) {
- this.valueValue = starValue - 0.5;
- } else {
- this.valueValue = starValue;
- }
- } else {
- this.valueValue = starValue;
- }
-
- // Dispatch un événement pour notifier du changement
- this.element.dispatchEvent(new CustomEvent('change', {
- detail: { value: this.valueValue }
- }));
- }
- get sizeClass() {
- const sizes = {
- 'xs': 'fa-xs',
- 'sm': 'fa-sm',
- 'md': '',
- 'lg': 'fa-lg',
- 'xl': 'fa-xl',
- '2x': 'fa-2x',
- '3x': 'fa-3x'
- };
- return sizes[this.sizeValue] || '';
- }
- }
|