π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
β¨ Drag 'n drop for section/item reordering (#1346)
Alicia Sykesb200b00968fc
diff --git a/package.json b/package.jsonindex b202f552..811a98b4 100644--- a/package.json+++ b/package.json@@ -49,6 +49,7 @@"pingman": "^2.2.0","rsup-progress": "^3.2.0","simple-icons": "^16.24.1",+ "sortablejs": "^1.15.7","vue": "^3.5.39","vue-i18n": "^9.14.0","vue-router": "^4.4.0",diff --git a/src/components/LinkItems/Section.vue b/src/components/LinkItems/Section.vueindex a1cef879..f34ce163 100644--- a/src/components/LinkItems/Section.vue+++ b/src/components/LinkItems/Section.vue@@ -22,7 +22,7 @@<!-- Item Container --><div v-if="hasItems":class="`there-are-items ${isGridLayout? 'item-group-grid': ''} inner-size-${itemSize}`"- :style="gridStyle" :id="`section-${groupId}`"+ :style="gridStyle" :id="`section-${groupId}`" v-drag-sort="itemDragConfig"> <!-- Show for each item --><template v-for="(item) in sortedItems" :key="item.id"><SubItemGroup@@ -62,10 +62,10 @@</div><divv-if="hasWidgets || isEditMode"- :class="`widget-list ${isWide? 'wide' : ''}`">+ :class="`widget-list ${isWide? 'wide' : ''}`" v-drag-sort="widgetDragConfig"><WidgetBasev-for="(widget, widgetIndx) in widgets"- :key="widgetIndx"+ :key="widget.id":widget="widget":index="index"@editWidget="openEditWidget(widgetIndx)"@@ -140,10 +140,14 @@ const EditSection = defineAsyncComponent(() => import('@/components/InteractiveEconst EditWidget = defineAsyncComponent(() => import('@/components/InteractiveEditor/EditWidget.vue'));import ErrorHandler from '@/utils/logging/ErrorHandler';import sortItems from '@/utils/SortItems';+import { reorder } from '@/directives/DragSort';import { makeRoutePath, viewFromPath } from '@/utils/config/ConfigHelpers';import StoreKeys from '@/utils/StoreMutations';import { sortOrder as defaultSortOrder } from '@/utils/config/defaults';+/* True if both lists contain the same elements, in the same order (compared by runtime id) */+const sameIdOrder = (a, b) => a.length === b.length && a.every((el, i) => el.id === b[i].id);+export default {name: 'Section',props: {@@ -236,6 +240,30 @@ export default {if (!cols) return cols;return Math.min(this.activeColCount, cols);},+ /* The section from the config, for the source of truth for drag-sorting+ * Rendered list needs to match exact (not filtered/sorted/etc) for drag to work */+ storeSection() {+ return this.$store.getters.getSectionByIndex(this.index) || {};+ },+ itemDragConfig() {+ return {+ enabled: this.isEditMode && sameIdOrder(this.storeSection.items || [], this.sortedItems),+ group: 'section-items',+ draggable: '.item-wrapper:not(.add-new-item), .sub-items-group',+ meta: { sectionIndex: this.index },+ onSorted: (e) => this.handleMoved('items', e),+ };+ },+ widgetDragConfig() {+ return {+ enabled: this.isEditMode && sameIdOrder(this.storeSection.widgets || [], this.widgets),+ group: 'section-widgets',+ draggable: '.widget-base',+ filter: 'a, button, input, textarea, select',+ meta: { sectionIndex: this.index },+ onSorted: (e) => this.handleMoved('widgets', e),+ };+ },},methods: {/* Opens the iframe modal */@@ -324,6 +352,32 @@ export default {});this.pendingRemoveWidgetIndex = -1;},+ /* Commits a drag-and-drop move of items or widgets, within or between sections */+ handleMoved(key, { oldIndex, newIndex, from, to }) {+ const { sections } = this.$store.state.config;+ const fromSection = sections[from?.sectionIndex];+ const toSection = sections[to?.sectionIndex];+ if (!fromSection || !toSection) {+ ErrorHandler('Unable to move, section not found');+ return;+ }+ if (fromSection === toSection) {+ this.$store.commit(StoreKeys.UPDATE_SECTION, {+ sectionIndex: from.sectionIndex,+ sectionData: { ...fromSection, [key]: reorder(fromSection[key] || [], oldIndex, newIndex) },+ });+ return;+ }+ const fromEntries = [...(fromSection[key] || [])];+ const [moved] = fromEntries.splice(oldIndex, 1);+ const toEntries = [...(toSection[key] || [])];+ toEntries.splice(newIndex, 0, moved);+ this.$store.commit(StoreKeys.SET_SECTIONS, sections.map((section, i) => {+ if (i === from.sectionIndex) return { ...section, [key]: fromEntries };+ if (i === to.sectionIndex) return { ...section, [key]: toEntries };+ return section;+ }));+ },/* Calculate width of section, used to dynamically set number of columns */calculateSectionWidth() {const secElem = this.$refs[this.sectionRef];@@ -416,6 +470,26 @@ export default {}}+/* Drag-and-drop things for when sorting is enabled, for drop slot */+.drag-sort-active {+ :deep(.item), :deep(.sub-items-group), :deep(.widget-base) {+ cursor: grab;+ }+ :deep(.drag-sort-ghost) {+ opacity: 0.4;+ outline: 2px dashed var(--primary);+ outline-offset: -2px;+ border-radius: var(--curve-factor);+ background: var(--item-background);+ transition: none !important;+ transform: none !important;+ > * {+ visibility: hidden;+ transition: none !important;+ }+ }+}+.widget-list {&.wide {display: flex;diff --git a/src/directives/DragSort.js b/src/directives/DragSort.jsnew file mode 100644index 00000000..398f26e6--- /dev/null+++ b/src/directives/DragSort.js@@ -0,0 +1,82 @@+/* Directive for drag-and-drop sorting of lists, using SortableJS.+ * Applied to a list container, with options: { enabled, onSorted, draggable, handle, group,+ * filter, meta }. On drop, Sortable's DOM change is reverted (Vue owns the DOM), then+ * `onSorted({ oldIndex, newIndex, from, to })` is called with each container's `meta`,+ * so the caller can commit the move to the store and let Vue re-render */+import { Sortable } from 'sortablejs';+import ErrorHandler from '@/utils/logging/ErrorHandler';++const ACTIVE_CLASS = 'drag-sort-active';+const registry = new WeakMap(); // container element -> { sortable, meta }++/* Returns a copy of an array, with one element moved to a new index */+export const reorder = (arr, fromIndex, toIndex) => {+ const result = [...arr];+ result.splice(toIndex, 0, ...result.splice(fromIndex, 1));+ return result;+};++const createSortable = (el, options) => {+ const { draggable, handle, group, filter, onSorted } = options;+ // The dragged element's original next sibling, for DOM revert. May be a text node:+ // v-for fragments are unmounted by anchor range, so the revert must land inside it+ let anchor = null;+ return new Sortable(el, {+ draggable,+ handle,+ group,+ filter,+ preventOnFilter: false,+ animation: 150,+ delay: 150,+ delayOnTouchOnly: true,+ forceFallback: true, // Consistent ghost behaviour, and no native link-drag on anchors+ fallbackTolerance: 3,+ ghostClass: 'drag-sort-ghost',+ // Prevent dropping after non-sortable trailing elements (e.g. add-new launchers),+ // except into lists with no sortable children yet+ onMove: (e) => !e.related || e.related.matches(draggable) || !e.willInsertAfter+ || !e.to.querySelector(draggable),+ onStart: (e) => { anchor = e.item.nextSibling; },+ onEnd: (e) => {+ const { item, from, to, oldIndex, newIndex } = e;+ from.insertBefore(item, anchor);+ if (from === to && oldIndex === newIndex) return;+ try {+ onSorted({+ oldIndex,+ newIndex,+ from: registry.get(from)?.meta,+ to: registry.get(to)?.meta,+ });+ } catch (error) {+ ErrorHandler('Failed to apply drag-and-drop reorder', error);+ }+ },+ });+};++const sync = (el, options = {}) => {+ const entry = registry.get(el) || {};+ entry.meta = options.meta;+ registry.set(el, entry);+ if (options.enabled && !entry.sortable) {+ entry.sortable = createSortable(el, options);+ } else if (!options.enabled && entry.sortable) {+ entry.sortable.destroy();+ entry.sortable = null;+ }+ // Re-applied on every update, as Vue class patching may remove it+ el.classList.toggle(ACTIVE_CLASS, !!entry.sortable);+};++const destroy = (el) => {+ registry.get(el)?.sortable?.destroy();+ registry.delete(el);+};++export default {+ mounted: (el, binding) => sync(el, binding.value),+ updated: (el, binding) => sync(el, binding.value),+ unmounted: destroy,+};diff --git a/src/main.js b/src/main.jsindex a2f4997a..6215e3ba 100644--- a/src/main.js+++ b/src/main.js@@ -16,6 +16,7 @@ import i18n from '@/utils/i18n'; // i18n instance (exportedimport ErrorReporting from '@/utils/logging/ErrorReporting'; // Error reporting initializer (off)import clickOutside from '@/directives/ClickOutside'; // Directive for closing popups, modals, etcimport tooltip from '@/directives/Tooltip'; // Custom tooltip directive+import dragSort from '@/directives/DragSort'; // Drag-and-drop list sorting directiveimport { initKeycloakAuth, isKeycloakEnabled } from '@/utils/auth/KeycloakAuth';import { initHeaderAuth, isHeaderAuthEnabled } from '@/utils/auth/HeaderAuth';import { initOidcAuth, isOidcEnabled } from '@/utils/auth/OidcAuth';@@ -38,6 +39,7 @@ app.component('modal', Modal);app.component('v-select', VSelect);app.directive('clickOutside', clickOutside);app.directive('tooltip', tooltip);+app.directive('dragSort', dragSort);app.config.errorHandler = (err, instance, info) => {ErrorHandler(`Vue error in ${info}`, err);diff --git a/src/store.js b/src/store.jsindex 4a24cd6f..d6760d08 100644--- a/src/store.js+++ b/src/store.js@@ -5,7 +5,7 @@ import Keys from '@/utils/StoreMutations';import {makePageName, formatConfigPath, componentVisibility, configScope, stripRootOwnedFields,} from '@/utils/config/ConfigHelpers';-import { applyItemId } from '@/utils/config/SectionHelpers';+import { applyItemId, stripItemIds } from '@/utils/config/SectionHelpers';import filterUserSections from '@/utils/CheckSectionVisibility';import ErrorHandler, { InfoHandler, InfoKeys } from '@/utils/logging/ErrorHandler';import {@@ -77,9 +77,9 @@ const readLocal = (key) => {* Item/widget `id`s are runtime-only β applied to `config` for rendering,* kept out of `configSource` so they never land in persisted YAML. */const commitConfigField = (state, field, value) => {- const runtime = field === 'sections' ? applyItemId(value) : value;- state.config = { ...state.config, [field]: runtime };- state.configSource = { ...state.configSource, [field]: value };+ const isSections = field === 'sections';+ state.config = { ...state.config, [field]: isSections ? applyItemId(value) : value };+ state.configSource = { ...state.configSource, [field]: isSections ? stripItemIds(value) : value };};/* Patch a single appConfig key. Optionally persists to a localStorage slot@@ -252,9 +252,8 @@ const store = createStore({return getUserState();},- getSectionByIndex: (state, getters) => (index) => {- return getters.sections[index];- },+ /* Index is the section's position in the raw config, not the filtered view */+ getSectionByIndex: (state) => (index) => (state.config.sections || [])[index],getItemById: (state, getters) => (id) => {if (!id) return undefined;let item;diff --git a/src/utils/config/SectionHelpers.js b/src/utils/config/SectionHelpers.jsindex c31ab3b6..1867f1b5 100644--- a/src/utils/config/SectionHelpers.js+++ b/src/utils/config/SectionHelpers.js@@ -22,6 +22,19 @@ const makeItemId = (sectionStr, itemStr, index) => {return `${index}_${charSum}_${itemTitleStr}`;};+/* Return a new array of sections with runtime ids removed from items and widgets,+ * so they don't end up in the persisted config */+export const stripItemIds = (inputSections) => (inputSections || []).map((section) => {+ const next = { ...section };+ if (Array.isArray(section.items)) {+ next.items = section.items.map(({ id: _id, ...item }) => item);+ }+ if (Array.isArray(section.widgets)) {+ next.widgets = section.widgets.map(({ id: _id, ...widget }) => widget);+ }+ return next;+});+/* Return a new array of sections with a unique id on each item and widget */export const applyItemId = (inputSections) => (inputSections || []).map((section) => {const next = { ...section };diff --git a/src/views/Home.vue b/src/views/Home.vueindex 9eec11a3..1436df4f 100644--- a/src/views/Home.vue+++ b/src/views/Home.vue@@ -15,10 +15,10 @@</div><!-- Main content, section for each group of items --><div v-if="checkTheresData(sections) || isEditMode" :class="computedClass"- ref="sectionsContainer">- <template v-for="(section, index) in filteredSections" :key="makeSectionId(section)">+ ref="sectionsContainer" v-drag-sort="sectionDragConfig">+ <template v-for="section in filteredSections" :key="makeSectionId(section)"><Section- :index="index"+ :index="section.configIndex":title="section.name":icon="section.icon || undefined":displayData="getDisplayData(section)"@@ -65,6 +65,8 @@ import {makePageName, makeRoutePath, resolveRouteIntent, viewFromPath,} from '@/utils/config/ConfigHelpers';import ErrorHandler from '@/utils/logging/ErrorHandler';+import StoreKeys from '@/utils/StoreMutations';+import { reorder } from '@/directives/DragSort';import BackIcon from '@/assets/interface-icons/back-arrow.svg';const EditModeSaveMenu = defineAsyncComponent(() => import('@/components/InteractiveEditor/EditModeSaveMenu.vue'));@@ -107,12 +109,16 @@ export default {if (colCount > 8) colCount = 8;return colCount;},- /* Return sections with filtered items, that match users search term */+ /* Return sections with filtered items, that match users search term.+ * Each is tagged with its index in the raw config, since the rendered+ * list may be filtered (e.g. sections hidden for the current user) */filteredSections() {+ const rawSections = this.$store.state.config.sections || [];const sections = this.singleSectionView || this.sections;const showHidden = this.isEditMode || !!this.searchValue || !!this.singleSectionView;return sections.map((section) => ({...section,+ configIndex: rawSections.indexOf(section),filteredItems: this.filterTiles(section.items, section.name, { showHidden }),}));},@@ -132,6 +138,17 @@ export default {if (this.colCount) classes += ` col-count-${this.colCount}`;return classes;},+ /* Config for drag-and-drop. Is disabled if sections don't match stored config */+ sectionDragConfig() {+ const storedSections = this.$store.state.config.sections || [];+ return {+ enabled: this.isEditMode && !this.singleSectionView+ && this.sections.length === storedSections.length,+ handle: '.section-header',+ draggable: '.collapsable',+ onSorted: this.handleSectionMoved,+ };+ },},watch: {/* Re-read col count once after config loaded */@@ -158,6 +175,11 @@ export default {if (!match) ErrorHandler(`No section named '${sectionTitle}' was found`);return match ? [match] : undefined;},+ /* Commits the new section order, after a drag-and-drop */+ handleSectionMoved({ oldIndex, newIndex }) {+ const { sections } = this.$store.state.config;+ this.$store.commit(StoreKeys.SET_SECTIONS, reorder(sections || [], oldIndex, newIndex));+ },readActiveColCount() {const { sectionsContainer } = this.$refs;if (!sectionsContainer) return;@@ -272,6 +294,25 @@ export default {margin-bottom: 12rem;}+ /* Drag-and-drop things, when section sorting is enabled */+ &.drag-sort-active {+ :deep(.collapsable .section-header) {+ cursor: grab;+ }+ // for empty drop slot+ :deep(.collapsable.drag-sort-ghost) {+ opacity: 0.4;+ outline: 2px dashed var(--primary);+ outline-offset: -2px;+ transition: none !important;+ transform: none !important;+ > * {+ visibility: hidden;+ transition: none !important;+ }+ }+ }+/* When in single-section view mode */&.single-section-view {display: block;diff --git a/yarn.lock b/yarn.lockindex 0a8d1ac5..914f1b3a 100644--- a/yarn.lock+++ b/yarn.lock@@ -4694,6 +4694,11 @@ smob@^1.0.0:resolved "https://registry.yarnpkg.com/smob/-/smob-1.6.2.tgz#190b94c25530c631a7ccc63de0d4c0087222d21d"integrity sha512-RQsvleCbF8cVHEv+xuDGaA4pOizFqJ0GgjtMSRo6oP8pnN7WsigHgVGey6aILRBKv4W2YOMHLqbKdnB6hpB9fw==+sortablejs@^1.15.7:+ version "1.15.7"+ resolved "https://registry.yarnpkg.com/sortablejs/-/sortablejs-1.15.7.tgz#83a0bddc472117ee328dea20b2e6f490fed20f86"+ integrity sha512-Kk8wLQPlS+yi1ZEf48a4+fzHa4yxjC30M/Sr2AnQu+f/MPwvvX9XjZ6OWejiz8crBsLwSq8GHqaxaET7u6ux0A==+"source-map-js@>=0.6.2 <2.0.0", source-map-js@^1.0.1, source-map-js@^1.0.2, source-map-js@^1.2.1:version "1.2.1"resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.2.1.tgz#1ce5650fddd87abc099eda37dcff024c2667ae46"