A platform for community discussion. Free, open, simple.
UX: Keep tooltips within the viewport and scroll their overflow (#42516)
Régis Hanoled2b5b2f8027
diff --git a/app/assets/stylesheets/common/float-kit/d-tooltip.scss b/app/assets/stylesheets/common/float-kit/d-tooltip.scssindex 25355c1c67d..99446f85ae4 100644--- a/app/assets/stylesheets/common/float-kit/d-tooltip.scss+++ b/app/assets/stylesheets/common/float-kit/d-tooltip.scss@@ -23,11 +23,18 @@}&__inner-content {+ box-sizing: border-box;display: flex;- overflow: hidden;+ max-height: 60dvh;+ overflow-x: hidden;+ overflow-y: auto;+ overscroll-behavior: contain;overflow-wrap: break-word;padding: 0.5rem;- align-items: center;++ // `safe` so content taller than the cap starts at the top instead of being centred,+ // which would put the first lines above the scrollport and out of reach+ align-items: safe center;}&__content {diff --git a/frontend/discourse/float-kit/components/d-float-body.gts b/frontend/discourse/float-kit/components/d-float-body.gtsindex a9c5d4e5ff4..3118ca7d739 100644--- a/frontend/discourse/float-kit/components/d-float-body.gts+++ b/frontend/discourse/float-kit/components/d-float-body.gts@@ -5,6 +5,7 @@ import { modifier as modifierFn } from "ember-modifier";import DFloatPortal from "discourse/float-kit/components/d-float-portal";import type FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";import { getScrollParent } from "discourse/float-kit/lib/get-scroll-parent";+import { horizontalViewportInset } from "discourse/float-kit/lib/update-position";import FloatKitApplyFloatingUi from "discourse/float-kit/modifiers/apply-floating-ui";import FloatKitCloseOnEscape from "discourse/float-kit/modifiers/close-on-escape";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@@ -164,12 +165,16 @@ export default class DFloatBody extends Component<DFloatBodySignature> {}get style() {- const maxWidth =- typeof this.options.maxWidth === "number"- ? `${this.options.maxWidth}px`- : this.options.maxWidth;+ const { maxWidth } = this.options;- return trustHTML(`max-width: ${maxWidth}`);+ // Only a number is clamped: a keyword like `none` or `unset` is invalid inside `min()`,+ // which would drop the declaration and hand the float to whatever CSS sets `max-width`.+ const value =+ typeof maxWidth === "number"+ ? `min(${maxWidth}px, calc(100dvw - ${horizontalViewportInset(this.options)}px))`+ : maxWidth;++ return trustHTML(`max-width: ${value}`);}<template>diff --git a/frontend/discourse/float-kit/lib/constants.ts b/frontend/discourse/float-kit/lib/constants.tsindex cb2712cba39..94f939b42b4 100644--- a/frontend/discourse/float-kit/lib/constants.ts+++ b/frontend/discourse/float-kit/lib/constants.ts@@ -134,6 +134,9 @@ export interface TooltipOptions {* `"none"` alongside `matchTriggerWidth` — the two are both applied inline, so a numeric cap* silently wins over the matched width and a trigger wider than the cap gets a narrower* overlay.+ *+ * A number is additionally capped to the width the viewport leaves the float, so it can never+ * overflow the document; a string is applied verbatim and gets no such cap.*/maxWidth: number | string;diff --git a/frontend/discourse/float-kit/lib/update-position.ts b/frontend/discourse/float-kit/lib/update-position.tsindex 6b0d887f042..956665e8732 100644--- a/frontend/discourse/float-kit/lib/update-position.ts+++ b/frontend/discourse/float-kit/lib/update-position.ts@@ -220,6 +220,19 @@ function getPadding(options: PositioningOptions): Padding {);}+/**+ * The total horizontal clearance a float keeps from the viewport edges: the left and right+ * {@link getPadding} sides added together. `shift` can only move a float, never shrink it, so a+ * float wider than what is left over overflows the document instead of being fitted on screen.+ */+export function horizontalViewportInset(options: PositioningOptions): number {+ const padding = getPadding(options);++ return typeof padding === "number"+ ? padding * 2+ : (padding.left ?? 0) + (padding.right ?? 0);+}+function buildDetectOverflowOptions(options: PositioningOptions,padding: Paddingdiff --git a/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjs b/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjsindex 11dc07fbdb7..32550dc49b5 100644--- a/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjs+++ b/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjs@@ -4,6 +4,7 @@ import { getOwner } from "@ember/owner";import didInsert from "@ember/render-modifiers/modifiers/did-insert";import {click,+ find,render,settled,triggerEvent,@@ -310,9 +311,78 @@ module("Integration | Component | FloatKit | DTooltip", function (hooks) {);await hover();+ assert.dom(".fk-d-tooltip__content").hasStyle({ maxWidth: "20px" });++ await close();++ await render(+ <template>+ <DTooltip @inline={{true}} @label="label" @maxWidth={{100000}} />+ </template>+ );+ await hover();++ // 20 is the default left + right `getPadding` inset the clamp reserves+ assert+ .dom(".fk-d-tooltip__content")+ .hasStyle(+ { maxWidth: `${window.innerWidth - 20}px` },+ "a numeric cap is clamped to the width the viewport leaves"+ );+ });++ test("a keyword @maxWidth is applied verbatim", async function (assert) {+ await render(+ <template>+ <DTooltip @inline={{true}} @label="label" @maxWidth="unset" />+ </template>+ );+ await hover();++ // asserting the declaration rather than the computed value: wrapping a keyword in `min()`+ // is invalid CSS, and the browser drops such a declaration to the same computed `none`assert.dom(".fk-d-tooltip__content")- .hasAttribute("style", /max-width: 20px;/);+ .hasAttribute("style", /max-width: unset;/);+ });++ test("content taller than the cap scrolls inside the tooltip", async function (assert) {+ await render(+ <template>+ <DTooltip @inline={{true}} @label="label">+ <div>+ <div class="first-line">first line</div>+ <div style="height: 4000px"></div>+ <div class="last-line">last line</div>+ </div>+ </DTooltip>+ </template>+ );+ await hover();++ const content = find(".fk-d-tooltip__inner-content");+ const scrollport = content.getBoundingClientRect();++ assert.true(+ content.clientHeight <= Math.ceil(window.innerHeight * 0.6),+ "the content is capped to a fraction of the viewport"+ );+ assert.true(+ content.scrollHeight > content.clientHeight,+ "the overflowing content is scrollable rather than clipped"+ );+ assert.true(+ find(".first-line").getBoundingClientRect().top >= scrollport.top,+ "the top of the content is reachable rather than centred out of view"+ );++ content.scrollTop = content.scrollHeight;++ assert.true(+ find(".last-line").getBoundingClientRect().bottom <=+ scrollport.bottom + 1,+ "the bottom of the content is reachable"+ );});test("applies position", async function (assert) {diff --git a/plugins/footnote/spec/system/page_objects/components/inline_footnote.rb b/plugins/footnote/spec/system/page_objects/components/inline_footnote.rbnew file mode 100644index 00000000000..20e74241059--- /dev/null+++ b/plugins/footnote/spec/system/page_objects/components/inline_footnote.rb@@ -0,0 +1,73 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class InlineFootnote < PageObjects::Components::Base+ CONTENT_SELECTOR = ".fk-d-tooltip__inner-content"++ def open+ find("a.expand-footnote").click+ end++ def within_screen?+ settled { popup_within_screen? }+ end++ def scrollable?+ content.evaluate_script("this.scrollHeight > this.clientHeight")+ end++ def scroll_to_bottom+ content.scroll_to(:bottom)+ end++ def has_scrolled_to?(text)+ tooltip.find("#{CONTENT_SELECTOR} p", text: text).evaluate_script(<<~JS)+ (() => {+ const scrollport = this.closest("#{CONTENT_SELECTOR}").getBoundingClientRect();++ return this.getBoundingClientRect().bottom <= scrollport.bottom + 1;+ })()+ JS+ end++ def has_no_horizontal_page_scroll?+ settled do+ evaluate_script(+ "document.documentElement.scrollWidth <= document.documentElement.clientWidth",+ )+ end+ end++ private++ def tooltip+ @tooltip ||= PageObjects::Components::Tooltips.new("inline-footnote")+ end++ def content+ tooltip.find(CONTENT_SELECTOR)+ end++ # the float is animated and positioned asynchronously, so a geometry read taken right+ # after it opens can measure it mid-flight+ def settled(&block)+ try_until_success { expect(block.call).to eq(true) }+ true+ rescue RSpec::Expectations::ExpectationNotMetError+ false+ end++ def popup_within_screen?+ tooltip.element.evaluate_script(<<~JS)+ (() => {+ const { top, bottom, left, right } = this.getBoundingClientRect();++ return top >= 0 && left >= 0 &&+ bottom <= window.innerHeight && right <= window.innerWidth;+ })()+ JS+ end+ end+ end+enddiff --git a/plugins/footnote/spec/system/read_long_footnote_spec.rb b/plugins/footnote/spec/system/read_long_footnote_spec.rbnew file mode 100644index 00000000000..99d699f29eb--- /dev/null+++ b/plugins/footnote/spec/system/read_long_footnote_spec.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++describe "Reading a long inline footnote" do+ fab!(:user)+ fab!(:post) do+ paragraphs = (1..10).map { |number| " Paragraph #{number}. #{"word " * 60}" }.join("\n\n")++ Fabricate(:post, raw: <<~MARKDOWN)+ A footnote with a lot of content[^1]++ [^1]: Start of the footnote.++ #{paragraphs}++ End of the footnote.+ MARKDOWN+ end++ let(:topic_page) { PageObjects::Pages::Topic.new }+ let(:footnote) { PageObjects::Components::InlineFootnote.new }++ before { sign_in(user) }++ it "lets the user read a long footnote without the popup running off a narrow screen",+ mobile: true do+ resize_window(width: 320) do+ topic_page.visit_topic(post.topic)++ footnote.open++ expect(footnote).to be_within_screen+ expect(footnote).to have_no_horizontal_page_scroll+ expect(footnote).to be_scrollable++ footnote.scroll_to_bottom++ expect(footnote).to have_scrolled_to("End of the footnote.")+ end+ end+enddiff --git a/spec/system/page_objects/components/tooltips.rb b/spec/system/page_objects/components/tooltips.rbindex fb66d9ac5eb..69fd01543a4 100644--- a/spec/system/page_objects/components/tooltips.rb+++ b/spec/system/page_objects/components/tooltips.rb@@ -11,6 +11,10 @@ module PageObjects@identifier = identifierend+ def element(**kwargs)+ page.find("#{SELECTOR}[data-identifier='#{identifier}']", **kwargs)+ end+def find(selector, **kwargs)page.find("#{SELECTOR}[data-identifier='#{identifier}'] #{selector}", **kwargs)end