|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +#-- copyright |
| 4 | +# OpenProject is an open source project management software. |
| 5 | +# Copyright (C) the OpenProject GmbH |
| 6 | +# |
| 7 | +# This program is free software; you can redistribute it and/or |
| 8 | +# modify it under the terms of the GNU General Public License version 3. |
| 9 | +# |
| 10 | +# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: |
| 11 | +# Copyright (C) 2006-2013 Jean-Philippe Lang |
| 12 | +# Copyright (C) 2010-2013 the ChiliProject Team |
| 13 | +# |
| 14 | +# This program is free software; you can redistribute it and/or |
| 15 | +# modify it under the terms of the GNU General Public License |
| 16 | +# as published by the Free Software Foundation; either version 2 |
| 17 | +# of the License, or (at your option) any later version. |
| 18 | +# |
| 19 | +# This program is distributed in the hope that it will be useful, |
| 20 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 21 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 22 | +# GNU General Public License for more details. |
| 23 | +# |
| 24 | +# You should have received a copy of the GNU General Public License |
| 25 | +# along with this program; if not, write to the Free Software |
| 26 | +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 27 | +# |
| 28 | +# See COPYRIGHT and LICENSE files for more details. |
| 29 | +#++ |
| 30 | + |
| 31 | +module Lists |
| 32 | + # Anchor-based reordering for acts_as_list models: moves the record |
| 33 | + # directly below another record of the same list, addressed by id. |
| 34 | + module MoveAfterAnchor |
| 35 | + # Moves the record below the record identified by `prev_id` within |
| 36 | + # `scope` (a relation over the same acts_as_list list). A blank |
| 37 | + # `prev_id` moves the record to the top. |
| 38 | + # |
| 39 | + # Returns false without mutating when the anchor is unknown, outside |
| 40 | + # the scope, or the record itself. |
| 41 | + def move_after_anchor(prev_id, scope:) # rubocop:disable Naming/PredicateMethod -- verb command, not a query |
| 42 | + if prev_id.blank? |
| 43 | + move_to_top |
| 44 | + return true |
| 45 | + end |
| 46 | + |
| 47 | + anchor = scope.find_by(id: prev_id) |
| 48 | + return false if anchor.nil? || anchor.id == id |
| 49 | + |
| 50 | + # Removing the record first shifts the anchor up by one when the |
| 51 | + # record currently sits above it, so the target slot differs by |
| 52 | + # direction of travel. |
| 53 | + insert_at(position > anchor.position ? anchor.position + 1 : anchor.position) |
| 54 | + true |
| 55 | + end |
| 56 | + end |
| 57 | +end |
0 commit comments