diff --git a/app/assets/builds/maglev/tailwind.css b/app/assets/builds/maglev/tailwind.css index 2aa76d6fc..9a7eafeb0 100644 --- a/app/assets/builds/maglev/tailwind.css +++ b/app/assets/builds/maglev/tailwind.css @@ -505,6 +505,9 @@ .-mr-1 { margin-right: calc(var(--spacing) * -1); } + .mr-4 { + margin-right: calc(var(--spacing) * 4); + } .-mb-5 { margin-bottom: calc(var(--spacing) * -5); } @@ -544,6 +547,9 @@ .block { display: block; } + .contents { + display: contents; + } .flex { display: flex; } @@ -556,6 +562,9 @@ .inline { display: inline; } + .inline\! { + display: inline !important; + } .inline-block { display: inline-block; } @@ -860,6 +869,12 @@ .cursor-pointer { cursor: pointer; } + .resize { + resize: both; + } + .resize-y { + resize: vertical; + } .appearance-none { appearance: none; } @@ -1669,12 +1684,18 @@ text-transform: uppercase; } } + .lowercase { + text-transform: lowercase; + } .uppercase { text-transform: uppercase; } .italic { font-style: italic; } + .line-through { + text-decoration-line: line-through; + } .underline { text-decoration-line: underline; } @@ -1762,6 +1783,16 @@ .outline-editor-primary { outline-color: var(--color-editor-primary); } + .blur { + --tw-blur: blur(8px); + filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,); + } + .filter { + filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,); + } + .filter\! { + filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,) !important; + } .backdrop-blur-sm { --tw-backdrop-blur: blur(var(--blur-sm)); -webkit-backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,); @@ -2999,6 +3030,7 @@ --tw-ring-inset: inset; } height: calc(var(--number-of-rows) * var(--spacing) * 8); + resize: vertical; overflow: auto; --tw-leading: calc(var(--spacing) * 6); line-height: calc(var(--spacing) * 6); @@ -3334,6 +3366,59 @@ inherits: false; initial-value: solid; } +@property --tw-blur { + syntax: "*"; + inherits: false; +} +@property --tw-brightness { + syntax: "*"; + inherits: false; +} +@property --tw-contrast { + syntax: "*"; + inherits: false; +} +@property --tw-grayscale { + syntax: "*"; + inherits: false; +} +@property --tw-hue-rotate { + syntax: "*"; + inherits: false; +} +@property --tw-invert { + syntax: "*"; + inherits: false; +} +@property --tw-opacity { + syntax: "*"; + inherits: false; +} +@property --tw-saturate { + syntax: "*"; + inherits: false; +} +@property --tw-sepia { + syntax: "*"; + inherits: false; +} +@property --tw-drop-shadow { + syntax: "*"; + inherits: false; +} +@property --tw-drop-shadow-color { + syntax: "*"; + inherits: false; +} +@property --tw-drop-shadow-alpha { + syntax: ""; + inherits: false; + initial-value: 100%; +} +@property --tw-drop-shadow-size { + syntax: "*"; + inherits: false; +} @property --tw-backdrop-blur { syntax: "*"; inherits: false; @@ -3439,6 +3524,19 @@ --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 #0000; --tw-outline-style: solid; + --tw-blur: initial; + --tw-brightness: initial; + --tw-contrast: initial; + --tw-grayscale: initial; + --tw-hue-rotate: initial; + --tw-invert: initial; + --tw-opacity: initial; + --tw-saturate: initial; + --tw-sepia: initial; + --tw-drop-shadow: initial; + --tw-drop-shadow-color: initial; + --tw-drop-shadow-alpha: 100%; + --tw-drop-shadow-size: initial; --tw-backdrop-blur: initial; --tw-backdrop-brightness: initial; --tw-backdrop-contrast: initial; diff --git a/app/assets/stylesheets/maglev/tailwind.css.erb b/app/assets/stylesheets/maglev/tailwind.css.erb index 018d7f4f8..744931cb2 100644 --- a/app/assets/stylesheets/maglev/tailwind.css.erb +++ b/app/assets/stylesheets/maglev/tailwind.css.erb @@ -40,7 +40,7 @@ .ProseMirror { @apply block py-2 px-3 rounded bg-gray-100 text-gray-800 focus:outline-none focus:ring focus:ring-inset focus:ring-2 focus:ring-editor-primary/50 placeholder-gray-500; - @apply h-[calc(var(--number-of-rows)*var(--spacing)*8)] overflow-auto leading-6; + @apply h-[calc(var(--number-of-rows)*var(--spacing)*8)] overflow-auto resize-y leading-6; overflow-wrap: break-word; word-wrap: break-word; diff --git a/app/components/maglev/editor/settings/text/richtext_component.html.erb b/app/components/maglev/editor/settings/text/richtext_component.html.erb index 97f18c566..ae245b7ba 100644 --- a/app/components/maglev/editor/settings/text/richtext_component.html.erb +++ b/app/components/maglev/editor/settings/text/richtext_component.html.erb @@ -16,6 +16,7 @@ options: { value: value, line_break: definition.options[:line_break], + rows: definition.options[:nb_rows], edit_link_path: fetch_path(:edit_link_path) } ) %> diff --git a/app/components/maglev/section_component.rb b/app/components/maglev/section_component.rb index 3de31bc6d..830ec6e72 100644 --- a/app/components/maglev/section_component.rb +++ b/app/components/maglev/section_component.rb @@ -4,12 +4,12 @@ # we need to move it along with the PageComponent and BlockComponent # to a separate folder (content?) -# rubocop:disable Metrics/ClassLength module Maglev class SectionComponent < BaseComponent include TagHelper extend Forwardable + def_delegators :parent, :site, :page, :config attr_reader :parent, :id, :type, :settings, :attributes, :definition, :templates_root_path, @@ -35,8 +35,11 @@ def dom_id @dom_id ||= "section-#{id}" end + # the lock version of the store the section content comes from + # (stamped by the sections content fetcher, even for site scoped sections + # whose content lives in the global site scoped store) def lock_version - @lock_version ||= lock_source&.lock_version || '0' + attributes[:lock_version] || '0' end def dom_data @@ -68,10 +71,6 @@ def render private - def lock_source - definition&.site_scoped? ? site : page - end - def build_block_list build_blocks(attributes[:blocks]) end @@ -140,4 +139,3 @@ def inspect_fields end end end -# rubocop:enable Metrics/ClassLength diff --git a/app/components/maglev/uikit/section_toolbar/top_right_corner_component.html.erb b/app/components/maglev/uikit/section_toolbar/top_right_corner_component.html.erb index 75b50f0a2..b78de82d2 100644 --- a/app/components/maglev/uikit/section_toolbar/top_right_corner_component.html.erb +++ b/app/components/maglev/uikit/section_toolbar/top_right_corner_component.html.erb @@ -15,6 +15,12 @@ <%= render Maglev::Uikit::IconComponent.new(name: 'settings') %> <% end if blocks? %> + <% section = helpers.current_maglev_page_content.find_section(id) %> + <% store = helpers.current_maglev_page_content.find_store(section.store_handle) %> + <% if store.addable_sections.include?(section.definition) %> + <%= render 'maglev/editor/sections/clone_button', section: section, button_classes: button_classes %> + <% end %> + <%= button_to paths[:delete], method: :delete, class: button_classes, data: { turbo_method: :delete, turbo_confirm: t('maglev.editor.sections.index.confirm_delete') }, form: { @@ -25,4 +31,4 @@ } do %> <%= render Maglev::Uikit::IconComponent.new(name: 'delete_bin') %> <% end %> - \ No newline at end of file + diff --git a/app/controllers/concerns/maglev/editor/lock_version_concern.rb b/app/controllers/concerns/maglev/editor/lock_version_concern.rb index 3b93050c4..117ec293f 100644 --- a/app/controllers/concerns/maglev/editor/lock_version_concern.rb +++ b/app/controllers/concerns/maglev/editor/lock_version_concern.rb @@ -11,8 +11,13 @@ module LockVersionConcern private + # NOTE: we can't always rely on the lock version of the store the section was fetched + # from: a site scoped section is listed in a layout store (its "slot") but its content + # lives in the global site scoped store, which is what the content services update. + # Fortunately, the sections content fetcher stamps each section with the lock version + # of the store its content actually comes from, so we use it whenever possible. def source_lock_version - sections_store.lock_version || 0 + @section ? @section.lock_version : (sections_store.lock_version || 0) end end end diff --git a/app/controllers/maglev/editor/section_blocks_controller.rb b/app/controllers/maglev/editor/section_blocks_controller.rb index 6ac82ad0c..f413af0d1 100644 --- a/app/controllers/maglev/editor/section_blocks_controller.rb +++ b/app/controllers/maglev/editor/section_blocks_controller.rb @@ -74,7 +74,7 @@ def sections_store end def update_section_block - services.update_section_block.call( + @updated_store = services.update_section_block.call( store: sections_store, section_id: @section.id, block_id: @section_block.id, diff --git a/app/controllers/maglev/editor/sections_controller.rb b/app/controllers/maglev/editor/sections_controller.rb index c35ba4e33..37a957875 100644 --- a/app/controllers/maglev/editor/sections_controller.rb +++ b/app/controllers/maglev/editor/sections_controller.rb @@ -10,7 +10,7 @@ class SectionsController < Maglev::Editor::BaseController helper_method :source_lock_version, :addable_section_categories before_action :ensure_turbo_frame_request, only: [:new] - before_action :set_section, only: %i[edit update destroy] + before_action :set_section, only: %i[edit update destroy clone] before_action :set_sections_store_content, only: %i[new create] def show @@ -54,6 +54,26 @@ def destroy redirect_to_sections_path end + def clone + store = services.fetch_sections_store.call(page: current_maglev_page, handle: @section.store_handle) + @section = services.clone_section.call( + store: store, section_id: @section.id, theme: maglev_theme, layout_id: current_maglev_page.layout_id + ) + preceding_sections = store.sections.take(store.position_of_section(@section['id'])) + position = preceding_sections.count { |section| !section['deleted'] } + + redirect_to edit_editor_section_path(@section['id'], maglev_editing_route_context), + flash: { + store_id: maglev_theme.store_view_id_of(current_maglev_page.layout_id, store.handle), + section_id: @section['id'], position: position.to_s + }, + notice: flash_t(:success), status: :see_other + rescue Maglev::CloneSection::NotCloneable + head :unprocessable_entity + rescue ActiveRecord::RecordNotFound + head :not_found + end + def sort services.sort_sections.call(store: sections_store, section_ids: params[:item_ids], lock_version: params[:lock_version]) @@ -89,7 +109,7 @@ def create_section end def update_section - services.update_section.call( + @updated_store = services.update_section.call( store: sections_store, section_id: @section.id, content: params[:section].to_unsafe_h, diff --git a/app/models/maglev/content/section_content.rb b/app/models/maglev/content/section_content.rb index a8fe9db99..ef160f892 100644 --- a/app/models/maglev/content/section_content.rb +++ b/app/models/maglev/content/section_content.rb @@ -35,7 +35,13 @@ def block_definitions end def root_blocks - blocks.select(&:root?) + # NOTE: a block whose type is root-eligible (root: true, the default) can still be + # nested under another block when its type is also accepted as a child + # (e.g. a navbar menu_item inside another menu_item). Selecting blocks by their + # definition's root? flag would return those nested blocks as well, rendering them + # twice in the editor tree. So we filter on the parent_id instead, like the + # front-end block tree builder does. + blocks.select { |block| block.parent_id.blank? } end # return the definitions of root blocks that can be added diff --git a/app/models/maglev/page_path.rb b/app/models/maglev/page_path.rb index 16458e040..bc5c6289c 100644 --- a/app/models/maglev/page_path.rb +++ b/app/models/maglev/page_path.rb @@ -56,8 +56,8 @@ def clean_value! def clean_value value .strip - .gsub(%r{(^/|/$)}, '') - .gsub(%r{//+/}, '/') + .gsub(%r{\A/+|/+\z}, '') + .gsub(%r{/{2,}}, '/') end end end diff --git a/app/services/concerns/maglev/get_page_sections/transform_link_concern.rb b/app/services/concerns/maglev/get_page_sections/transform_link_concern.rb index 99d437e9c..21b0570bb 100644 --- a/app/services/concerns/maglev/get_page_sections/transform_link_concern.rb +++ b/app/services/concerns/maglev/get_page_sections/transform_link_concern.rb @@ -26,10 +26,16 @@ def get_fullpath_from_link(link) # since the static pages don't have a preview version, we need the raw url if is_static_page page = fetch_static_pages.call.find { |static_page| static_page.id == page_id } - page&.path + normalize_static_page_path(page.path) if page else get_page_fullpath.call(page: page_id, locale: locale) end end + + def normalize_static_page_path(path) + return path if path.blank? || path.match?(%r{\A[a-z][a-z0-9+.-]*://}i) # absolute url, leave it as is + + Maglev::GetPageFullpath.join(nil, path) + end end # rubocop:enable Style/ClassAndModuleChildren diff --git a/app/services/maglev/app_container.rb b/app/services/maglev/app_container.rb index ec51117a2..708995e27 100644 --- a/app/services/maglev/app_container.rb +++ b/app/services/maglev/app_container.rb @@ -55,6 +55,7 @@ class AppContainer dependency :add_section, class: Maglev::Content::AddSectionService, depends_on: %i[fetch_site fetch_theme] + dependency :clone_section, class: Maglev::CloneSection dependency :update_section, class: Maglev::Content::UpdateSectionService, depends_on: %i[fetch_site fetch_theme] dependency :delete_section, class: Maglev::Content::DeleteSectionService, diff --git a/app/services/maglev/clone_section.rb b/app/services/maglev/clone_section.rb new file mode 100644 index 000000000..296e2ef4f --- /dev/null +++ b/app/services/maglev/clone_section.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +module Maglev + class CloneSection + include Injectable + include Maglev::Content::PublishingStateConcern + + class NotCloneable < StandardError; end + + argument :store + argument :section_id + argument :theme + argument :layout_id + + def call + store.with_lock do + original = store.find_section_by_id(section_id) + raise ActiveRecord::RecordNotFound unless original + + definition = theme.sections.find(original.fetch('type')) + group = theme.find_layout(layout_id).find_group(store.handle) + raise NotCloneable unless definition&.can_be_added_in?(group, true) + + copy = source_content(original).deep_dup.except('mirror_of', 'lock_version', 'deleted') + copy['id'] = SecureRandom.urlsafe_base64(8) + blocks = copy.fetch('blocks', []) + block_ids = blocks.to_h { |block| [block.fetch('id'), SecureRandom.urlsafe_base64(8)] } + blocks.each do |block| + block['id'] = block_ids.fetch(block['id']) + block['parent_id'] = block_ids.fetch(block['parent_id']) if block['parent_id'].present? + block.delete('lock_version') + end + + store.sections_translations_will_change! + store.sections.insert(store.position_of_section(section_id) + 1, copy) + store.save! + touch_page(store) + copy + end + end + + private + + def source_content(section) + visited = Set.new + while section.dig('mirror_of', 'enabled') + mirror = section.fetch('mirror_of') + raise NotCloneable unless visited.add?(mirror) + + page = Maglev::Page.find(mirror.fetch('page_id')) + handle = mirror['layout_store_id'] || mirror['layout_group_id'] + group = theme.find_layout(page.layout_id).find_group(handle) + raise ActiveRecord::RecordNotFound unless group + + source_store = Maglev::SectionsContentStore.unpublished.find_by!( + handle: group.handle, page: group.page_scoped? ? page : nil + ) + section = source_store.find_section_by_id(mirror.fetch('section_id')) + raise ActiveRecord::RecordNotFound unless section + end + section + end + end +end diff --git a/app/services/maglev/content/sort_section_blocks_service.rb b/app/services/maglev/content/sort_section_blocks_service.rb index 5e3647af8..940ac77aa 100644 --- a/app/services/maglev/content/sort_section_blocks_service.rb +++ b/app/services/maglev/content/sort_section_blocks_service.rb @@ -42,11 +42,29 @@ def sort_section_blocks!(source) source.save! end + # Only the siblings (the blocks sharing the same parent) are re-ordered, in place. + # The other blocks keep their position in the flat list: sorting the whole list + # with a non-stable sort (Array#sort_by!) used to shuffle the blocks outside of + # the sorted scope, like the children of the other blocks in a tree. def sort_section_blocks(source) - find_blocks(source)&.sort_by! do |block| - block['parent_id'] == parent_id ? block_ids.index(block['id']) || Float::INFINITY : -1 + blocks = find_blocks(source) + return if blocks.blank? + + indices = blocks.each_index.select { |index| sibling?(blocks[index]) } + sorted_siblings = sort_siblings(blocks.values_at(*indices)) + + indices.zip(sorted_siblings) { |index, block| blocks[index] = block } + end + + def sort_siblings(siblings) + siblings.sort_by.with_index do |block, position| + [block_ids.index(block['id']) || Float::INFINITY, position] end end + + def sibling?(block) + block['parent_id'].presence == parent_id.presence + end end end end diff --git a/app/services/maglev/content/update_section_block_service.rb b/app/services/maglev/content/update_section_block_service.rb index 347928673..26a9e9fbb 100644 --- a/app/services/maglev/content/update_section_block_service.rb +++ b/app/services/maglev/content/update_section_block_service.rb @@ -28,6 +28,9 @@ def call private def unsafe_call + # return the store which has been actually written into, so the caller + # can read its fresh lock version (a site scoped section is listed in + # a layout store but its content is written in the site scoped store) if site_scoped? update_section_block_content!(site_scoped_store) else @@ -41,6 +44,8 @@ def update_section_block_content!(source) source.sections_translations_will_change! update_section_block_content(source) source.save! + + source end def update_section_block_content(source) diff --git a/app/services/maglev/content/update_section_service.rb b/app/services/maglev/content/update_section_service.rb index a4bac8f5d..53c998e7c 100644 --- a/app/services/maglev/content/update_section_service.rb +++ b/app/services/maglev/content/update_section_service.rb @@ -26,6 +26,9 @@ def call private def unsafe_call + # return the store which has been actually written into, so the caller + # can read its fresh lock version (a site scoped section is listed in + # a layout store but its content is written in the site scoped store) if site_scoped? add_missing_site_scoped_section # make sure the section is also present in the site scoped store update_section_content!(site_scoped_store) @@ -40,6 +43,8 @@ def update_section_content!(source) source.sections_translations_will_change! update_section_content(source) source.save! + + source end def update_section_content(source) diff --git a/app/services/maglev/get_page_fullpath.rb b/app/services/maglev/get_page_fullpath.rb index 93530f08a..93a14a52a 100644 --- a/app/services/maglev/get_page_fullpath.rb +++ b/app/services/maglev/get_page_fullpath.rb @@ -14,6 +14,21 @@ class GetPageFullpath argument :preview_mode, default: nil argument :locale + # Build a path from a base url (optional) and a list of segments. + # Segments are stripped from their leading/trailing slashes so that + # a stored path such as "/hello-world" doesn't end up as "//hello-world". + # The result never contains "//" (except for the scheme of the base url) + # and always starts with a single "/" when there is no base url. + def self.join(base_url, *segments) + root = base_url.to_s.sub(%r{/+\z}, '') + segments = segments.map { |segment| normalize_segment(segment) }.compact_blank + [root, *segments].join('/').presence || '/' + end + + def self.normalize_segment(segment) + segment.to_s.gsub(%r{\A/+|/+\z}, '').gsub(%r{/{2,}}, '/') + end + def call base_url = get_base_url.call(preview_mode: preview_mode) safe_path = path || fetch_path @@ -42,11 +57,10 @@ def fetch_paths end def build_fullpath(base_url, path) - fullpath = [base_url] - fullpath.push(locale) if prefix_by_default_locale? - fullpath.push(path) unless path == 'index' # for SEO purpose) - fullpath.push(nil) if fullpath == [nil] # avoid "" as the fullpath - fullpath.join('/') + segments = [] + segments.push(locale) if prefix_by_default_locale? + segments.push(path) unless self.class.normalize_segment(path) == 'index' # for SEO purpose + self.class.join(base_url, *segments) end def site diff --git a/app/views/maglev/editor/section_blocks/update.turbo_stream.erb b/app/views/maglev/editor/section_blocks/update.turbo_stream.erb index 613844a6a..dae6ff104 100644 --- a/app/views/maglev/editor/section_blocks/update.turbo_stream.erb +++ b/app/views/maglev/editor/section_blocks/update.turbo_stream.erb @@ -1,13 +1,10 @@ -<%= turbo_stream.dispatch_event "section-block-#{@section_block.id}:persisted", payload: { lockVersion: source_lock_version }.to_json %> - +<%= turbo_stream.dispatch_event "section-block-#{@section_block.id}:persisted", payload: { lockVersion: @updated_store.lock_version }.to_json %> <%= turbo_stream.update 'page-layout-notification', method: 'morph' do %> <%= render Maglev::Uikit::BadgeComponent.new(color: :green, icon_name: 'checkbox_circle', disappear_after: 3.seconds).with_content(flash.now[:notice]) %> <% end %> - <%= turbo_stream.update dom_id(current_maglev_page, 'topbar-page-info'), method: 'morph' do %> <%= render 'layouts/maglev/editor/topbar/page_info' %> <% end %> - <%= turbo_stream.update dom_id(current_maglev_page, 'topbar-publish-button'), method: 'morph' do %> <%= render 'layouts/maglev/editor/topbar/publish_button' %> -<% end %> \ No newline at end of file +<% end %> diff --git a/app/views/maglev/editor/sections/_clone_button.html.erb b/app/views/maglev/editor/sections/_clone_button.html.erb new file mode 100644 index 000000000..e2b6a831f --- /dev/null +++ b/app/views/maglev/editor/sections/_clone_button.html.erb @@ -0,0 +1,10 @@ +<%= button_to clone_editor_section_path(section.id, maglev_editing_route_context), + class: button_classes, + title: t('maglev.editor.sections.actions.clone'), + aria: { label: t('maglev.editor.sections.actions.clone') }, + form: { data: { + turbo_frame: '_top', + action: 'turbo:submit-end->editor-preview-notification-center#addSection' + } } do %> + <%= render Maglev::Uikit::IconComponent.new(name: 'clone', size: '1.15rem') %> +<% end %> diff --git a/app/views/maglev/editor/sections/_list.html.erb b/app/views/maglev/editor/sections/_list.html.erb index df0e440d3..82cc1444f 100644 --- a/app/views/maglev/editor/sections/_list.html.erb +++ b/app/views/maglev/editor/sections/_list.html.erb @@ -26,6 +26,9 @@ <% end %> <% item.with_action do %> + <% if sections_store.addable_sections.include?(section.definition) %> + <%= render 'maglev/editor/sections/clone_button', section: section, button_classes: maglev_icon_button_classes %> + <% end %> <%= button_to editor_section_path(section.id, maglev_editing_route_context), method: :delete, class: maglev_icon_button_classes, @@ -48,4 +51,4 @@ <% component.with_item_insert_button(link: { url: new_editor_section_path(store_id: sections_store, position: index + 1, **maglev_editing_route_context), data: { turbo_frame: 'modal' } }) %> <% end %> <% end %> -<% end %> \ No newline at end of file +<% end %> diff --git a/app/views/maglev/editor/sections/update.turbo_stream.erb b/app/views/maglev/editor/sections/update.turbo_stream.erb index d1ad61bb7..f270a9d0c 100644 --- a/app/views/maglev/editor/sections/update.turbo_stream.erb +++ b/app/views/maglev/editor/sections/update.turbo_stream.erb @@ -1,13 +1,10 @@ -<%= turbo_stream.dispatch_event "section-#{@section.id}:persisted", payload: { lockVersion: source_lock_version }.to_json %> - +<%= turbo_stream.dispatch_event "section-#{@section.id}:persisted", payload: { lockVersion: @updated_store.lock_version }.to_json %> <%= turbo_stream.update 'page-layout-notification', method: 'morph' do %> <%= render Maglev::Uikit::BadgeComponent.new(color: :green, icon_name: 'checkbox_circle', disappear_after: 3.seconds).with_content(flash.now[:notice]) %> <% end %> - <%= turbo_stream.update dom_id(current_maglev_page, 'topbar-page-info'), method: 'morph' do %> <%= render 'layouts/maglev/editor/topbar/page_info' %> <% end %> - <%= turbo_stream.update dom_id(current_maglev_page, 'topbar-publish-button'), method: 'morph' do %> <%= render 'layouts/maglev/editor/topbar/publish_button' %> -<% end %> \ No newline at end of file +<% end %> diff --git a/config/locales/editor.en.yml b/config/locales/editor.en.yml index 1be3fc373..9e27702b9 100644 --- a/config/locales/editor.en.yml +++ b/config/locales/editor.en.yml @@ -76,6 +76,8 @@ en: layout_prompt: "Select a layout" sections: breadcrumb: "Sections" + actions: + clone: "Clone section" index: title: "Organize sections" sub_title: "Re-order / delete the sections of the page" @@ -259,6 +261,8 @@ en: sort: success: "Sorted!" error: "Failed!" + clone: + success: "Section cloned." create: success: "Added!" error: "Failed!" diff --git a/config/routes/maglev/editor.rb b/config/routes/maglev/editor.rb index d46f38ad6..f24b8cd03 100644 --- a/config/routes/maglev/editor.rb +++ b/config/routes/maglev/editor.rb @@ -36,6 +36,8 @@ get 'sections', to: 'sections_stores#index', as: :sections_stores resources :sections, only: %i[edit update destroy] do + post :clone, on: :member + resources :blocks, controller: :section_blocks do put :sort, on: :collection end diff --git a/spec/components/maglev/editor/settings/text/richtext_component_spec.rb b/spec/components/maglev/editor/settings/text/richtext_component_spec.rb new file mode 100644 index 000000000..43529e773 --- /dev/null +++ b/spec/components/maglev/editor/settings/text/richtext_component_spec.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Maglev::Editor::Settings::Text::RichtextComponent, type: :component do + let(:options) { { html: true } } + let(:definition) { build(:section_setting, :richtext, options: options) } + let(:instance) do + described_class.new(definition: definition, value: '

Hello

', paths: { edit_link_path: '/links/edit' }, + scope: { input: 'section', i18n: 'maglev.editor' }) + end + + subject { render_inline(instance) } + + before do + vc_test_view_context.class.include(Maglev::ApplicationHelper) + end + + it 'renders the editor with the default number of rows' do + subject + expect(rendered_content).to have_selector('[style*="--number-of-rows: 4;"]') + end + + context 'when the setting defines nb_rows' do + let(:options) { { html: true, nb_rows: 15 } } + + it 'sizes the editor to that number of rows' do + subject + expect(rendered_content).to have_selector('[style*="--number-of-rows: 15;"]') + end + end +end diff --git a/spec/components/maglev/section_component_spec.rb b/spec/components/maglev/section_component_spec.rb index 1bacae5f7..0f5b3b301 100644 --- a/spec/components/maglev/section_component_spec.rb +++ b/spec/components/maglev/section_component_spec.rb @@ -36,6 +36,31 @@ end end + describe '#lock_version' do + subject { component.lock_version } + + context 'when the attributes carry no lock version' do + it { is_expected.to eq '0' } + end + + context 'when the attributes carry the lock version of the source store' do + before { attributes[:lock_version] = 42 } + + it { is_expected.to eq 42 } + end + + context 'when the section is site scoped' do + # the lock version stamped on the attributes is the one of the + # site scoped store (where the content lives), not the one of + # the layout store the section is listed in + let(:definition) { build(:section, category: 'headers', site_scoped: true) } + + before { attributes[:lock_version] = 7 } + + it { is_expected.to eq 7 } + end + end + describe '#render' do subject { pretty_html(component.render) } diff --git a/spec/factories/maglev/themes.rb b/spec/factories/maglev/themes.rb index 96fdfe927..0d72450e0 100644 --- a/spec/factories/maglev/themes.rb +++ b/spec/factories/maglev/themes.rb @@ -66,11 +66,13 @@ site_scoped: true, singleton: true, insert_at: 'top', + blocks_presentation: 'tree', settings: [{ label: 'Logo', id: 'logo', type: 'image' }], blocks: [ { name: 'Menu item', type: 'menu_item', + accept: %w[menu_item], settings: [ { label: 'Label', id: 'label', type: 'text', default: 'Menu item' }, { label: 'Link', id: 'link', type: 'link', default: '/' } @@ -153,8 +155,8 @@ { type: 'jumbotron', settings: { - "title": "Let's create the product
your clients
will love.", - "body": '

NoCoffee, passionated developers,
creators of web applications, mobiles apps and
fancy R&D projects.

' + title: "Let's create the product
your clients
will love.", + body: '

NoCoffee, passionated developers,
creators of web applications, mobiles apps and
fancy R&D projects.

' }, blocks: [] }, @@ -190,8 +192,8 @@ { type: 'jumbotron', settings: { - "title": 'About our awesome team', - "body": '

NoCoffee, passionated developers,
creators of web applications, mobiles apps and
fancy R&D projects.

' + title: 'About our awesome team', + body: '

NoCoffee, passionated developers,
creators of web applications, mobiles apps and
fancy R&D projects.

' }, blocks: [] } diff --git a/spec/models/maglev/content/section_content_spec.rb b/spec/models/maglev/content/section_content_spec.rb index 7e554fa86..0f74e560a 100644 --- a/spec/models/maglev/content/section_content_spec.rb +++ b/spec/models/maglev/content/section_content_spec.rb @@ -52,4 +52,27 @@ end end end + + context '#root_blocks' do + let(:store) { build(:sections_content_store, :with_navbar, page: page) } + + it 'returns only the blocks without a parent' do + # the menu_item type is both root-eligible and accepted as a child of itself: + # nested menu items must not be returned here, otherwise the editor tree + # would render them twice (at the root and under their parent) + expect(section_content.root_blocks.map(&:id)).to eq %w[menu-item-0 menu-item-1] + end + end + + context '#child_blocks_of' do + let(:store) { build(:sections_content_store, :with_navbar, page: page) } + + it 'returns the direct children of the given block' do + expect(section_content.child_blocks_of('menu-item-1').map(&:id)).to eq %w[menu-item-1-1 menu-item-1-2] + end + + it 'returns an empty list for a block without children' do + expect(section_content.child_blocks_of('menu-item-0')).to eq [] + end + end end diff --git a/spec/models/maglev/page_path_spec.rb b/spec/models/maglev/page_path_spec.rb index 02df0cfa9..5f223a88d 100644 --- a/spec/models/maglev/page_path_spec.rb +++ b/spec/models/maglev/page_path_spec.rb @@ -27,6 +27,23 @@ expect(page.paths.build(canonical: false, value: 'whatevs')).to be_valid end + describe 'cleaning the value' do + def clean(value) + page.paths.build(canonical: false, value: value).tap(&:valid?).value + end + + it 'strips the leading and trailing slashes' do + expect(clean('/hello-world/')).to eq 'hello-world' + expect(clean('//hello-world//')).to eq 'hello-world' + expect(clean(' /hello-world ')).to eq 'hello-world' + end + + it 'collapses the inner double slashes' do + expect(clean('hello//world')).to eq 'hello/world' + expect(clean('hello///world')).to eq 'hello/world' + end + end + describe 'with a different locale' do let!(:value) { Maglev::I18n.with_locale(Maglev::I18n.default_locale) { page.path } } diff --git a/spec/requests/maglev/editor/section_blocks_spec.rb b/spec/requests/maglev/editor/section_blocks_spec.rb index 20fa0a055..f3553b56b 100644 --- a/spec/requests/maglev/editor/section_blocks_spec.rb +++ b/spec/requests/maglev/editor/section_blocks_spec.rb @@ -14,11 +14,71 @@ allow(Maglev.local_themes).to receive(:first).and_return(theme) end + # the navbar is a site scoped section presenting its blocks as a tree: + # it is listed in the "header" layout store (its "slot") while its content + # lives in the global site scoped store + shared_context 'with a site scoped section with nested blocks' do + let(:slot_store) { fetch_sections_store('header') } + let(:site_store) { fetch_sections_store('_site') } + let(:navbar_section) { site_store.find_section_by_type('navbar') } + let(:section_id) { navbar_section['id'] } + + # rubocop:disable Style/StringHashKeys + before do + # two root menu items, one of them with a nested menu item + navbar_section['blocks'] = [ + { + 'id' => 'menu-item-0', + 'type' => 'menu_item', + 'settings' => [ + { 'id' => 'label', 'value' => 'Home' }, + { 'id' => 'link', 'value' => '/' } + ] + }, + { + 'id' => 'menu-item-1', + 'type' => 'menu_item', + 'settings' => [ + { 'id' => 'label', 'value' => 'About us' }, + { 'id' => 'link', 'value' => '/about-us' } + ] + }, + { + 'id' => 'nested-menu-item', + 'type' => 'menu_item', + 'parent_id' => 'menu-item-1', + 'settings' => [ + { 'id' => 'label', 'value' => 'Nested item' }, + { 'id' => 'link', 'value' => { 'link_type' => 'url', 'href' => '/nested', 'open_new_window' => false } } + ] + } + ] + site_store.sections_translations_will_change! + site_store.save! + end + # rubocop:enable Style/StringHashKeys + end + describe 'GET /maglev/editor/:context/sections/:id/blocks' do it 'returns a success response' do get "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/blocks" expect(response).to be_successful end + + context 'when the section presents its blocks as a tree' do + include_context 'with a site scoped section with nested blocks' + + it 'renders each block exactly once' do + get "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/blocks" + expect(response).to be_successful + expect(response.body.scan('Nested item').count).to eq 1 + end + + it 'nests the child block under its parent' do + get "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/blocks" + expect(response.body).to include('data-sortable-scope-value="menu-item-1"') + end + end end describe 'POST /maglev/editor/:context/sections/:id/blocks' do @@ -62,6 +122,42 @@ expect(response).to be_successful expect(main_store.reload.sections.dig(1, 'blocks', 0, 'settings', 0, 'value')).to eq 'My new title 🍔' end + + context 'when the section is site scoped' do + include_context 'with a site scoped section with nested blocks' + + let(:block_id) { 'nested-menu-item' } + + before do + # make sure the lock versions of the slot store and the site scoped store differ + # rubocop:disable Rails/SkipsModelValidations + slot_store.update_column(:lock_version, 0) + site_store.update_column(:lock_version, 7) + # rubocop:enable Rails/SkipsModelValidations + end + + it 'renders the form with the lock version of the site scoped store' do + get "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/blocks/#{block_id}/edit" + expect(response.body).to have_selector("input[name='lock_version'][value='7']", visible: :hidden) + end + + it 'updates the site scoped store and dispatches its fresh lock version' do + put "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/blocks/#{block_id}", + as: :turbo_stream, + params: { lock_version: 7, section_block: { label: 'Our dream team' } } + expect(response).to be_successful + expect(response.body).to include('"lockVersion":8') + expect(site_store.reload.lock_version).to eq 8 + expect(slot_store.reload.lock_version).to eq 0 + end + + it 'still rejects a stale lock version' do + put "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/blocks/#{block_id}", + as: :turbo_stream, + params: { lock_version: 6, section_block: { label: 'Our dream team' } } + expect(response).to have_http_status(:conflict) + end + end end describe 'DELETE /maglev/editor/:context/sections/:id/blocks/:id' do diff --git a/spec/requests/maglev/editor/sections_spec.rb b/spec/requests/maglev/editor/sections_spec.rb index 348cc9833..07189e389 100644 --- a/spec/requests/maglev/editor/sections_spec.rb +++ b/spec/requests/maglev/editor/sections_spec.rb @@ -46,6 +46,69 @@ end end + describe 'POST /maglev/editor/:context/sections/:id/clone' do + let(:main_store) { fetch_sections_store('main', home_page.id) } + let(:section_id) { main_store.find_section_by_type('showcase')['id'] } + let(:clone_path) { "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/clone" } + + it 'clones the section and redirects to its editor with preview insertion headers' do + post clone_path, params: { store_id: 'footer' } + + expect(response).to have_http_status(:see_other) + copy = main_store.reload.sections.last + expect(main_store.sections.size).to eq(3) + expect(copy['id']).not_to eq(section_id) + expect(response).to redirect_to("/maglev/editor/en/#{home_page.id}/sections/#{copy['id']}/edit") + follow_redirect! + + expect(response).to be_successful + expect(response.headers['X-Section-Id']).to eq(copy['id']) + expect(response.headers['X-Layout-Store-Id']).to eq('main') + expect(response.headers['X-Section-Position']).to eq('2') + expect(response.body).to include('Section cloned.') + end + + it 'ignores soft-deleted sections when positioning the preview copy' do + main_store.sections.first['deleted'] = true + main_store.save! + + post clone_path + follow_redirect! + + expect(response).to be_successful + expect(response.headers['X-Section-Position']).to eq('1') + end + + it 'renders clone buttons in the list and toolbar with development view annotations enabled' do + allow(ActionView::Base).to receive(:annotate_rendered_view_with_filenames).and_return(true) + + paths = ["/maglev/editor/en/#{home_page.id}", "/maglev/editor/en/#{home_page.id}/sections"] + paths.each_with_index do |path, index| + get path + + expect(response).to be_successful + expect(response.body).to have_selector("form[action='#{clone_path}'] button[aria-label='Clone section']", + count: index + 1, visible: :all) + end + end + + it 'preserves restrictions on sections that cannot be added twice' do + restricted_id = fetch_sections_store('header').find_section_by_type('navbar')['id'] + + post "/maglev/editor/en/#{home_page.id}/sections/#{restricted_id}/clone" + + expect(response).to have_http_status(422) + expect(main_store.reload.sections.size).to eq(2) + end + + it 'does not clone a section outside the current page' do + post "/maglev/editor/en/#{home_page.id}/sections/missing-section/clone" + + expect(response).to redirect_to("/maglev/editor/en/#{home_page.id}/sections") + expect(main_store.reload.sections.size).to eq(2) + end + end + describe 'GET /maglev/editor/:context/sections/:id/edit' do let(:main_store) { fetch_sections_store('main', home_page.id) } let(:section_id) { main_store.sections.dig(0, 'id') } @@ -78,6 +141,44 @@ expect(response.media_type).to eq Mime[:turbo_stream] expect(main_store.reload.sections.dig(0, 'settings', 0, 'value')).to eq('Hello world!') end + + context 'when the section is site scoped' do + # a site scoped section is listed in a layout store (its "slot") but its content + # lives in the global site scoped store: the lock version of the latter must be used + let(:slot_store) { fetch_sections_store('header') } + let(:site_store) { fetch_sections_store('_site') } + let(:section_id) { site_store.find_section_by_type('navbar')['id'] } + + before do + # make sure the lock versions of the two stores differ + # rubocop:disable Rails/SkipsModelValidations + slot_store.update_column(:lock_version, 0) + site_store.update_column(:lock_version, 7) + # rubocop:enable Rails/SkipsModelValidations + end + + it 'renders the form with the lock version of the site scoped store' do + get "/maglev/editor/en/#{home_page.id}/sections/#{section_id}/edit" + expect(response.body).to have_selector("input[name='lock_version'][value='7']", visible: :hidden) + end + + it 'updates the site scoped store and dispatches its fresh lock version' do + put "/maglev/editor/en/#{home_page.id}/sections/#{section_id}", + as: :turbo_stream, + params: { lock_version: 7, section: { logo: 'new-logo.png' } } + expect(response).to be_successful + expect(response.body).to include('"lockVersion":8') + expect(site_store.reload.lock_version).to eq 8 + expect(slot_store.reload.lock_version).to eq 0 + end + + it 'still rejects a stale lock version' do + put "/maglev/editor/en/#{home_page.id}/sections/#{section_id}", + as: :turbo_stream, + params: { lock_version: 6, section: { logo: 'new-logo.png' } } + expect(response).to have_http_status(:conflict) + end + end end describe 'DELETE /maglev/editor/:context/sections/:id' do diff --git a/spec/services/maglev/clone_section_spec.rb b/spec/services/maglev/clone_section_spec.rb new file mode 100644 index 000000000..76f952e3d --- /dev/null +++ b/spec/services/maglev/clone_section_spec.rb @@ -0,0 +1,144 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe Maglev::CloneSection do + let(:theme) { build(:theme) } + let(:page) { create(:page, sections: nil, layout_id: 'sidebar') } + let(:store) { create(:sections_content_store, :with_navbar, page: page, handle: 'main') } + let(:definition) { theme.sections.find('navbar') } + let(:service) { described_class.new } + + subject(:copy) do + service.call(store: store, section_id: 'abc', theme: theme, layout_id: page.layout_id) + end + + before do + definition.site_scoped = false + definition.singleton = false + end + + it 'inserts an independent copy with fresh section and nested block identities' do + original = store.sections.first.deep_dup + following = { id: 'following', type: 'showcase', settings: [], blocks: [] }.deep_stringify_keys + store.sections << following + store.save! + published = create(:sections_content_store, :published, page: page, sections: store.sections.deep_dup) + + result = copy + + expect(store.reload.section_ids).to eq(['abc', result['id'], 'following']) + expect(store.sections.first).to eq(original) + expect(result['settings']).to eq(original['settings']) + expect(result['blocks'].map { |block| block['id'] } & original['blocks'].map { |block| block['id'] }).to be_empty + original['blocks'].zip(result['blocks']).each do |source_block, copied_block| + expect(copied_block.except('id', 'parent_id')).to eq(source_block.except('id', 'parent_id')) + next if source_block['parent_id'].blank? + + parent_index = original['blocks'].index { |block| block['id'] == source_block['parent_id'] } + expect(copied_block['parent_id']).to eq(result['blocks'][parent_index]['id']) + end + expect(published.reload.sections).to eq([original, following]) + end + + it 'deep copies nested setting values and preserves independence after saving and reloading' do + original = store.sections.first.deep_dup + result = copy + result['blocks'].last['settings'].last['value']['href'] = '/clone-only' + + expect(store.sections.first).to eq(original) + store.sections_translations_will_change! + store.save! + copied_content = store.reload.sections.last.deep_dup + store.sections.first['blocks'].last['settings'].last['value']['href'] = '/original-only' + store.sections_translations_will_change! + store.save! + + expect(store.reload.sections.last).to eq(copied_content) + end + + it 'marks the page as having unpublished changes' do + page.update!(updated_at: 1.day.ago) + + copy + + expect(page.reload.updated_at).to be > 1.hour.ago + end + + it 'keeps deletion of either section independent' do + cloned_id = copy['id'] + store.delete_section(cloned_id) + store.save! + expect(store.reload.find_section_by_id('abc')).to be_present + + cloned_id = service.call(store: store, section_id: 'abc', theme: theme, layout_id: page.layout_id)['id'] + store.delete_section('abc') + store.save! + expect(store.reload.find_section_by_id(cloned_id)).to be_present + end + + it 'clones only the active locale' do + english = store.sections.deep_dup + french = english.deep_dup + french.first['settings'].first['value'] = 'french-logo.png' + store.update!(sections_translations: { en: english, fr: french }) + Maglev::I18n.available_locales = %i[en fr] + + Maglev::I18n.with_locale(:fr) { copy } + + translations = store.reload.sections_translations + expect(translations['en']).to eq(english) + expect(translations['fr'].size).to eq(2) + expect(translations['fr'].last['settings']).to eq(french.first['settings']) + end + + %i[site_scoped singleton].each do |restriction| + it "rejects #{restriction} sections without changing the store" do + definition.public_send("#{restriction}=", true) + + expect { copy }.to raise_error(described_class::NotCloneable) + expect(store.reload.sections.size).to eq(1) + end + end + + context 'with a mirrored section' do + let(:source_page) { create(:page, sections: nil, path: 'source', layout_id: 'sidebar') } + let(:source_store) { create(:sections_content_store, :with_navbar, page: source_page, handle: 'main') } + + before do + source_store.sections.first['settings'].first['value'] = 'current-source-logo.png' + source_store.save! + store.sections.first['mirror_of'] = { + enabled: true, page_id: source_page.id, layout_store_id: 'main', section_id: 'abc' + }.stringify_keys + store.sections.first['lock_version'] = 7 + store.save! + end + + it 'snapshots the current source and removes its mirroring and lock metadata' do + result = copy + + expect(result).not_to have_key('mirror_of') + expect(result).not_to have_key('lock_version') + expect(result['settings']).to eq(source_store.sections.first['settings']) + source_store.sections.first['settings'].first['value'] = 'later-source-logo.png' + source_store.save! + expect(store.reload.sections.last).to eq(result) + end + + it 'rejects missing sources without changing content' do + source_store.destroy! + + expect { copy }.to raise_error(ActiveRecord::RecordNotFound) + expect(store.reload.sections.size).to eq(1) + end + + it 'rejects circular mirrors without changing content' do + source_store.sections.first['mirror_of'] = store.sections.first['mirror_of'].deep_dup + source_store.save! + + expect { copy }.to raise_error(described_class::NotCloneable) + expect(store.reload.sections.size).to eq(1) + end + end +end diff --git a/spec/services/maglev/content/sort_section_blocks_service_spec.rb b/spec/services/maglev/content/sort_section_blocks_service_spec.rb index 5f24aae25..62dc9aee6 100644 --- a/spec/services/maglev/content/sort_section_blocks_service_spec.rb +++ b/spec/services/maglev/content/sort_section_blocks_service_spec.rb @@ -76,5 +76,64 @@ end }.to ['Home', 'About us', 'Our office', 'Our team'] end + + context 'when the sorted siblings are interleaved with other blocks' do + # blocks are appended to the flat list as the editor creates them, so the children + # of a menu item are rarely stored right after it + let!(:page) do + create(:page, header_sections: [{ + id: 'abc', + type: 'navbar', + settings: [{ id: :logo, value: 'logo.png' }], + blocks: [ + menu_item('home', 'Home'), + menu_item('about', 'About us'), + menu_item('about-team', 'Our team', parent_id: 'about'), + menu_item('contact', 'Contact'), + menu_item('about-office', 'Our office', parent_id: 'about'), + menu_item('contact-email', 'Email', parent_id: 'contact'), + menu_item('contact-phone', 'Phone', parent_id: 'contact'), + menu_item('blog', 'Blog') + ] + }]) + end + + def menu_item(id, label, parent_id: nil) + { + id: id, + type: 'menu_item', + parent_id: parent_id, + settings: [{ id: :label, value: label }, { id: :link, value: '/' }] + }.compact + end + + def block_ids_in_store + site_scoped_store.reload.sections.dig(0, 'blocks').map { |block| block['id'] } + end + + context 'sorting the root blocks' do + let(:parent_id) { nil } + let(:block_ids) { %w[blog contact about home] } + + it 'only moves the root blocks and leaves the nested blocks where they are' do + subject + expect(block_ids_in_store).to eq( + %w[blog contact about-team about about-office contact-email contact-phone home] + ) + end + end + + context 'sorting the children of a block' do + let(:parent_id) { 'about' } + let(:block_ids) { %w[about-office about-team] } + + it 'only moves the children and leaves the other blocks where they are' do + subject + expect(block_ids_in_store).to eq( + %w[home about about-office contact about-team contact-email contact-phone blog] + ) + end + end + end end end diff --git a/spec/services/maglev/content/update_section_service_spec.rb b/spec/services/maglev/content/update_section_service_spec.rb index 053f0aaee..77512a7ae 100644 --- a/spec/services/maglev/content/update_section_service_spec.rb +++ b/spec/services/maglev/content/update_section_service_spec.rb @@ -22,7 +22,7 @@ let(:lock_version) { 0 } it 'updates the section' do - expect(subject).to eq(true) + expect(subject).to be(store) expect(store.reload.sections.dig(0, 'settings', 0, 'value')).to eq('Hello world!') expect(store.reload.lock_version).to eq(1) end @@ -51,7 +51,7 @@ context 'Given an existing page section with a version' do it 'updates the section' do - expect(subject).to eq(true) + expect(subject).to be(store) end context 'Given the store has been modified while updating the section' do @@ -79,7 +79,8 @@ end it 'updates the section content on the site' do - expect(subject).to eq(true) + # the written store is the site scoped one, not the passed (slot) store + expect(subject).to eq(site_scoped_store) # rubocop:disable Style/StringHashKeys expect(site_scoped_sections.dig(0, 'settings', 0, 'value')).to eq({ 'url' => '/awesome-logo.png' }) # rubocop:enable Style/StringHashKeys diff --git a/spec/services/maglev/fetch_sections_content_service_spec.rb b/spec/services/maglev/fetch_sections_content_service_spec.rb index bd0467015..b207cdb83 100644 --- a/spec/services/maglev/fetch_sections_content_service_spec.rb +++ b/spec/services/maglev/fetch_sections_content_service_spec.rb @@ -126,6 +126,55 @@ locale: :en).once.and_return('/preview/awesome-path') expect(subject[0][0]['blocks'][0]['settings'][1]['value']['href']).to eq('/preview/awesome-path') end + + context 'with an anchor to a section' do + let!(:store) do + create(:sections_content_store, :sidebar, :page_link_in_link, page: page).tap do |store| + store.find_section_by_type('navbar').dig('blocks', 0, 'settings', 1)['value']['section_id'] = 'hero' + store.save! + end + end + + it 'appends the anchor to the path' do + expect(get_page_fullpath).to receive(:call).and_return('/preview/awesome-path') + expect(subject[0][0]['blocks'][0]['settings'][1]['value']['href']).to eq('/preview/awesome-path#section-hero') + end + end + end + + context 'the sections include a link to a static page' do + let(:page) { create(:page, sections: nil) } + let(:static_page) { build(:static_page, path_translations: { 'en' => '/products/' }) } + let(:service) do + described_class.new( + fetch_site: double('FetchSite', call: site), + fetch_theme: double('FetchTheme', call: theme), + get_page_fullpath: get_page_fullpath, + fetch_collection_items: fetch_collection_items, + fetch_static_pages: double('FetchStaticPages', call: [static_page]) + ) + end + let!(:store) do + create(:sections_content_store, :sidebar, :page_link_in_link, page: page).tap do |store| + link = store.find_section_by_type('navbar').dig('blocks', 0, 'settings', 1)['value'] + link['link_type'] = 'static_page' + link['link_id'] = static_page.id + store.save! + end + end + let(:handle) { 'sidebar' } + + it 'sets the href with a single leading slash' do + expect(subject[0][0]['blocks'][0]['settings'][1]['value']['href']).to eq('/products') + end + + context 'the static page path is an absolute url' do + let(:static_page) { build(:static_page, path_translations: { 'en' => 'https://www.example.com/products' }) } + + it 'leaves the url untouched' do + expect(subject[0][0]['blocks'][0]['settings'][1]['value']['href']).to eq('https://www.example.com/products') + end + end end context 'the sections include collection items' do diff --git a/spec/services/maglev/get_page_fullpath_spec.rb b/spec/services/maglev/get_page_fullpath_spec.rb index 831bb9262..347ca0f64 100644 --- a/spec/services/maglev/get_page_fullpath_spec.rb +++ b/spec/services/maglev/get_page_fullpath_spec.rb @@ -76,5 +76,97 @@ it 'returns the fullpath to the page' do expect(subject).to eq '/maglev/preview/hello-world' end + + context 'the static page path starts with a slash' do + let(:page) do + Maglev::StaticPage.new(id: '233456abcdef', path_translations: { fr: '/bonjour-le-monde', en: '/hello-world/' }) + end + + it 'returns the fullpath without a double slash' do + expect(subject).to eq '/maglev/preview/hello-world' + end + end + end + + describe 'normalization of the slashes' do + subject { service.call(path: path, locale: locale) } + + let(:path) { '/hello-world' } + + context 'preview mode with a base url ending with a slash' do + let(:get_base_url) { double('GetBaseUrl', call: '/maglev/preview/') } + + it 'joins the base url and the path with a single slash' do + expect(subject).to eq '/maglev/preview/hello-world' + end + + context 'index page' do + let(:path) { 'index' } + + it 'returns the base url without the trailing slash' do + expect(subject).to eq '/maglev/preview' + end + end + end + + context 'live mode (base url is the host)' do + let(:get_base_url) { double('GetBaseUrl', call: 'https://www.example.com') } + + it 'returns an absolute url without a double slash' do + expect(subject).to eq 'https://www.example.com/hello-world' + end + + context 'index page' do + let(:path) { 'index' } + + it 'returns the host only' do + expect(subject).to eq 'https://www.example.com' + end + end + + context 'in a different locale' do + let(:locale) { 'fr' } + + it 'prefixes the path by the locale without a double slash' do + expect(subject).to eq 'https://www.example.com/fr/hello-world' + end + end + end + + context 'live mode without a request (base url is nil)' do + let(:get_base_url) { double('GetBaseUrl', call: nil) } + + it 'returns a path starting with a single slash' do + expect(subject).to eq '/hello-world' + end + + context 'path with a trailing slash and inner double slashes' do + let(:path) { 'hello//world/' } + + it 'collapses the slashes' do + expect(subject).to eq '/hello/world' + end + end + + context 'index page with a leading slash' do + let(:path) { '/index' } + + it 'returns the root path' do + expect(subject).to eq '/' + end + end + end + end + + describe '.join' do + it 'never emits a double slash except after the scheme' do + expect(described_class.join('https://www.example.com/', '/fr/', '/hello-world/')).to eq( + 'https://www.example.com/fr/hello-world' + ) + expect(described_class.join(nil, '/hello-world')).to eq '/hello-world' + expect(described_class.join(nil)).to eq '/' + expect(described_class.join('/maglev/preview')).to eq '/maglev/preview' + expect(described_class.join('/maglev/preview/', nil, '')).to eq '/maglev/preview' + end end end