From 2a631bcc2d8034a455e559cc34f4348d7d51dc1c Mon Sep 17 00:00:00 2001 From: Elia Schito Date: Tue, 24 Oct 2023 16:06:25 +0200 Subject: [PATCH] Add some dynamic positioning to the `ui/toggletip` component --- .../ui/toggletip/component.html.erb | 5 +--- .../solidus_admin/ui/toggletip/component.js | 26 ++++++++++++++++--- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/admin/app/components/solidus_admin/ui/toggletip/component.html.erb b/admin/app/components/solidus_admin/ui/toggletip/component.html.erb index a4fd25d046f..a375863af79 100644 --- a/admin/app/components/solidus_admin/ui/toggletip/component.html.erb +++ b/admin/app/components/solidus_admin/ui/toggletip/component.html.erb @@ -3,7 +3,6 @@ <%= tag.attributes(**@attributes) %> > -target="button" data-action=" - click:prevent-><%= stimulus_id %>#toggle + click-><%= stimulus_id %>#toggle keydown.esc@window-><%= stimulus_id %>#close " aria-label="<%= t('.get_help') %>" @@ -52,7 +50,6 @@ before:bg-inherit <%= POSITIONS.fetch(@position)[:arrow] %> " - data-<%= stimulus_id %>-target="content" > <%= @text %> diff --git a/admin/app/components/solidus_admin/ui/toggletip/component.js b/admin/app/components/solidus_admin/ui/toggletip/component.js index 54709c83a2e..ec04b795ad7 100644 --- a/admin/app/components/solidus_admin/ui/toggletip/component.js +++ b/admin/app/components/solidus_admin/ui/toggletip/component.js @@ -2,10 +2,11 @@ import { Controller } from '@hotwired/stimulus' import { useClickOutside } from 'stimulus-use' export default class extends Controller { - static targets = ['button', 'bubble', 'content'] + static targets = ['bubble'] connect () { useClickOutside(this) + this.open = false } clickOutside () { @@ -13,14 +14,31 @@ export default class extends Controller { } toggle (e) { - this.element.open = !this.element.open + e.preventDefault() + this.open = !this.open + this.render() } open () { - this.element.open = true + this.open = true + this.render() } close () { - this.element.open = false + this.open = false + this.render() + } + + render() { + const needsPositioning = this.open && !this.element.open + this.element.open = this.open + + if (needsPositioning) { + const bubbleRect = this.bubbleTarget.getBoundingClientRect() + if (bubbleRect.right > window.innerWidth) this.bubbleTarget.style.left = `${window.innerWidth - bubbleRect.width}px` + if (bubbleRect.bottom > window.innerHeight) this.bubbleTarget.style.top = `${window.innerHeight - bubbleRect.height}px` + if (bubbleRect.left < 0) this.bubbleTarget.style.left = '0px' + if (bubbleRect.top < 0) this.bubbleTarget.style.top = '0px' + } } }