Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions app/controllers/concerns/uploads_gallery_images.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Saves files posted by a page's form (the gallery's no-JavaScript fallback)
# the same way the gallery's drop zone does: through ImageUploadService, so
# upload bandwidth is charged and gallery activity is recorded.
module UploadsGalleryImages
extend ActiveSupport::Concern

private

# Returns the error message for each file that couldn't be saved.
def upload_gallery_images(content, files)
Array(files).compact_blank.filter_map do |file|
result = ImageUploadService.upload(user: current_user, content: content, file: file)
if result.success?
GalleryActivity.record!(content, user: current_user, action: :image_added, image: result.image)
nil
else
result.error
end
end
end
end
13 changes: 3 additions & 10 deletions app/controllers/content_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# TODO: we should probably spin off an Api::ContentController for #api_sort and anything else
# api-wise we need
class ContentController < ApplicationController
include UploadsGalleryImages

before_action :authenticate_user!, except: [:show, :changelog, :api_sort] \
+ Rails.application.config.content_types[:all_non_universe].map { |type| type.name.downcase.pluralize.to_sym }

Expand Down Expand Up @@ -516,16 +518,7 @@ def upload_files image_uploads_list, content_type, content_id
content = content_type.to_s.safe_constantize&.find_by(id: content_id)
return if content.nil?

upload_errors = []

image_uploads_list.each do |image_data|
result = ImageUploadService.upload(user: current_user, content: content, file: image_data)
if result.success?
GalleryActivity.record!(content, user: current_user, action: :image_added, image: result.image)
else
upload_errors << result.error
end
end
upload_errors = upload_gallery_images(content, image_uploads_list)

if upload_errors.any? { |error| error.include?('upload bandwidth') }
upload_errors << "<a href='#{subscription_path}' class='btn white black-text center-align'>Get more</a>"
Expand Down
30 changes: 28 additions & 2 deletions app/controllers/timelines_controller.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
class TimelinesController < ApplicationController
include ApplicationHelper
include UploadsGalleryImages

before_action :authenticate_user!, except: [:show]
before_action :set_timeline, only: [:show, :edit, :update, :destroy, :toggle_archive, :toggle_favorite]
before_action :set_timeline, only: [:show, :edit, :update, :destroy, :toggle_archive, :toggle_favorite, :gallery, :cover]

before_action :set_navbar_color
before_action :set_sidenav_expansion

before_action :require_premium_plan, only: [:new, :create]
before_action :require_timeline_read_permission, only: [:show]
before_action :require_timeline_edit_permission, only: [:edit, :update]
before_action :require_timeline_edit_permission, only: [:edit, :update, :gallery, :cover]
before_action :require_timeline_delete_permission, only: [:destroy]

# GET /timelines
Expand Down Expand Up @@ -83,6 +84,22 @@ def show
@page_title = @timeline.name
end

# GET /timelines/1/gallery
# The editor's Images window loads this over XHR when it first opens; a
# plain request (no JavaScript) gets it as a page of its own.
def gallery
if request.xhr?
render partial: 'timelines/gallery_panel', locals: { timeline: @timeline }
else
@page_title = "Images for #{@timeline.name.presence || 'Untitled Timeline'}"
end
end

# GET /timelines/1/cover
def cover
render partial: 'timelines/edit/cover', locals: { timeline: @timeline }
end

# GET /timelines/new
def new
timeline = current_user.timelines.create(name: '', universe: @universe_scope).reload
Expand Down Expand Up @@ -149,6 +166,15 @@ def create

# PATCH/PUT /timelines/1
def update
# The gallery's no-JavaScript form posts files here; everything else on
# the editor saves over XHR and gets JSON back.
gallery_files = params.dig(:timeline, :image_uploads_attributes)&.values&.map { |attrs| attrs[:src] }&.compact_blank
if gallery_files.present?
errors = upload_gallery_images(@timeline, gallery_files)
flash[:alert] = errors.to_sentence if errors.any?
return redirect_to gallery_timeline_path(@timeline)
end

# Moving a timeline between universes is only for its owner
attributes = @timeline.user_id == current_user.id ? timeline_params : timeline_params.except(:universe_id)

Expand Down
22 changes: 19 additions & 3 deletions app/views/content/_hero_header.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,29 @@
can_see_private = user_signed_in? && ContentImageAuthorization.can_manage?(current_user, content)
# Shared with every page-banner header; see ImagePresets::BANNER_BOX_CLASSES.
hero_classes = local_assigns[:height_classes] || ImagePresets::BANNER_BOX_CLASSES

# Pages without a ContentSerializer (timelines) pass these directly.
hero_icon = local_assigns[:icon] || serialized_content.class_icon
hero_color = local_assigns[:color] || serialized_content.class_color
hero_title = local_assigns[:title] || content.name
# Optional: an Alpine expression that keeps the title in step with inline renames.
title_x_text = local_assigns[:title_x_text]
# Optional: HTML for the banner's top-right corner (the timeline editor's images button). The
# corner, not the title bar, because the editors' fixed side tabs overlap the title bar.
corner_actions = local_assigns[:corner_actions]
%>
<div class="relative w-full <%= hero_classes %> bg-gray-900 overflow-hidden">
<%= content_image_tag content, :banner,
include_private: can_see_private,
class: "w-full h-full object-cover",
alt: "#{content.name} banner image" %>

<% if corner_actions.present? %>
<div class="absolute top-3 right-3 z-10">
<%= corner_actions %>
</div>
<% end %>

<!-- Content overlay with solid background -->
<div class="absolute bottom-0 left-0 right-0 p-6 lg:p-8">
<div class="max-w-4xl mx-auto">
Expand All @@ -19,16 +35,16 @@
<div class="flex items-center space-x-4">
<!-- Premium page icon -->
<div class="flex-shrink-0">
<div class="w-12 h-12 <%= serialized_content.class_color %> rounded-xl flex items-center justify-center shadow-lg ring-2 ring-white ring-opacity-20">
<i class="material-icons text-white text-xl font-light"><%= serialized_content.class_icon %></i>
<div class="w-12 h-12 <%= hero_color %> rounded-xl flex items-center justify-center shadow-lg ring-2 ring-white ring-opacity-20">
<i class="material-icons text-white text-xl font-light"><%= hero_icon %></i>
</div>
</div>

<!-- Enhanced typography section -->
<div class="flex-1 min-w-0">
<!-- Page name with refined typography -->
<h1 class="text-xl lg:text-2xl font-semibold text-white truncate mb-1 tracking-tight leading-tight page-title">
<%= link_to content.name, content %>
<%= link_to hero_title, content, 'x-text': title_x_text %>
</h1>

<!-- Universe information moved to right sidebar -->
Expand Down
6 changes: 6 additions & 0 deletions app/views/timelines/_gallery_panel.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<%# The shared content gallery for a timeline. Used by the editor's Images window (loaded over XHR) and timelines#gallery. %>
<%# Locals: timeline %>
<%# The form only matters to the gallery's no-JavaScript upload fallback; timelines#update saves its files. %>
<%= form_for timeline, url: timeline_path(timeline), method: :patch, html: { multipart: true } do |f| %>
<%= render partial: 'content/edit/gallery_panel', locals: { raw_content: timeline, content: timeline, f: f } %>
<% end %>
117 changes: 116 additions & 1 deletion app/views/timelines/edit.html.erb
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
<div x-data="timelineEditor()" class="min-h-screen flex flex-col bg-gray-50 dark:bg-gray-900">
<%# Banner, as on other content editors. Narrows with the side panels like the main column does. %>
<%# Its button opens the Images window; the banner is re-fetched from timelines#cover when that window closes. %>
<div x-ref="coverSlot"
data-cover-url="<%= cover_timeline_path(@timeline) %>"
:class="{ 'lg:ml-80': showLeftSidebar && isDesktop, 'lg:mr-96': showRightSidebar && isDesktop }"
@click="if ($event.target.closest('[data-open-gallery]')) { $event.preventDefault(); openGallery() }">
<%= render 'timelines/edit/cover', timeline: @timeline %>
</div>

<!-- Three-Column Layout with Pull-Out Tabs -->
<div class="flex-1 flex min-h-0 relative">

Expand Down Expand Up @@ -127,7 +136,9 @@
</div>

<!-- Main Content Area -->
<main class="flex-1 min-h-0"
<%# min-w-0: as a flex item <main> otherwise can't shrink below its content's widest unbreakable row, %>
<%# which made the editor about 150px wider than a phone screen. %>
<main class="flex-1 min-h-0 min-w-0"
:class="{
'lg:ml-80': showLeftSidebar && isDesktop,
'lg:mr-96': showRightSidebar && isDesktop
Expand Down Expand Up @@ -411,6 +422,9 @@

<%# Share Modal Partial %>
<%= render 'timelines/edit/share_modal', timeline: @timeline %>

<%# Images Modal Partial %>
<%= render 'timelines/edit/gallery_modal', timeline: @timeline %>
</div>

<!-- Timeline Editor Initialization Data (for external JS files) -->
Expand All @@ -437,6 +451,7 @@ function timelineEditor() {
showMetaPanel: false,
showLinkModal: false,
showShareModal: false,
showGalleryModal: false,
showFilters: false,
showMobileFilters: false,
linkingEventId: null,
Expand Down Expand Up @@ -513,8 +528,108 @@ function timelineEditor() {
tempTitle: '<%= j(@timeline.name) %>',
tempSubtitle: '<%= j(@timeline.subtitle) %>',

// Images window: 'idle' until first opened, then 'loading' / 'loaded' / 'error'
galleryState: 'idle',
modalReturnFocus: null,

openGallery() {
this.showGalleryModal = true;
if (this.galleryState === 'idle' || this.galleryState === 'error') this.loadGallery();
},

async loadGallery() {
this.galleryState = 'loading';
try {
const response = await fetch(this.$refs.galleryModal.dataset.galleryUrl, {
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/html' },
credentials: 'same-origin'
});
if (!response.ok || response.redirected) throw new Error(`Gallery request failed (${response.status})`);
// Stimulus connects the gallery, lightbox and framing editor as soon as they're in the DOM.
this.$refs.galleryBody.innerHTML = await response.text();
this.galleryState = 'loaded';
} catch (error) {
console.error(error);
this.galleryState = 'error';
}
},

closeGallery() {
this.showGalleryModal = false;
if (this.galleryState === 'loaded') this.refreshCover();
},

// Uploads, deletes, reordering and cover changes can all change the cover, so re-render the slot.
async refreshCover() {
const slot = this.$refs.coverSlot;
try {
const response = await fetch(slot.dataset.coverUrl, {
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/html' },
credentials: 'same-origin'
});
if (!response.ok || response.redirected) return;
const hadFocus = slot.contains(document.activeElement);
slot.innerHTML = await response.text();
if (hadFocus) slot.querySelector('[data-open-gallery]')?.focus();
} catch (error) {
console.error('Could not refresh the cover image', error);
}
},

// Escape closes, Tab stays inside. While the gallery's image viewer or framing editor is open
// on top, keys are theirs: focus can still be in this window, and this handler runs first.
// (Named rather than passed a callback: an arrow function in an HTML attribute trips up
// the HTML parser the tests use, which then drops the element's other attributes.)
modalKeydown(event, modal, name) {
if (event.defaultPrevented) return;
if (document.querySelector('[data-lightbox-target="modal"]:not(.hidden), [data-image-editor-target="modal"]:not(.hidden)')) return;
if (event.key === 'Escape') {
event.preventDefault();
if (name === 'gallery') this.closeGallery();
if (name === 'share') this.showShareModal = false;
return;
}
if (event.key !== 'Tab') return;

const focusable = Array.from(modal.querySelectorAll(
'a[href], button:not([disabled]), input:not([disabled]):not([type=hidden]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
)).filter(el => el.offsetParent !== null);
if (focusable.length === 0) return;

const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && (document.activeElement === first || !modal.contains(document.activeElement))) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (document.activeElement === last || !modal.contains(document.activeElement))) {
event.preventDefault();
first.focus();
}
},

// On open: remember what had focus, stop the page scrolling behind, focus the window.
// On close: put everything back.
modalToggled(open, modal) {
if (open) {
this.modalReturnFocus = document.activeElement;
document.body.style.overflow = 'hidden';
this.$nextTick(() => {
const target = modal.querySelector('[aria-label="Close"]') || modal.querySelector('button, a[href], input');
target?.focus();
});
} else {
document.body.style.overflow = '';
const returnTo = this.modalReturnFocus;
this.modalReturnFocus = null;
if (returnTo && document.contains(returnTo)) returnTo.focus();
}
},

// Initialize method
init() {
this.$watch('showGalleryModal', open => this.modalToggled(open, this.$refs.galleryModal));
this.$watch('showShareModal', open => this.modalToggled(open, this.$refs.shareModal));

// Initialize sidebar state
this.initializeSidebarState();
this.setupResizeListener();
Expand Down
24 changes: 24 additions & 0 deletions app/views/timelines/edit/_cover.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<%# The editor's banner: the same hero header as other content editors, plus a button into the Images window. %>
<%# Locals: timeline %>
<%# Re-rendered from timelines#cover when the Images window closes. The button links to timelines#gallery so it %>
<%# still works without JavaScript; the editor intercepts clicks on [data-open-gallery]. %>
<% has_cover = content_cover_image?(timeline, include_private: true) %>
<% images_button = capture do %>
<%= link_to gallery_timeline_path(timeline),
data: { open_gallery: true },
class: "inline-flex items-center px-3 py-1.5 rounded-lg bg-white bg-opacity-90 hover:bg-opacity-100 text-sm font-medium text-gray-800 shadow focus:outline-none focus:ring-2 focus:ring-white transition-colors" do %>
<i class="material-icons text-base sm:mr-1.5"><%= has_cover ? 'photo_library' : 'add_photo_alternate' %></i>
<span class="sr-only sm:not-sr-only"><%= has_cover ? 'Edit images' : 'Add cover image' %></span>
<% end %>
<% end %>

<%= render partial: 'content/hero_header', locals: {
content: timeline,
serialized_content: nil,
icon: Timeline.icon,
color: Timeline.color,
title: timeline.name.presence || 'Untitled Timeline',
title_x_text: "timelineName || 'Untitled Timeline'",
height_classes: 'h-32 md:h-40 lg:h-48',
corner_actions: images_button
} %>
Loading
Loading