A platform for community discussion. Free, open, simple.
FEATURE: carousel mode for image grid (#36825)
Samdc21ce016a39
diff --git a/app/assets/stylesheets/common/base/d-image-grid.scss b/app/assets/stylesheets/common/base/d-image-grid.scssindex 074fad879c2..e0ec5d662e4 100644--- a/app/assets/stylesheets/common/base/d-image-grid.scss+++ b/app/assets/stylesheets/common/base/d-image-grid.scss@@ -99,3 +99,157 @@}}}++.d-image-carousel {+ position: relative;+ width: 100%;+ display: flex;+ flex-direction: column;+ gap: var(--space-1);++ &__track {+ display: flex;+ width: 100%;+ height: 400px;+ overflow-x: auto;+ overflow-y: hidden;+ scroll-snap-type: x mandatory;+ scroll-behavior: smooth;+ -webkit-overflow-scrolling: touch;+ scrollbar-width: none;++ &::-webkit-scrollbar {+ display: none;+ }+ }++ &__slide {+ .d-image-carousel--carousel & {+ flex: 0 0 100%;+ width: 100%;+ height: 100%;+ scroll-snap-align: center;+ scroll-snap-stop: always;+ display: flex;+ align-items: center;+ justify-content: center;++ img:not(.thumbnail, .ytp-thumbnail-image, .emoji) {+ max-width: 100% !important;+ max-height: 100% !important;+ width: auto !important;+ height: auto !important;+ object-fit: contain !important;+ border-radius: var(--d-border-radius);+ }+ }++ .lightbox-wrapper {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ max-width: 100%;+ max-height: 100%;+ height: 100%;++ // Ensure the lightbox link itself doesn't force a crop+ .lightbox {+ display: flex;+ align-items: center;+ justify-content: center;+ max-width: 100%;+ max-height: 100%;+ }+ }+ }++ &__controls {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--space-2);+ padding-block: var(--space-2);+ }++ &__nav {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ border: 0;+ padding: 0;+ background: none;+ color: var(--primary-medium);+ cursor: pointer;+ font-size: var(--font-down-1);+ touch-action: manipulation;++ &:hover {+ background: none;+ color: var(--primary);+ }++ &:disabled {+ cursor: default;+ opacity: 0.6;+ }+ }++ &__dots {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.5rem 0.75rem;+ background: var(--primary-very-low);+ border-radius: 1rem;+ }++ &__dot {+ height: 0.6rem;+ width: 0.6rem;+ padding: 0;+ background: var(--primary-low-mid);+ border: none;+ border-radius: 1rem;+ cursor: pointer;+ transition:+ width 0.25s cubic-bezier(0.4, 0, 0.2, 1),+ background-color 0.25s cubic-bezier(0.4, 0, 0.2, 1),+ transform 0.15s ease-out;+ touch-action: manipulation;++ &:hover {+ transform: scale(1.2);+ }++ &.active {+ background: var(--primary-medium);+ width: 1.4rem;+ }+ }++ &__counter {+ padding: 0.5rem 0.75rem;+ background: var(--primary-very-low);+ border-radius: 1rem;+ font-size: var(--font-down-1);+ color: var(--primary-medium);+ font-variant-numeric: tabular-nums;+ text-align: center;+ }++ &--single {+ .d-image-carousel__controls {+ display: none;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ .d-image-carousel__track {+ scroll-behavior: auto;+ }+ }+}diff --git a/app/assets/stylesheets/common/rich-editor/_index.scss b/app/assets/stylesheets/common/rich-editor/_index.scssindex 31b532f02a9..527639ffe90 100644--- a/app/assets/stylesheets/common/rich-editor/_index.scss+++ b/app/assets/stylesheets/common/rich-editor/_index.scss@@ -1 +1,2 @@@import "rich-editor";+@import "composer-image-gallery";diff --git a/app/assets/stylesheets/common/rich-editor/composer-image-gallery.scss b/app/assets/stylesheets/common/rich-editor/composer-image-gallery.scssnew file mode 100644index 00000000000..8244dfef8fb--- /dev/null+++ b/app/assets/stylesheets/common/rich-editor/composer-image-gallery.scss@@ -0,0 +1,62 @@+@use "lib/viewport";++.composer-image-gallery {+ &__mode-buttons {+ position: absolute;+ right: var(--space-2);+ top: var(--space-2);+ display: flex;+ z-index: 1;++ @include viewport.until(sm) {+ flex-direction: column;+ gap: var(--space-2);+ }+ }++ &__mode-btn {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ border: 1px solid var(--primary-low);+ background: var(--secondary);+ color: var(--primary-medium);+ font-size: var(--font-down-1-rem);+ padding: var(--space-1) var(--space-2);++ @include viewport.until(sm) {+ padding: var(--space-2) var(--space-4);+ }++ @include viewport.from(sm) {+ &:first-child {+ border-top-left-radius: var(--d-border-radius);+ border-bottom-left-radius: var(--d-border-radius);+ }++ &:last-child {+ border-top-right-radius: var(--d-border-radius);+ border-bottom-right-radius: var(--d-border-radius);+ }++ &:not(:first-child) {+ border-left: none;+ }++ &:hover {+ color: var(--primary);+ background-color: var(--d-hover);+ }+ }++ &.is-active {+ background-color: var(--tertiary-low);+ color: var(--tertiary);+ border-color: var(--tertiary-low);+ }++ &:focus-visible {+ outline: 1px auto var(--tertiary);+ }+ }+}diff --git a/app/assets/stylesheets/common/rich-editor/rich-editor.scss b/app/assets/stylesheets/common/rich-editor/rich-editor.scssindex 909f9465009..8b66cbf694f 100644--- a/app/assets/stylesheets/common/rich-editor/rich-editor.scss+++ b/app/assets/stylesheets/common/rich-editor/rich-editor.scss@@ -181,24 +181,29 @@position: relative;border: 2px dashed var(--primary-low-mid);border-radius: var(--d-border-radius);- padding: var(--space-half) var(--space-2) var(--space-2) var(--space-2);+ padding: var(--space-half) var(--space-2) 0 var(--space-2);margin-block: var(--space-4);- &__title {+ &__remove-btn {+ position: absolute;+ bottom: var(--space-2);+ right: var(--space-2);+ color: var(--primary-medium);+ padding: var(--space-1) var(--space-2);+ background: var(--secondary);+ border: 1px solid var(--primary-low);+ font-size: var(--font-down-1-rem);display: flex;align-items: center;- justify-content: end;- font-size: var(--font-down-1-rem);- color: var(--primary-medium);+ gap: var(--space-1);- svg {- font-size: var(--font-up-1-rem);- padding-inline: var(--space-2);+ @include viewport.until(sm) {+ padding: var(--space-2) var(--space-4);+ }- &:hover {- color: var(--primary);- cursor: pointer;- }+ &:hover {+ color: var(--primary);+ background: var(--primary-low);}}diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 720cb6d6fd4..2e37fd07ca0 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -1,5 +1,9 @@en:js:+ carousel:+ go_to_slide: "Go to slide %{index}"+ previous: "Previous slide"+ next: "Next slide"number:format:# symbol used to separate the integer part from the fractional part of a number@@ -3175,6 +3179,10 @@ en:image: "image"grid_label: "This will be displayed as a grid"+ grid_mode_grid: "Grid"+ grid_mode_carousel: "Carousel"+ grid_mode_title: "Set image gallery style to %{mode}"+ remove_grid: "Remove grid"image_scale_button: "Scale image to %{percent}%"delete_image_button: Delete Imagediff --git a/frontend/discourse-markdown-it/src/features/image-grid.js b/frontend/discourse-markdown-it/src/features/image-grid.jsindex c55b3543fa3..fcb3701ae72 100644--- a/frontend/discourse-markdown-it/src/features/image-grid.js+++ b/frontend/discourse-markdown-it/src/features/image-grid.js@@ -1,8 +1,20 @@+import { applyDataAttributes } from "./bbcode-block";++const VALID_MODES = new Set(["grid", "carousel"]);+const gridRule = {tag: "grid",- before(state) {+ before(state, tagInfo) {let token = state.push("bbcode_open", "div", 1);token.attrs = [["class", "d-image-grid"]];++ if (tagInfo?.attrs) {+ let { mode } = tagInfo.attrs;+ if (mode && !VALID_MODES.has(mode)) {+ mode = "grid";+ }+ applyDataAttributes(token, { mode });+ }},after(state) {@@ -11,7 +23,7 @@ const gridRule = {};export function setup(helper) {- helper.allowList(["div.d-image-grid"]);+ helper.allowList(["div.d-image-grid", "div.d-image-grid[data-mode]"]);helper.registerPlugin((md) => {md.block.bbcode.ruler.push("grid", gridRule);diff --git a/frontend/discourse/app/components/image-carousel.gjs b/frontend/discourse/app/components/image-carousel.gjsnew file mode 100644index 00000000000..a7a3e667d50--- /dev/null+++ b/frontend/discourse/app/components/image-carousel.gjs@@ -0,0 +1,287 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { helper } from "@ember/component/helper";+import { concat, fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { cancel, throttle } from "@ember/runloop";+import { htmlSafe } from "@ember/template";+import { modifier } from "ember-modifier";+import concatClass from "discourse/helpers/concat-class";+import icon from "discourse/helpers/d-icon";+import { isTesting } from "discourse/lib/environment";+import discourseLater from "discourse/lib/later";+import { eq } from "discourse/truth-helpers";+import { i18n } from "discourse-i18n";++const plusOne = helper(([val]) => val + 1);+const getAspectRatio = helper(([width, height]) => {+ const w = parseInt(width, 10) || 1;+ const h = parseInt(height, 10) || 1;+ return htmlSafe(`aspect-ratio: ${w} / ${h}`);+});++const FALLBACK_TIMEOUT_MS = 1000;+const KEYBOARD_THROTTLE_MS = isTesting() ? 0 : 150;+const SCROLL_THROTTLE_MS = 50;+const MAX_DOTS = 10;++export default class ImageCarousel extends Component {+ @tracked currentIndex = 0;++ registerSlide = modifier((element, [index]) => {+ this.#slides.set(index, element);+ return () => {+ this.#slides.delete(index);+ };+ });++ setupTrack = modifier((element) => {+ this.#trackDirection =+ getComputedStyle(element).direction === "rtl" ? -1 : 1;++ const onScrollEnd = () => {+ if (this.#isNavigating) {+ this.#endNavigation();+ } else {+ this.currentIndex = this.#calculateNearestIndex(element);+ }+ };++ const supportsScrollEnd = "onscrollend" in window;+ let scrollStopTimer;++ const onScroll = () => {+ if (!this.#isNavigating) {+ throttle(+ this,+ this.#updateIndexFromScroll,+ element,+ SCROLL_THROTTLE_MS+ );+ }++ // Fallback for browsers without scrollend support (Safari < 17.4)+ if (!supportsScrollEnd) {+ clearTimeout(scrollStopTimer);+ scrollStopTimer = setTimeout(onScrollEnd, 150);+ }+ };++ element.addEventListener("scroll", onScroll, { passive: true });++ if (supportsScrollEnd) {+ element.addEventListener("scrollend", onScrollEnd);+ }++ return () => {+ element.removeEventListener("scroll", onScroll);+ if (supportsScrollEnd) {+ element.removeEventListener("scrollend", onScrollEnd);+ }+ clearTimeout(scrollStopTimer);+ cancel(this.#fallbackTimer);+ };+ });++ #isNavigating = false;+ #fallbackTimer = null;+ #trackDirection = 1;+ #slides = new Map();++ willDestroy() {+ super.willDestroy(...arguments);+ cancel(this.#fallbackTimer);+ }++ #calculateNearestIndex(track) {+ if (!track) {+ return this.currentIndex;+ }++ const trackCenter = track.scrollLeft + track.clientWidth / 2;+ let bestIndex = 0;+ let minDistance = Infinity;++ this.#slides.forEach((slide, index) => {+ const slideCenter = slide.offsetLeft + slide.offsetWidth / 2;+ const distance = Math.abs(slideCenter - trackCenter);+ if (distance < minDistance) {+ minDistance = distance;+ bestIndex = index;+ }+ });++ return bestIndex;+ }++ #endNavigation() {+ this.#isNavigating = false;+ cancel(this.#fallbackTimer);+ }++ #updateIndexFromScroll(track) {+ const newIndex = this.#calculateNearestIndex(track);+ if (newIndex !== this.currentIndex) {+ this.currentIndex = newIndex;+ }+ }++ get #scrollBehavior() {+ return window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches+ ? "auto"+ : "smooth";+ }++ get items() {+ return this.args.data.items || [];+ }++ get isSingle() {+ return this.items.length < 2;+ }++ get prevIndex() {+ return this.currentIndex === 0 ? this.lastIndex : this.currentIndex - 1;+ }++ get nextIndex() {+ return this.currentIndex === this.lastIndex ? 0 : this.currentIndex + 1;+ }++ get lastIndex() {+ return this.items.length - 1;+ }++ get showDots() {+ return this.items.length <= MAX_DOTS;+ }++ get counterText() {+ return `${this.currentIndex + 1} / ${this.items.length}`;+ }++ @action+ scrollToIndex(index) {+ const clamped = Math.max(0, Math.min(index, this.items.length - 1));++ if (this.#isNavigating || clamped === this.currentIndex) {+ return;+ }++ const slide = this.#slides.get(clamped);++ if (!slide) {+ return;+ }++ this.#isNavigating = true;+ this.currentIndex = clamped;++ cancel(this.#fallbackTimer);+ this.#fallbackTimer = discourseLater(() => {+ if (this.#isNavigating) {+ this.#endNavigation();+ }+ }, FALLBACK_TIMEOUT_MS);++ slide.scrollIntoView({+ behavior: this.#scrollBehavior,+ block: "nearest",+ inline: "center",+ });+ }++ #navigateByKey(direction) {+ const goNext = (direction === "right") === (this.#trackDirection === 1);+ this.scrollToIndex(goNext ? this.nextIndex : this.prevIndex);+ }++ @action+ onKeyDown(event) {+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") {+ return;+ }++ event.preventDefault();+ const direction = event.key === "ArrowLeft" ? "left" : "right";+ throttle(this, this.#navigateByKey, direction, KEYBOARD_THROTTLE_MS);+ }++ <template>+ <div+ class={{concatClass+ "d-image-carousel"+ (if @data.mode (concat "d-image-carousel--" @data.mode))+ (if this.isSingle "d-image-carousel--single")+ }}+ >+ <div+ class="d-image-carousel__track"+ tabindex="0"+ {{this.setupTrack}}+ {{on "keydown" this.onKeyDown}}+ >+ {{#each this.items as |item index|}}+ <div+ class={{concatClass+ "d-image-carousel__slide"+ (if (eq this.currentIndex index) "is-active")+ }}+ data-index={{index}}+ style={{getAspectRatio item.width item.height}}+ {{this.registerSlide index}}+ >+ {{item.element}}+ </div>+ {{/each}}+ </div>++ {{#unless this.isSingle}}+ <div class="d-image-carousel__controls">+ <button+ type="button"+ class="d-image-carousel__nav d-image-carousel__nav--prev"+ title={{i18n "carousel.previous"}}+ aria-label={{i18n "carousel.previous"}}+ {{on "click" (fn this.scrollToIndex this.prevIndex)}}+ >+ {{icon "chevron-left"}}+ </button>++ {{#if this.showDots}}+ <div class="d-image-carousel__dots">+ {{#each this.items as |_item index|}}+ <button+ type="button"+ class={{concatClass+ "d-image-carousel__dot"+ (if (eq this.currentIndex index) "active")+ }}+ aria-label={{i18n+ "carousel.go_to_slide"+ index=(plusOne index)+ }}+ aria-current={{if (eq this.currentIndex index) "true"}}+ {{on "click" (fn this.scrollToIndex index)}}+ ></button>+ {{/each}}+ </div>+ {{else}}+ <span class="d-image-carousel__counter">{{this.counterText}}</span>+ {{/if}}++ <button+ type="button"+ class="d-image-carousel__nav d-image-carousel__nav--next"+ title={{i18n "carousel.next"}}+ aria-label={{i18n "carousel.next"}}+ {{on "click" (fn this.scrollToIndex this.nextIndex)}}+ >+ {{icon "chevron-right"}}+ </button>+ </div>+ {{/unless}}+ </div>+ </template>+}diff --git a/frontend/discourse/app/instance-initializers/post-decorations.js b/frontend/discourse/app/instance-initializers/post-decorations.jsindex d6f18ae66a9..6da55d46bd6 100644--- a/frontend/discourse/app/instance-initializers/post-decorations.js+++ b/frontend/discourse/app/instance-initializers/post-decorations.js@@ -6,6 +6,7 @@ import { popupAjaxError } from "discourse/lib/ajax-error";import Columns from "discourse/lib/columns";import highlightSyntax from "discourse/lib/highlight-syntax";import { iconElement, iconHTML } from "discourse/lib/icon-library";+import setupImageGridCarousel from "discourse/lib/image-grid-carousel";import { nativeLazyLoading } from "discourse/lib/lazy-load-images";import lightbox from "discourse/lib/lightbox";import { withPluginApi } from "discourse/lib/plugin-api";@@ -28,21 +29,32 @@ export default {});api.decorateCookedElement((elem, helper) => {- return lightbox(elem, { post: helper.model });- });-- api.decorateCookedElement((elem) => {const grids = elem.querySelectorAll(".d-image-grid");+ let needsLightboxAfterRender = false;++ if (grids.length) {+ grids.forEach((grid) => {+ if (grid.dataset.mode === "carousel") {+ if (setupImageGridCarousel(grid, helper)) {+ needsLightboxAfterRender = true;+ }+ return;+ }- if (!grids.length) {- return;+ return new Columns(grid, {+ columns: site.mobileView ? 2 : 3,+ });+ });}- grids.forEach((grid) => {- return new Columns(grid, {- columns: site.mobileView ? 2 : 3,+ if (needsLightboxAfterRender) {+ schedule("afterRender", () => {+ lightbox(elem, { post: helper.model });});- });+ return;+ }++ return lightbox(elem, { post: helper.model });});if (siteSettings.support_mixed_text_direction) {diff --git a/frontend/discourse/app/lib/columns.js b/frontend/discourse/app/lib/columns.jsindex 455611ae572..882998f5aa1 100644--- a/frontend/discourse/app/lib/columns.js+++ b/frontend/discourse/app/lib/columns.js@@ -51,18 +51,23 @@ export default class Columns {_prepareItems() {let targets = [];- for (let child of this.container.children) {+ const children = [...this.container.children];+ for (let child of children) {// sometimes children are wrapped in a paragraphif (child.nodeName === "P" && child.children.length > 0) {- for (let c of child.children) {- targets.push(this._wrapDirectImage(c));+ for (let c of [...child.children]) {+ if (!["BR", "P"].includes(c.nodeName)) {+ targets.push(c);+ }}} else {- targets.push(this._wrapDirectImage(child));+ if (!["BR", "P"].includes(child.nodeName)) {+ targets.push(child);+ }}}- return targets.filter((item) => !["BR", "P"].includes(item.nodeName));+ return targets;}_wrapDirectImage(item) {@@ -72,7 +77,7 @@ export default class Columns {const wrapper = document.createElement("span");wrapper.classList.add("image-wrapper");- wrapper.appendChild(item.cloneNode());+ wrapper.appendChild(item);return wrapper;}@@ -92,9 +97,12 @@ export default class Columns {// use aspect ratio to compare heights and append to shortest column// if element is not an image, assume ratio is 1:1- const img = item.querySelector("img") || item;- heights[shortest] += img.nodeName === "IMG" ? img.height / img.width : 1;- columns[shortest].append(item);+ const img =+ item.querySelector("img") || (item.nodeName === "IMG" ? item : null);+ heights[shortest] += img && img.width > 0 ? img.height / img.width : 1;++ const wrappedItem = this._wrapDirectImage(item);+ columns[shortest].append(wrappedItem);});return columns;diff --git a/frontend/discourse/app/lib/image-grid-carousel.js b/frontend/discourse/app/lib/image-grid-carousel.jsnew file mode 100644index 00000000000..a722acf338c--- /dev/null+++ b/frontend/discourse/app/lib/image-grid-carousel.js@@ -0,0 +1,114 @@+import ImageCarousel from "discourse/components/image-carousel";++const FALLBACK_WIDTH = 1024;+const FALLBACK_HEIGHT = 768;++function parseInfoDimensions(text) {+ if (!text) {+ return null;+ }++ const dimensions = text.trim().split(" ")[0];+ if (!dimensions) {+ return null;+ }++ const [width, height] = dimensions.split(/x|×/).map(Number);+ if (!width || !height) {+ return null;+ }++ return { width, height };+}++function resolveDimensions(anchor, img) {+ const targetWidth = Number(anchor?.dataset.targetWidth || img?.width || 0);+ const targetHeight = Number(anchor?.dataset.targetHeight || img?.height || 0);++ if (targetWidth && targetHeight) {+ return { width: targetWidth, height: targetHeight };+ }++ const infoText = anchor?.querySelector(".informations")?.textContent;+ const infoDimensions = parseInfoDimensions(infoText);+ if (infoDimensions) {+ return infoDimensions;+ }++ const naturalWidth = Number(img?.naturalWidth || 0);+ const naturalHeight = Number(img?.naturalHeight || 0);+ if (naturalWidth && naturalHeight) {+ return { width: naturalWidth, height: naturalHeight };+ }++ return { width: FALLBACK_WIDTH, height: FALLBACK_HEIGHT };+}++function isRenderableImage(img) {+ return (+ !img.classList.contains("thumbnail") &&+ !img.classList.contains("ytp-thumbnail-image") &&+ !img.classList.contains("emoji")+ );+}++function buildCarouselItems(grid) {+ const images = [...grid.querySelectorAll("img")].filter(isRenderableImage);+ const seen = new Set();++ return images+ .map((img) => {+ const wrapper =+ img.closest(".lightbox-wrapper") || img.closest("a.lightbox") || img;+ if (!wrapper || seen.has(wrapper)) {+ return null;+ }++ seen.add(wrapper);+ const anchor = wrapper.matches?.("a.lightbox")+ ? wrapper+ : wrapper.querySelector?.("a.lightbox") || img.closest("a");+ const { width, height } = resolveDimensions(anchor, img);++ return {+ element: wrapper,+ img,+ width,+ height,+ };+ })+ .filter(Boolean);+}++export default function setupImageGridCarousel(grid, helper) {+ if (!grid || grid.dataset.carouselInitialized) {+ return false;+ }++ if (!helper?.renderGlimmer) {+ return false;+ }++ const items = buildCarouselItems(grid);++ if (!items.length) {+ return false;+ }++ grid.dataset.carouselInitialized = "true";+ grid.classList.add("d-image-grid--carousel");++ const mode = grid.dataset.mode || "carousel";++ helper.renderGlimmer(+ grid,+ ImageCarousel,+ {+ items,+ mode,+ },+ { append: false }+ );++ return true;+}diff --git a/frontend/discourse/app/static/prosemirror/components/grid-node-view.gjs b/frontend/discourse/app/static/prosemirror/components/grid-node-view.gjsnew file mode 100644index 00000000000..277485e44f9--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/components/grid-node-view.gjs@@ -0,0 +1,105 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import concatClass from "discourse/helpers/concat-class";+import icon from "discourse/helpers/d-icon";+import { eq } from "discourse/truth-helpers";+import { i18n } from "discourse-i18n";++export default class GridNodeView extends Component {+ // Note: contentDOM is appended to dom in GlimmerNodeView constructor+ // and is a sibling of the Glimmer-rendered content++ constructor() {+ super(...arguments);+ this.args.dom?.classList.add("composer-image-grid");+ this.args.onSetup?.(this);+ }++ get currentMode() {+ return this.args.node.attrs.mode;+ }++ @action+ setMode(mode, event) {+ event.preventDefault();+ const pos = this.args.getPos();+ this.args.view.dispatch(+ this.args.view.state.tr.setNodeMarkup(pos, null, {+ ...this.args.node.attrs,+ mode,+ })+ );+ }++ @action+ removeGrid(event) {+ event.preventDefault();+ event.stopPropagation();+ const pos = this.args.getPos();+ const node = this.args.view.state.doc.nodeAt(pos);+ const tr = this.args.view.state.tr;+ tr.replaceWith(pos, pos + node.nodeSize, node.content);+ this.args.view.dispatch(tr);+ }++ selectNode() {+ this.args.dom.classList.add("ProseMirror-selectednode");+ }++ deselectNode() {+ this.args.dom.classList.remove("ProseMirror-selectednode");+ }++ <template>+ {{~! strip whitespace ~}}<div+ class="composer-image-gallery__mode-buttons"+ role="group"+ contenteditable="false"+ >+ <button+ type="button"+ class={{concatClass+ "composer-image-gallery__mode-btn"+ (if (eq this.currentMode "grid") "is-active")+ }}+ data-mode="grid"+ aria-label={{i18n "composer.grid_mode_grid"}}+ title={{i18n+ "composer.grid_mode_title"+ mode=(i18n "composer.grid_mode_grid")+ }}+ aria-pressed={{if (eq this.currentMode "grid") "true" "false"}}+ {{on "click" (fn this.setMode "grid")}}+ >{{icon "table-cells"}}<span>{{i18n+ "composer.grid_mode_grid"+ }}</span></button>+ <button+ type="button"+ class={{concatClass+ "composer-image-gallery__mode-btn"+ (if (eq this.currentMode "carousel") "is-active")+ }}+ data-mode="carousel"+ aria-label={{i18n "composer.grid_mode_carousel"}}+ title={{i18n+ "composer.grid_mode_title"+ mode=(i18n "composer.grid_mode_carousel")+ }}+ aria-pressed={{if (eq this.currentMode "carousel") "true" "false"}}+ {{on "click" (fn this.setMode "carousel")}}+ >{{icon "image"}}<span>{{i18n+ "composer.grid_mode_carousel"+ }}</span></button>+ </div><button+ type="button"+ class="composer-image-grid__remove-btn"+ title={{i18n "composer.remove_grid"}}+ contenteditable="false"+ {{on "click" this.removeGrid}}+ ><span>{{i18n+ "composer.remove_grid"+ }}</span></button>{{~! strip whitespace ~}}+ </template>+}diff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjsindex 246a988fb85..3e44340e5df 100644--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs@@ -370,7 +370,7 @@ export default class ProsemirrorEditor extends Component {@getPos={{nodeView.getPos}}@dom={{nodeView.dom}}@onSetup={{nodeView.setComponentInstance}}- >{{nodeView.contentDOM}}</nodeView.component>+ />{{~/in-element~}}{{/each}}</template>diff --git a/frontend/discourse/app/static/prosemirror/extensions/grid.js b/frontend/discourse/app/static/prosemirror/extensions/grid.jsindex 3a557660eaa..00368ac1441 100644--- a/frontend/discourse/app/static/prosemirror/extensions/grid.js+++ b/frontend/discourse/app/static/prosemirror/extensions/grid.js@@ -1,86 +1,69 @@-import { bind } from "discourse/lib/decorators";-import { iconHTML } from "discourse/lib/icon-library";-import { i18n } from "discourse-i18n";--class GridNodeView {- constructor(node, view, getPos) {- this.node = node;- this.view = view;- this.getPos = getPos;-- const div = document.createElement("div");- div.className = "composer-image-grid";-- const title = document.createElement("div");- title.className = "composer-image-grid__title";- title.innerHTML = iconHTML("table-cells");- title.prepend(document.createTextNode(i18n("composer.grid_label")));-- div.appendChild(title);-- const contentDiv = document.createElement("div");- div.appendChild(contentDiv);-- this.dom = div;- this.contentDOM = contentDiv;-- this.svg = div.querySelector("svg");- this.svg.setAttribute("alt", i18n("composer.toggle_image_grid"));- this.svg.addEventListener("click", this.iconClickHandler);- }-- @bind- iconClickHandler() {- const pos = this.getPos();- const currentNode = this.view.state.doc.nodeAt(pos);- const tr = this.view.state.tr;-- tr.replaceWith(pos, pos + currentNode.nodeSize, currentNode.content);- this.view.dispatch(tr);- }-- selectNode() {- this.dom.classList.add("ProseMirror-selectednode");- }-- deselectNode() {- this.dom.classList.remove("ProseMirror-selectednode");- }-- update(node) {- return node.type === this.node.type;- }-- destroy() {- this.svg.removeEventListener("click", this.iconClickHandler);- }-}+import GridNodeView from "../components/grid-node-view";+import GlimmerNodeView from "../lib/glimmer-node-view";++const createGridNodeView =+ ({ getContext }) =>+ (node, view, getPos) =>+ new GlimmerNodeView({+ node,+ view,+ getPos,+ getContext,+ component: GridNodeView,+ name: "grid",+ hasContent: true,+ });-/** @type {RichEditorExtension} */const extension = {nodeSpec: {grid: {content: "block+",group: "block",+ attrs: {+ mode: { default: "grid" },+ },createGapCursor: true,parseDOM: [- { tag: "div.d-image-grid" },- { tag: "div.composer-image-grid" },+ {+ tag: "div.d-image-grid",+ getAttrs(dom) {+ return {+ mode: dom.getAttribute("data-mode") || "grid",+ };+ },+ },+ {+ tag: "div.composer-image-grid",+ getAttrs(dom) {+ return {+ mode: dom.getAttribute("data-mode") || "grid",+ };+ },+ },],- toDOM() {- return ["div", { class: "composer-image-grid" }, 0];+ toDOM(node) {+ return [+ "div",+ {+ class: "composer-image-grid",+ "data-mode": node.attrs.mode,+ },+ 0,+ ];},},},nodeViews: {- grid: GridNodeView,+ grid: createGridNodeView,},parse: {bbcode_open(state, token) {if (token.attrGet("class") === "d-image-grid") {- state.openNode(state.schema.nodes.grid);+ state.openNode(state.schema.nodes.grid, {+ mode: token.attrGet("data-mode") || "grid",+ });return true;}},@@ -94,7 +77,11 @@ const extension = {serializeNode: {grid: (state, node) => {- state.write("\n[grid]\n\n");+ let attrs = "";+ if (node.attrs.mode && node.attrs.mode !== "grid") {+ attrs += ` mode=${node.attrs.mode}`;+ }+ state.write(`\n[grid${attrs}]\n\n`);state.renderContent(node.content);state.write("\n[/grid]\n\n");},@@ -111,7 +98,6 @@ const extension = {plugins({ pmState: { Plugin } }) {return new Plugin({appendTransaction(transactions, oldState, newState) {- // Only process if the document actually changedif (!transactions.some((tr) => tr.docChanged)) {return null;}@@ -119,7 +105,6 @@ const extension = {const tr = newState.tr;let modified = false;- // Process grids from end to beginning to avoid position shiftsconst gridNodes = [];newState.doc.descendants((node, pos) => {if (node.type.name === "grid") {@@ -128,7 +113,6 @@ const extension = {});gridNodes.reverse().forEach(({ node, pos }) => {- // If grid is completely empty, remove itif (node.childCount === 0) {tr.delete(pos, pos + node.nodeSize);modified = true;@@ -136,12 +120,11 @@ const extension = {}const changes = [];- let currentPos = pos + 1; // Start inside the grid node+ let currentPos = pos + 1;node.content.forEach((child) => {if (child.type.name === "paragraph") {if (child.content.size === 0) {- // Only remove empty paragraph if grid has other contentif (node.childCount > 1) {changes.push({type: "remove",@@ -150,7 +133,6 @@ const extension = {});}} else {- // Split paragraphs with multiple imagesconst images = [];child.content.forEach((grandchild) => {if (grandchild.type.name === "image") {diff --git a/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.js b/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.jsindex 4227741b348..83d59ee78dc 100644--- a/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.js+++ b/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.js@@ -40,6 +40,7 @@ export default class GlimmerNodeView {this.dom.classList.add(`composer-${name}-node`);if (hasContent) {this.contentDOM = document.createElement(node.isInline ? "span" : "div");+ this.dom.appendChild(this.contentDOM);}}diff --git a/frontend/discourse/tests/integration/components/image-carousel-test.gjs b/frontend/discourse/tests/integration/components/image-carousel-test.gjsnew file mode 100644index 00000000000..badf40501d4--- /dev/null+++ b/frontend/discourse/tests/integration/components/image-carousel-test.gjs@@ -0,0 +1,89 @@+import { click, render, triggerKeyEvent } from "@ember/test-helpers";+import { setupRenderingTest } from "ember-qunit";+import hbs from "htmlbars-inline-precompile";+import { module, test } from "qunit";++module("Integration | Component | image-carousel", function (hooks) {+ setupRenderingTest(hooks);++ const items = [+ {+ element: document.createElement("div"),+ img: document.createElement("img"),+ width: 100,+ height: 100,+ },+ {+ element: document.createElement("div"),+ img: document.createElement("img"),+ width: 100,+ height: 100,+ },+ {+ element: document.createElement("div"),+ img: document.createElement("img"),+ width: 100,+ height: 100,+ },+ ];++ test("it renders and navigates via buttons", async function (assert) {+ this.set("data", { items, mode: "carousel" });++ await render(hbs`<ImageCarousel @data={{this.data}} />`);++ assert+ .dom(".d-image-carousel__slide[data-index='0']")+ .hasClass("is-active");++ await click(".d-image-carousel__nav--next");+ assert+ .dom(".d-image-carousel__slide[data-index='1']")+ .hasClass("is-active");++ await click(".d-image-carousel__nav--prev");+ assert+ .dom(".d-image-carousel__slide[data-index='0']")+ .hasClass("is-active");+ });++ test("it wraps around in carousel mode", async function (assert) {+ this.set("data", { items, mode: "carousel" });++ await render(hbs`<ImageCarousel @data={{this.data}} />`);++ assert+ .dom(".d-image-carousel__slide[data-index='0']")+ .hasClass("is-active");++ await click(".d-image-carousel__nav--prev");+ assert+ .dom(".d-image-carousel__slide[data-index='2']")+ .hasClass("is-active");++ await click(".d-image-carousel__nav--next");+ assert+ .dom(".d-image-carousel__slide[data-index='0']")+ .hasClass("is-active");+ });++ test("it handles keyboard navigation", async function (assert) {+ this.set("data", { items, mode: "carousel" });++ await render(hbs`<ImageCarousel @data={{this.data}} />`);++ assert+ .dom(".d-image-carousel__slide[data-index='0']")+ .hasClass("is-active");++ await triggerKeyEvent(".d-image-carousel__track", "keydown", "ArrowRight");+ assert+ .dom(".d-image-carousel__slide[data-index='1']")+ .hasClass("is-active");++ await triggerKeyEvent(".d-image-carousel__track", "keydown", "ArrowLeft");+ assert+ .dom(".d-image-carousel__slide[data-index='0']")+ .hasClass("is-active");+ });+});diff --git a/frontend/discourse/tests/unit/lib/image-grid-carousel-test.js b/frontend/discourse/tests/unit/lib/image-grid-carousel-test.jsnew file mode 100644index 00000000000..f8a609febca--- /dev/null+++ b/frontend/discourse/tests/unit/lib/image-grid-carousel-test.js@@ -0,0 +1,55 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import setupImageGridCarousel from "discourse/lib/image-grid-carousel";++module("Unit | setupImageGridCarousel", function (hooks) {+ setupTest(hooks);++ hooks.afterEach(function () {+ document.getElementById("qunit-fixture").innerHTML = "";+ });++ test("returns false when grid is null", function (assert) {+ assert.false(setupImageGridCarousel(null, {}));+ });++ test("returns false when grid is already initialized", function (assert) {+ const grid = document.createElement("div");+ grid.dataset.carouselInitialized = "true";+ assert.false(setupImageGridCarousel(grid, {}));+ });++ test("returns false when helper has no renderGlimmer", function (assert) {+ const grid = document.createElement("div");+ assert.false(setupImageGridCarousel(grid, {}));+ });++ test("returns false when no valid images are found", function (assert) {+ document.getElementById("qunit-fixture").innerHTML =+ `<div class="d-image-grid"></div>`;+ const grid = document.querySelector(".d-image-grid");+ const helper = { renderGlimmer: () => {} };+ assert.false(setupImageGridCarousel(grid, helper));+ });++ test("initializes carousel and returns true when images are found", function (assert) {+ document.getElementById("qunit-fixture").innerHTML = `+ <div class="d-image-grid">+ <img src="/images/avatar.png" width="10" height="10">+ <img src="/images/avatar.png" width="10" height="10">+ </div>+ `;+ const grid = document.querySelector(".d-image-grid");+ let rendered = false;+ const helper = {+ renderGlimmer: () => {+ rendered = true;+ },+ };++ assert.true(setupImageGridCarousel(grid, helper));+ assert.true(rendered);+ assert.strictEqual(grid.dataset.carouselInitialized, "true");+ assert.true(grid.classList.contains("d-image-grid--carousel"));+ });+});diff --git a/spec/system/image_grid_carousel_spec.rb b/spec/system/image_grid_carousel_spec.rbnew file mode 100644index 00000000000..c73ea6509ba--- /dev/null+++ b/spec/system/image_grid_carousel_spec.rb@@ -0,0 +1,111 @@+# frozen_string_literal: true++describe "Image Carousel", type: :system do+ fab!(:current_user, :admin)+ fab!(:upload1) do+ UploadCreator.new(file_from_fixtures("logo.png", "images"), "logo.png").create_for(+ current_user.id,+ )+ end+ fab!(:upload2) do+ UploadCreator.new(file_from_fixtures("logo.jpg", "images"), "logo.jpg").create_for(+ current_user.id,+ )+ end++ let(:composer) { PageObjects::Components::Composer.new }+ let(:topic_page) { PageObjects::Pages::Topic.new }++ before { sign_in(current_user) }++ it "renders a carousel in the post stream" do+ post = create_post(raw: <<~MD)+ [grid mode=carousel]+ + + [/grid]+ MD++ topic_page.visit_topic(post.topic, post_number: post.post_number)+ carousel = PageObjects::Components::ImageCarousel.new(post.post_number)++ expect(carousel).to have_carousel+ expect(carousel).to have_mode("carousel")+ expect(carousel).to have_track+ expect(carousel).to have_slides(count: 2)+ end++ it "wraps around in carousel mode" do+ post = create_post(raw: <<~MD)+ [grid mode=carousel]+ + + [/grid]+ MD++ topic_page.visit_topic(post.topic, post_number: post.post_number)+ carousel = PageObjects::Components::ImageCarousel.new(post.post_number)++ expect(carousel).to have_active_slide_index(0)++ carousel.click_prev+ expect(carousel).to have_active_slide_index(1)++ carousel.click_next+ expect(carousel).to have_active_slide_index(0)++ carousel.click_next+ expect(carousel).to have_active_slide_index(1)++ carousel.click_next+ expect(carousel).to have_active_slide_index(0)+ end++ it "keyboard navigation wraps around in carousel mode" do+ post = create_post(raw: <<~MD)+ [grid mode=carousel]+ + + [/grid]+ MD++ topic_page.visit_topic(post.topic, post_number: post.post_number)+ carousel = PageObjects::Components::ImageCarousel.new(post.post_number)++ carousel.focus_track++ send_keys(:left)+ expect(carousel).to have_active_slide_index(1)++ wait_for_timeout(150) # we throttle keyboard actions++ send_keys(:right)+ expect(carousel).to have_active_slide_index(0)+ end++ it "allows changing modes in the rich text editor", js: true do+ SiteSetting.rich_editor = true+ SiteSetting.post_menu_hidden_items = ""+ current_user.user_option.update!(composition_mode: 1)++ post = create_post(raw: <<~MD)+ [grid mode=carousel]+ + [/grid]+ MD++ topic_page.visit_topic(post.topic, post_number: post.post_number)+ expect(topic_page).to have_post_action_button(post, :edit)+ topic_page.click_post_action_button(post, :edit)++ expect(composer).to be_opened+ expect(composer).to have_rich_editor_active+ expect(composer.image_grid).to have_mode_select++ composer.image_grid.select_mode("Grid")+ expect(composer.image_grid).to have_selected_mode("grid")++ composer.toggle_rich_editor+ expect(composer.composer_input.value).to include("[grid]")+ end+enddiff --git a/spec/system/page_objects/components/composer_image_grid.rb b/spec/system/page_objects/components/composer_image_grid.rbindex 0427560407a..abef3ab75b4 100644--- a/spec/system/page_objects/components/composer_image_grid.rb+++ b/spec/system/page_objects/components/composer_image_grid.rb@@ -51,6 +51,23 @@ module PageObjects@rich_editor.has_css?(".composer-image-grid .composer-image-node img", count: count) &&@rich_editor.has_no_css?(".composer-image-grid .composer-image-grid")end++ def has_mode_select?+ @rich_editor.has_css?(".composer-image-gallery__mode-buttons")+ end++ def select_mode(mode)+ @rich_editor.find(".composer-image-gallery__mode-btn[data-mode='#{mode.downcase}']").click+ self+ end++ def has_selected_mode?(value)+ @rich_editor.has_css?(".composer-image-gallery__mode-btn[data-mode='#{value}'].is-active")+ end++ def mode_value+ @rich_editor.find(".composer-image-gallery")["data-mode"]+ endendendenddiff --git a/spec/system/page_objects/components/image_grid_carousel.rb b/spec/system/page_objects/components/image_grid_carousel.rbnew file mode 100644index 00000000000..8bef334f286--- /dev/null+++ b/spec/system/page_objects/components/image_grid_carousel.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class ImageCarousel < PageObjects::Components::Base+ def initialize(post_number)+ @post_number = post_number+ end++ def has_carousel?+ has_css?(carousel_selector)+ end++ def has_track?+ has_css?("#{carousel_selector} .d-image-carousel__track")+ end++ def has_mode?(mode)+ has_css?("#{carousel_selector} .d-image-carousel.d-image-carousel--#{mode}")+ end++ def has_slides?(count:)+ has_css?("#{carousel_selector} .d-image-carousel__slide", count: count)+ end++ def has_active_slide?+ has_css?("#{carousel_selector} .d-image-carousel__slide.is-active")+ end++ def has_active_slide_index?(index)+ has_css?("#{carousel_selector} .d-image-carousel__slide[data-index='#{index}'].is-active")+ end++ def click_next+ find("#{carousel_selector} .d-image-carousel__nav--next").click+ end++ def click_prev+ find("#{carousel_selector} .d-image-carousel__nav--prev").click+ end++ def next_button_disabled?+ find("#{carousel_selector} .d-image-carousel__nav--next").disabled?+ end++ def prev_button_disabled?+ find("#{carousel_selector} .d-image-carousel__nav--prev").disabled?+ end++ def focus_track+ find("#{carousel_selector} .d-image-carousel__track").click+ self+ end++ private++ def carousel_selector+ "#post_#{@post_number} .d-image-grid--carousel"+ end+ end+ end+end