You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by as...@apache.org on 2026/06/19 11:56:04 UTC

(superset) 03/10: standardizing the permission manage modal

This is an automated email from the ASF dual-hosted git repository.

alexandrusoare pushed a commit to branch alexandrusoare/feat/folders-testing-branch
in repository https://gitbox.apache.org/repos/asf/superset.git

commit ae49a80cbea42d85fb6fc77e743124cd60e878a6
Author: alexandrusoare <al...@gmail.com>
AuthorDate: Tue Jun 9 17:45:38 2026 +0300

    standardizing the permission manage modal
---
 .../src/components/ListView/ListView.tsx           |  12 +-
 .../src/pages/AnalyticsList/FolderAssetsModal.tsx  |  31 +-
 .../pages/AnalyticsList/FolderPermissionsModal.tsx | 581 +++++++++++++--------
 .../src/pages/AnalyticsList/MoveToModal.tsx        | 207 +++++++-
 .../src/pages/AnalyticsList/index.tsx              |   5 +
 superset/folders/api.py                            |  47 ++
 6 files changed, 612 insertions(+), 271 deletions(-)

diff --git a/superset-frontend/src/components/ListView/ListView.tsx b/superset-frontend/src/components/ListView/ListView.tsx
index 6bc680b8f7b..56828e1256e 100644
--- a/superset-frontend/src/components/ListView/ListView.tsx
+++ b/superset-frontend/src/components/ListView/ListView.tsx
@@ -28,7 +28,6 @@ import {
   ReactNode,
 } from 'react';
 import cx from 'classnames';
-import type { ExpandableConfig } from 'antd/es/table/interface';
 import TableCollection from '@superset-ui/core/components/TableCollection';
 import BulkTagModal from 'src/features/tags/BulkTagModal';
 import {
@@ -309,18 +308,13 @@ export interface ListViewProps<T extends object = any> {
   columnsForWrapText?: string[];
   enableBulkTag?: boolean;
   bulkTagResourceName?: string;
-  /**
-   * Opt-in antd expandable-row config (e.g. `expandedRowRender`,
-   * `rowExpandable`). Callbacks receive the flattened row record.
-   */
-  expandable?: ExpandableConfig<Record<string, any>>;
+  /** Optional expandable row configuration, passed through to antd Table. */
+  expandable?: Record<string, unknown>;
   /** Optional ref exposed to callers for programmatic filter control. */
   filtersRef?: React.RefObject<{
     clearFilters: () => void;
     clearFilterById: (id: string) => void;
   }>;
-  /** Optional expandable row configuration, passed through to antd Table. */
-  expandable?: Record<string, unknown>;
 }
 
 export function ListView<T extends object = any>({
@@ -349,7 +343,6 @@ export function ListView<T extends object = any>({
   bulkTagResourceName,
   expandable,
   filtersRef,
-  expandable,
   addSuccessToast,
   addDangerToast,
 }: ListViewProps<T>) {
@@ -600,7 +593,6 @@ export function ListView<T extends object = any>({
                   setSortBy={setSortBy}
                   rows={rows}
                   columns={columns}
-                  expandable={expandable}
                   loading={loading && rows.length > 0}
                   highlightRowId={highlightRowId}
                   columnsForWrapText={columnsForWrapText}
diff --git a/superset-frontend/src/pages/AnalyticsList/FolderAssetsModal.tsx b/superset-frontend/src/pages/AnalyticsList/FolderAssetsModal.tsx
index df10d78f582..e4c2420300e 100644
--- a/superset-frontend/src/pages/AnalyticsList/FolderAssetsModal.tsx
+++ b/superset-frontend/src/pages/AnalyticsList/FolderAssetsModal.tsx
@@ -275,14 +275,35 @@ export default function FolderAssetsModal({
   const handleSave = useCallback(async () => {
     setSaving(true);
     try {
-      const payloadAssets = Array.from(selected).map(key => {
+      const all = Array.from(selected).map(key => {
         const [type, id] = key.split('-');
         return { type, id: parseInt(id, 10) };
       });
-      await SupersetClient.put({
-        endpoint: `/api/v1/folders/${folderUuid}/assets`,
-        jsonPayload: { assets: payloadAssets },
-      });
+      // Separate folders from assets — folders use parent_id update,
+      // assets use the bulk PUT endpoint
+      const assetPayload = all.filter(a => a.type !== 'folder');
+      const folderPayload = all.filter(a => a.type === 'folder');
+
+      const calls: Promise<unknown>[] = [];
+
+      // Update assets via bulk PUT
+      calls.push(
+        SupersetClient.put({
+          endpoint: `/api/v1/folders/${folderUuid}/assets`,
+          jsonPayload: { assets: assetPayload },
+        }),
+      );
+
+      // Move each selected folder into this folder via single-asset PUT
+      for (const f of folderPayload) {
+        calls.push(
+          SupersetClient.put({
+            endpoint: `/api/v1/folders/${folderUuid}/assets/folder/${f.id}`,
+          }),
+        );
+      }
+
+      await Promise.all(calls);
       addSuccessToast(t('Updated assets in %s', folderName));
       onSuccess();
       onHide();
diff --git a/superset-frontend/src/pages/AnalyticsList/FolderPermissionsModal.tsx b/superset-frontend/src/pages/AnalyticsList/FolderPermissionsModal.tsx
index 7cda2fb8092..bc0a53d2f99 100644
--- a/superset-frontend/src/pages/AnalyticsList/FolderPermissionsModal.tsx
+++ b/superset-frontend/src/pages/AnalyticsList/FolderPermissionsModal.tsx
@@ -16,11 +16,17 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
 import { t } from '@apache-superset/core/translation';
+import rison from 'rison';
 import { SupersetClient } from '@superset-ui/core';
 import { styled, css, useTheme } from '@apache-superset/core/theme';
-import { Button, Input } from '@superset-ui/core/components';
+import {
+  AsyncSelect,
+  Select,
+  Tag,
+  type SelectOptionsTypePage,
+} from '@superset-ui/core/components';
 import { StandardModal } from 'src/components/Modal';
 import { Icons } from '@superset-ui/core/components/Icons';
 
@@ -31,16 +37,14 @@ interface Subject {
   permission: Permission;
 }
 
-interface UserOption {
-  id: number;
-  first_name: string;
-  last_name: string;
-  username: string;
+interface LocalSubject extends Subject {
+  label: string;
 }
 
 interface FolderPermissionsModalProps {
   folderUuid: string;
   folderName: string;
+  currentUserId: number;
   show: boolean;
   onHide: () => void;
   addDangerToast: (msg: string) => void;
@@ -50,112 +54,147 @@ interface FolderPermissionsModalProps {
 const ModalContent = styled.div`
   ${({ theme }) => css`
     padding: ${theme.sizeUnit * 3}px ${theme.sizeUnit * 4}px;
+    display: flex;
+    flex-direction: column;
+    gap: ${theme.sizeUnit * 3}px;
   `}
 `;
 
-const SubjectRow = styled.div`
-  ${({ theme }) => css`
+const SubjectRow = styled.div<{ isCurrentUser?: boolean }>`
+  ${({ theme, isCurrentUser }) => css`
     display: flex;
     align-items: center;
-    justify-content: space-between;
-    padding: ${theme.sizeUnit * 2}px 0;
-    border-bottom: 1px solid ${theme.colorBorderSecondary};
-
-    .subject-info {
-      display: flex;
-      align-items: center;
-      gap: ${theme.sizeUnit * 2}px;
-    }
-
-    .permission-badge {
-      padding: ${theme.sizeUnit / 2}px ${theme.sizeUnit * 2}px;
-      border-radius: ${theme.borderRadius}px;
-      font-size: ${theme.fontSizeSM}px;
-      font-weight: ${theme.fontWeightStrong};
-      cursor: pointer;
-    }
-
-    .permission-editor {
-      background: ${theme.colorInfoBg};
-      color: ${theme.colorInfo};
-    }
+    gap: ${theme.sizeUnit * 2}px;
+    padding: ${theme.sizeUnit * 2}px ${theme.sizeUnit * 3}px;
+    border-radius: ${theme.borderRadius}px;
+    ${isCurrentUser ? `opacity: 0.6;` : ''}
 
-    .permission-viewer {
-      background: ${theme.colorSuccessBg};
-      color: ${theme.colorSuccess};
+    &:hover {
+      background: ${isCurrentUser ? 'transparent' : theme.colorBgTextHover};
     }
 
-    .remove-button {
-      cursor: pointer;
-      color: ${theme.colorIcon};
-      &:hover {
-        color: ${theme.colorError};
-      }
+    .subject-name {
+      flex: 1;
+      min-width: 0;
+      overflow: hidden;
+      text-overflow: ellipsis;
+      white-space: nowrap;
     }
   `}
 `;
 
-const UserList = styled.div`
+const SubjectList = styled.div`
   ${({ theme }) => css`
-    max-height: 200px;
+    max-height: 320px;
     overflow-y: auto;
-    margin-top: ${theme.sizeUnit * 2}px;
     border: 1px solid ${theme.colorBorderSecondary};
     border-radius: ${theme.borderRadius}px;
-
-    .user-row {
-      display: flex;
-      align-items: center;
-      justify-content: space-between;
-      padding: ${theme.sizeUnit * 2}px ${theme.sizeUnit * 3}px;
-
-      &:hover {
-        background: ${theme.colorBgTextHover};
-      }
-
-      .user-info {
-        display: flex;
-        align-items: center;
-        gap: ${theme.sizeUnit * 2}px;
-      }
-
-      .add-actions {
-        display: flex;
-        gap: ${theme.sizeUnit}px;
-      }
-    }
   `}
 `;
 
 const SectionLabel = styled.div`
   ${({ theme }) => css`
     font-weight: ${theme.fontWeightStrong};
-    margin-top: ${theme.sizeUnit * 4}px;
-    margin-bottom: ${theme.sizeUnit * 2}px;
+    color: ${theme.colorTextLabel};
+    font-size: ${theme.fontSizeSM}px;
+    text-transform: uppercase;
+    letter-spacing: 0.5px;
+  `}
+`;
+
+const AddRow = styled.div`
+  ${({ theme }) => css`
+    display: flex;
+    gap: ${theme.sizeUnit * 2}px;
+    align-items: center;
   `}
 `;
 
+const PERMISSION_OPTIONS = [
+  { value: 'viewer', label: t('Viewer') },
+  { value: 'editor', label: t('Editor') },
+];
+
+async function fetchUserOptions(
+  filterValue: string,
+  page: number,
+  pageSize: number,
+): Promise<SelectOptionsTypePage> {
+  const query = rison.encode({
+    filter: filterValue,
+    page,
+    page_size: pageSize,
+    order_column: 'username',
+    order_direction: 'asc',
+  });
+  const { json } = await SupersetClient.get({
+    endpoint: `/api/v1/security/users/?q=${query}`,
+  });
+  const results = json?.result || [];
+  return {
+    data: results.map(
+      (u: {
+        id: number;
+        first_name: string;
+        last_name: string;
+        username: string;
+      }) => ({
+        value: u.id,
+        label: `${u.first_name} ${u.last_name} (${u.username})`,
+      }),
+    ),
+    totalCount: json?.count ?? 0,
+  };
+}
+
 export default function FolderPermissionsModal({
   folderUuid,
   folderName,
+  currentUserId,
   show,
   onHide,
   addDangerToast,
   addSuccessToast,
 }: FolderPermissionsModalProps) {
   const theme = useTheme();
-  const [subjects, setSubjects] = useState<Subject[]>([]);
-  const [allUsers, setAllUsers] = useState<UserOption[]>([]);
+  const [serverSubjects, setServerSubjects] = useState<LocalSubject[]>([]);
+  const [localSubjects, setLocalSubjects] = useState<LocalSubject[]>([]);
   const [loading, setLoading] = useState(false);
-  const [search, setSearch] = useState('');
+  const [saving, setSaving] = useState(false);
+  const [addPermission, setAddPermission] = useState<Permission>('viewer');
 
   const fetchSubjects = useCallback(async () => {
     setLoading(true);
     try {
-      const { json } = await SupersetClient.get({
-        endpoint: `/api/v1/folders/${folderUuid}/subjects`,
-      });
-      setSubjects((json.result as Subject[]) || []);
+      const [subjectsRes, usersRes] = await Promise.all([
+        SupersetClient.get({
+          endpoint: `/api/v1/folders/${folderUuid}/subjects`,
+        }),
+        SupersetClient.get({
+          endpoint: '/api/v1/security/users/?q=(page_size:1000,page:0)',
+        }),
+      ]);
+      const subjects = (subjectsRes.json.result as Subject[]) || [];
+      const users =
+        (usersRes.json.result as {
+          id: number;
+          first_name: string;
+          last_name: string;
+          username: string;
+        }[]) || [];
+      const userMap = new Map(
+        users.map(u => [
+          u.id,
+          `${u.first_name} ${u.last_name} (${u.username})`,
+        ]),
+      );
+
+      const enriched: LocalSubject[] = subjects.map(s => ({
+        ...s,
+        label: userMap.get(s.user_id) || t('User %s', s.user_id),
+      }));
+      setServerSubjects(enriched);
+      setLocalSubjects(enriched);
     } catch {
       addDangerToast(t('Error loading permissions'));
     } finally {
@@ -163,193 +202,273 @@ export default function FolderPermissionsModal({
     }
   }, [folderUuid, addDangerToast]);
 
-  const fetchUsers = useCallback(async () => {
-    try {
-      const { json } = await SupersetClient.get({
-        endpoint: '/api/v1/security/users/?q=(page_size:100,page:0)',
-      });
-      setAllUsers((json.result as UserOption[]) || []);
-    } catch {
-      addDangerToast(t('Error loading users'));
-    }
-  }, [addDangerToast]);
-
   useEffect(() => {
     if (show) {
       fetchSubjects();
-      fetchUsers();
-      setSearch('');
+      setAddPermission('viewer');
     }
-  }, [show, fetchSubjects, fetchUsers]);
+  }, [show, fetchSubjects]);
 
-  const handleAddSubject = useCallback(
-    async (userId: number, permission: Permission) => {
-      try {
-        await SupersetClient.post({
-          endpoint: `/api/v1/folders/${folderUuid}/subjects`,
-          jsonPayload: { user_id: userId, permission },
-        });
-        addSuccessToast(t('Permission added'));
-        fetchSubjects();
-      } catch {
-        addDangerToast(t('Error adding permission'));
-      }
+  const handleAddUser = useCallback(
+    (value: number, option: { label: string }) => {
+      if (!value) return;
+      setLocalSubjects(prev => {
+        if (prev.some(s => s.user_id === value)) return prev;
+        return [
+          ...prev,
+          { user_id: value, permission: addPermission, label: option.label },
+        ];
+      });
     },
-    [folderUuid, addSuccessToast, addDangerToast, fetchSubjects],
+    [addPermission],
   );
 
-  const handleTogglePermission = useCallback(
-    async (userId: number, currentPermission: Permission) => {
-      const newPerm: Permission =
-        currentPermission === 'viewer' ? 'editor' : 'viewer';
-      try {
-        await SupersetClient.put({
-          endpoint: `/api/v1/folders/${folderUuid}/subjects/${userId}`,
-          jsonPayload: { permission: newPerm },
-        });
-        addSuccessToast(t('Permission updated'));
-        fetchSubjects();
-      } catch {
-        addDangerToast(t('Error updating permission'));
-      }
+  const handleChangePermission = useCallback(
+    (userId: number, permission: Permission) => {
+      if (userId === currentUserId) return;
+      setLocalSubjects(prev =>
+        prev.map(s => (s.user_id === userId ? { ...s, permission } : s)),
+      );
     },
-    [folderUuid, addSuccessToast, addDangerToast, fetchSubjects],
+    [currentUserId],
   );
 
   const handleRemoveSubject = useCallback(
-    async (userId: number) => {
-      try {
-        await SupersetClient.delete({
-          endpoint: `/api/v1/folders/${folderUuid}/subjects/${userId}`,
-        });
-        addSuccessToast(t('Permission removed'));
-        fetchSubjects();
-      } catch {
-        addDangerToast(t('Error removing permission'));
-      }
+    (userId: number) => {
+      if (userId === currentUserId) return;
+      setLocalSubjects(prev => prev.filter(s => s.user_id !== userId));
     },
-    [folderUuid, addSuccessToast, addDangerToast, fetchSubjects],
+    [currentUserId],
   );
 
-  const subjectUserIds = new Set(subjects.map(s => s.user_id));
+  const handleSave = useCallback(async () => {
+    setSaving(true);
+    try {
+      const serverMap = new Map(
+        serverSubjects.map(s => [s.user_id, s.permission]),
+      );
+      const localMap = new Map(
+        localSubjects.map(s => [s.user_id, s.permission]),
+      );
 
-  const availableUsers = allUsers.filter(u => {
-    if (subjectUserIds.has(u.id)) return false;
-    if (!search) return true;
-    const name = `${u.first_name} ${u.last_name} ${u.username}`.toLowerCase();
-    return name.includes(search.toLowerCase());
-  });
+      const calls: Promise<unknown>[] = [];
 
-  const getUserName = (userId: number) => {
-    const user = allUsers.find(u => u.id === userId);
-    if (user) return `${user.first_name} ${user.last_name}`;
-    return t('User %s', userId);
-  };
+      for (const [userId, permission] of localMap) {
+        if (!serverMap.has(userId)) {
+          calls.push(
+            SupersetClient.post({
+              endpoint: `/api/v1/folders/${folderUuid}/subjects`,
+              jsonPayload: { user_id: userId, permission },
+            }),
+          );
+        }
+      }
+
+      for (const [userId] of serverMap) {
+        if (!localMap.has(userId)) {
+          calls.push(
+            SupersetClient.delete({
+              endpoint: `/api/v1/folders/${folderUuid}/subjects/${userId}`,
+            }),
+          );
+        }
+      }
+
+      for (const [userId, permission] of localMap) {
+        const serverPerm = serverMap.get(userId);
+        if (serverPerm && serverPerm !== permission) {
+          calls.push(
+            SupersetClient.put({
+              endpoint: `/api/v1/folders/${folderUuid}/subjects/${userId}`,
+              jsonPayload: { permission },
+            }),
+          );
+        }
+      }
+
+      await Promise.all(calls);
+      addSuccessToast(t('Permissions updated'));
+      onHide();
+    } catch {
+      addDangerToast(t('Error updating permissions'));
+    } finally {
+      setSaving(false);
+    }
+  }, [
+    folderUuid,
+    serverSubjects,
+    localSubjects,
+    addSuccessToast,
+    addDangerToast,
+    onHide,
+  ]);
+
+  const hasChanges = useMemo(() => {
+    if (serverSubjects.length !== localSubjects.length) return true;
+    const serverMap = new Map(
+      serverSubjects.map(s => [s.user_id, s.permission]),
+    );
+    return localSubjects.some(s => serverMap.get(s.user_id) !== s.permission);
+  }, [serverSubjects, localSubjects]);
+
+  const existingUserIdsRef = useRef(new Set<number>());
+  existingUserIdsRef.current = new Set(localSubjects.map(s => s.user_id));
+
+  const filteredUserOptions = useCallback(
+    async (search: string, page: number, pageSize: number) => {
+      const result = await fetchUserOptions(search, page, pageSize);
+      return {
+        ...result,
+        data: result.data.filter(
+          (opt: { value: number }) =>
+            !existingUserIdsRef.current.has(opt.value),
+        ),
+      };
+    },
+    [],
+  );
 
   return (
     <StandardModal
       title={t('Manage permissions — %s', folderName)}
       show={show}
       onHide={onHide}
-      onSave={onHide}
-      saveText={t('Done')}
+      onSave={handleSave}
+      saveText={t('Save')}
+      saveLoading={saving}
+      saveDisabled={!hasChanges}
     >
       <ModalContent>
-        <SectionLabel>
-          {t('Current permissions')} ({subjects.length})
-        </SectionLabel>
-        {loading ? (
-          <p>{t('Loading...')}</p>
-        ) : subjects.length === 0 ? (
-          <p css={{ color: theme.colorTextSecondary }}>
-            {t('No permissions set on this folder.')}
-          </p>
-        ) : (
-          subjects.map(subject => (
-            <SubjectRow key={subject.user_id}>
-              <div className="subject-info">
-                <Icons.UserOutlined iconSize="m" />
-                <span>{getUserName(subject.user_id)}</span>
-                <span
-                  className={`permission-badge permission-${subject.permission}`}
-                  role="button"
-                  tabIndex={0}
-                  onClick={() =>
-                    handleTogglePermission(subject.user_id, subject.permission)
-                  }
-                  onKeyDown={e => {
-                    if (e.key === 'Enter')
-                      handleTogglePermission(
-                        subject.user_id,
-                        subject.permission,
-                      );
-                  }}
-                  title={t('Click to toggle')}
-                >
-                  {subject.permission}
-                </span>
-              </div>
-              <div className="subject-actions">
-                <span
-                  className="remove-button"
-                  role="button"
-                  tabIndex={0}
-                  onClick={() => handleRemoveSubject(subject.user_id)}
-                  onKeyDown={e => {
-                    if (e.key === 'Enter') handleRemoveSubject(subject.user_id);
-                  }}
-                >
-                  <Icons.DeleteOutlined iconSize="m" />
-                </span>
-              </div>
-            </SubjectRow>
-          ))
-        )}
+        <div>
+          <SectionLabel>{t('Add user')}</SectionLabel>
+          <AddRow css={{ marginTop: theme.sizeUnit }}>
+            <div css={{ flex: 1 }}>
+              <AsyncSelect
+                ariaLabel={t('Search users')}
+                placeholder={t('Search for a user…')}
+                options={filteredUserOptions}
+                onSelect={(value: number, option: { label: string }) =>
+                  handleAddUser(value, option)
+                }
+                value={null}
+                getPopupContainer={trigger =>
+                  trigger.closest('.ant-modal-content') || document.body
+                }
+              />
+            </div>
+            <Select
+              ariaLabel={t('Permission level')}
+              options={PERMISSION_OPTIONS}
+              value={addPermission}
+              onChange={(val: Permission) => setAddPermission(val)}
+              css={{ width: 120 }}
+              getPopupContainer={trigger =>
+                trigger.closest('.ant-modal-content') || document.body
+              }
+            />
+          </AddRow>
+        </div>
 
-        <SectionLabel>{t('Add users')}</SectionLabel>
-        <Input
-          placeholder={t('Search users...')}
-          value={search}
-          onChange={e => setSearch(e.target.value)}
-          allowClear
-        />
-        <UserList>
-          {availableUsers.length === 0 ? (
-            <p css={{ padding: 12, color: theme.colorTextSecondary }}>
-              {search ? t('No users found') : t('All users already added')}
+        <div>
+          <SectionLabel>
+            {t('Members')} ({localSubjects.length})
+          </SectionLabel>
+          {loading ? (
+            <p
+              css={{
+                color: theme.colorTextSecondary,
+                padding: theme.sizeUnit * 2,
+              }}
+            >
+              {t('Loading…')}
+            </p>
+          ) : localSubjects.length === 0 ? (
+            <p
+              css={{
+                color: theme.colorTextSecondary,
+                padding: theme.sizeUnit * 2,
+              }}
+            >
+              {t('No permissions set. Add users above.')}
             </p>
           ) : (
-            availableUsers.map(user => (
-              <div className="user-row" key={user.id}>
-                <div className="user-info">
-                  <Icons.UserOutlined iconSize="m" />
-                  <span>
-                    {user.first_name} {user.last_name}
-                  </span>
-                  <span css={{ color: theme.colorTextSecondary, fontSize: 12 }}>
-                    @{user.username}
-                  </span>
-                </div>
-                <div className="add-actions">
-                  <Button
-                    buttonStyle="secondary"
-                    buttonSize="xsmall"
-                    onClick={() => handleAddSubject(user.id, 'viewer')}
-                  >
-                    + {t('Viewer')}
-                  </Button>
-                  <Button
-                    buttonStyle="secondary"
-                    buttonSize="xsmall"
-                    onClick={() => handleAddSubject(user.id, 'editor')}
+            <SubjectList>
+              {localSubjects.map(subject => {
+                const isCurrentUser = subject.user_id === currentUserId;
+                return (
+                  <SubjectRow
+                    key={subject.user_id}
+                    isCurrentUser={isCurrentUser}
                   >
-                    + {t('Editor')}
-                  </Button>
-                </div>
-              </div>
-            ))
+                    <Icons.UserOutlined
+                      iconSize="m"
+                      css={{ color: theme.colorIcon, flexShrink: 0 }}
+                    />
+                    <span className="subject-name">
+                      {subject.label}
+                      {isCurrentUser && (
+                        <span
+                          css={{
+                            color: theme.colorTextSecondary,
+                            fontSize: theme.fontSizeSM,
+                            marginLeft: 4,
+                          }}
+                        >
+                          ({t('you')})
+                        </span>
+                      )}
+                    </span>
+                    {isCurrentUser ? (
+                      <Tag
+                        color={
+                          subject.permission === 'editor' ? 'blue' : 'green'
+                        }
+                      >
+                        {subject.permission === 'editor'
+                          ? t('Editor')
+                          : t('Viewer')}
+                      </Tag>
+                    ) : (
+                      <>
+                        <Select
+                          ariaLabel={t('Permission')}
+                          options={PERMISSION_OPTIONS}
+                          value={subject.permission}
+                          onChange={(val: Permission) =>
+                            handleChangePermission(subject.user_id, val)
+                          }
+                          css={{ width: 110 }}
+                          getPopupContainer={trigger =>
+                            trigger.closest('.ant-modal-content') ||
+                            document.body
+                          }
+                        />
+                        <Icons.DeleteOutlined
+                          iconSize="m"
+                          role="button"
+                          tabIndex={0}
+                          onClick={() => handleRemoveSubject(subject.user_id)}
+                          onKeyDown={(e: React.KeyboardEvent) => {
+                            if (e.key === 'Enter')
+                              handleRemoveSubject(subject.user_id);
+                          }}
+                          css={css`
+                            cursor: pointer;
+                            color: ${theme.colorIcon};
+                            flex-shrink: 0;
+                            &:hover {
+                              color: ${theme.colorError};
+                            }
+                          `}
+                        />
+                      </>
+                    )}
+                  </SubjectRow>
+                );
+              })}
+            </SubjectList>
           )}
-        </UserList>
+        </div>
       </ModalContent>
     </StandardModal>
   );
diff --git a/superset-frontend/src/pages/AnalyticsList/MoveToModal.tsx b/superset-frontend/src/pages/AnalyticsList/MoveToModal.tsx
index 5cf67f113af..fad57175e32 100644
--- a/superset-frontend/src/pages/AnalyticsList/MoveToModal.tsx
+++ b/superset-frontend/src/pages/AnalyticsList/MoveToModal.tsx
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
 import { t } from '@apache-superset/core/translation';
 import { SupersetClient } from '@superset-ui/core';
 import { styled, css } from '@apache-superset/core/theme';
@@ -25,9 +25,11 @@ import { Icons } from '@superset-ui/core/components/Icons';
 import { useToasts } from 'src/components/MessageToasts/withToasts';
 
 interface Folder {
+  id: number;
   uuid: string;
   name: string;
   parent_uuid: string | null;
+  children_count: number;
 }
 
 interface MoveToModalProps {
@@ -44,12 +46,13 @@ const ModalContent = styled.div`
   `}
 `;
 
-const FolderRow = styled.div<{ selected?: boolean }>`
-  ${({ theme, selected }) => css`
+const FolderRow = styled.div<{ selected?: boolean; depth?: number }>`
+  ${({ theme, selected, depth = 0 }) => css`
     display: flex;
     align-items: center;
     gap: ${theme.sizeUnit * 2}px;
     padding: ${theme.sizeUnit * 2}px ${theme.sizeUnit * 3}px;
+    padding-left: ${theme.sizeUnit * 3 + depth * theme.sizeUnit * 4}px;
     border-radius: 4px;
     cursor: pointer;
     background: ${selected ? theme.colorInfoBg : 'transparent'};
@@ -58,9 +61,64 @@ const FolderRow = styled.div<{ selected?: boolean }>`
     &:hover {
       background: ${selected ? theme.colorInfoBg : theme.colorBgTextHover};
     }
+
+    .folder-name {
+      flex: 1;
+    }
+
+    .toggle-button {
+      display: flex;
+      align-items: center;
+      background: none;
+      border: none;
+      cursor: pointer;
+      padding: 0;
+      color: ${theme.colorIcon};
+      &:hover {
+        color: ${theme.colorPrimary};
+      }
+    }
   `}
 `;
 
+const FolderTree = styled.div`
+  max-height: 400px;
+  overflow-y: auto;
+`;
+
+interface TreeNode extends Folder {
+  children: TreeNode[];
+}
+
+function buildTree(folders: Folder[]): TreeNode[] {
+  const map = new Map<string | null, TreeNode[]>();
+  const nodes: TreeNode[] = folders.map(f => ({ ...f, children: [] }));
+
+  for (const node of nodes) {
+    const parentKey = node.parent_uuid ?? null;
+    if (!map.has(parentKey)) map.set(parentKey, []);
+    map.get(parentKey)!.push(node);
+  }
+
+  // Attach children
+  for (const node of nodes) {
+    node.children = map.get(node.uuid) || [];
+  }
+
+  // Return root-level nodes
+  return map.get(null) || [];
+}
+
+function getDescendantUuids(node: TreeNode): Set<string> {
+  const result = new Set<string>();
+  function walk(n: TreeNode) {
+    result.add(n.uuid);
+    n.children.forEach(walk);
+  }
+  walk(node);
+  return result;
+}
+
 export default function MoveToModal({
   item,
   currentFolderUuid,
@@ -69,36 +127,91 @@ export default function MoveToModal({
   onSuccess,
 }: MoveToModalProps) {
   const { addSuccessToast, addDangerToast } = useToasts();
-  const [folders, setFolders] = useState<Folder[]>([]);
+  const [allFolders, setAllFolders] = useState<Folder[]>([]);
   const [selectedUuid, setSelectedUuid] = useState<string | null>(null);
+  const [expandedUuids, setExpandedUuids] = useState<Set<string>>(new Set());
   const [loading, setLoading] = useState(false);
   const [saving, setSaving] = useState(false);
 
   useEffect(() => {
     if (!show) return;
     setSelectedUuid(null);
+    setExpandedUuids(new Set());
     setLoading(true);
     SupersetClient.get({
       endpoint: '/api/v1/folders/?folder_type=analytics',
     })
       .then(({ json }) => {
-        setFolders(
-          (json.result || []).filter(
-            (f: Folder) => f.uuid !== currentFolderUuid,
-          ),
-        );
+        setAllFolders(json.result || []);
       })
       .catch(() => addDangerToast(t('Error loading folders')))
       .finally(() => setLoading(false));
-  }, [show, currentFolderUuid, addDangerToast]);
+  }, [show, addDangerToast]);
+
+  // Build tree and exclude the item being moved + its descendants
+  const tree = useMemo(() => {
+    const fullTree = buildTree(allFolders);
+    if (item.type !== 'folder') return fullTree;
+
+    // Find the node being moved and collect its descendants
+    const allNodes = buildTree(allFolders);
+    function findNode(nodes: TreeNode[], uuid: string): TreeNode | null {
+      for (const n of nodes) {
+        if (n.uuid === uuid) return n;
+        const found = findNode(n.children, uuid);
+        if (found) return found;
+      }
+      return null;
+    }
+    const movingNode = item.uuid ? findNode(allNodes, item.uuid) : null;
+    const excludeUuids = movingNode
+      ? getDescendantUuids(movingNode)
+      : new Set<string>();
+
+    // Filter out excluded nodes
+    function filterTree(nodes: TreeNode[]): TreeNode[] {
+      return nodes
+        .filter(n => !excludeUuids.has(n.uuid))
+        .map(n => ({ ...n, children: filterTree(n.children) }));
+    }
+    return filterTree(fullTree);
+  }, [allFolders, item]);
+
+  const toggleExpand = useCallback((uuid: string) => {
+    setExpandedUuids(prev => {
+      const next = new Set(prev);
+      if (next.has(uuid)) {
+        next.delete(uuid);
+      } else {
+        next.add(uuid);
+      }
+      return next;
+    });
+  }, []);
 
   const handleMove = useCallback(async () => {
-    if (!selectedUuid) return;
     setSaving(true);
     try {
-      await SupersetClient.put({
-        endpoint: `/api/v1/folders/${selectedUuid}/assets/${item.type}/${item.id}`,
-      });
+      if (selectedUuid === 'root') {
+        // Move to root: if folder, set parent_id to null; if asset, remove from folder
+        if (item.type === 'folder') {
+          await SupersetClient.put({
+            endpoint: `/api/v1/folders/${item.uuid}`,
+            jsonPayload: { parent_uuid: null },
+          });
+        } else {
+          // Remove asset from its current folder by moving to root
+          // This requires a separate endpoint or convention
+          // For now, use the folder update to set parent to null
+          await SupersetClient.delete({
+            endpoint: `/api/v1/folders/${currentFolderUuid}/assets/${item.type}/${item.id}`,
+          });
+        }
+      } else if (selectedUuid) {
+        await SupersetClient.put({
+          endpoint: `/api/v1/folders/${selectedUuid}/assets/${item.type}/${item.id}`,
+        });
+      }
       addSuccessToast(t('Moved "%s" successfully', item.name));
       onSuccess();
       onHide();
@@ -107,7 +220,53 @@ export default function MoveToModal({
     } finally {
       setSaving(false);
     }
-  }, [selectedUuid, item, addSuccessToast, addDangerToast, onSuccess, onHide]);
+  }, [
+    selectedUuid,
+    item,
+    currentFolderUuid,
+    addSuccessToast,
+    addDangerToast,
+    onSuccess,
+    onHide,
+  ]);
+
+  function renderNodes(nodes: TreeNode[], depth: number = 0) {
+    return nodes.map(node => {
+      const isExpanded = expandedUuids.has(node.uuid);
+      const hasChildren = node.children.length > 0;
+      return (
+        <div key={node.uuid}>
+          <FolderRow
+            selected={selectedUuid === node.uuid}
+            depth={depth}
+            onClick={() => setSelectedUuid(node.uuid)}
+          >
+            {hasChildren ? (
+              <button
+                type="button"
+                className="toggle-button"
+                onClick={e => {
+                  e.stopPropagation();
+                  toggleExpand(node.uuid);
+                }}
+              >
+                {isExpanded ? (
+                  <Icons.DownOutlined iconSize="s" />
+                ) : (
+                  <Icons.RightOutlined iconSize="s" />
+                )}
+              </button>
+            ) : (
+              <span style={{ width: 14 }} />
+            )}
+            <Icons.FolderOutlined iconSize="m" />
+            <span className="folder-name">{node.name}</span>
+          </FolderRow>
+          {isExpanded && hasChildren && renderNodes(node.children, depth + 1)}
+        </div>
+      );
+    });
+  }
 
   return (
     <StandardModal
@@ -116,25 +275,23 @@ export default function MoveToModal({
       onHide={onHide}
       onSave={handleMove}
       saveText={t('Move')}
-      saveDisabled={!selectedUuid}
+      saveDisabled={selectedUuid === null}
       saveLoading={saving}
     >
       <ModalContent>
         {loading ? (
           <p>{t('Loading folders...')}</p>
-        ) : folders.length === 0 ? (
-          <p>{t('No folders available')}</p>
         ) : (
-          folders.map(folder => (
+          <FolderTree>
             <FolderRow
-              key={folder.uuid}
-              selected={selectedUuid === folder.uuid}
-              onClick={() => setSelectedUuid(folder.uuid)}
+              selected={selectedUuid === 'root'}
+              onClick={() => setSelectedUuid('root')}
             >
-              <Icons.FolderOutlined iconSize="m" />
-              {folder.name}
+              <Icons.FolderOpenOutlined iconSize="m" />
+              <span className="folder-name">{t('Root (Analytics)')}</span>
             </FolderRow>
-          ))
+            {renderNodes(tree)}
+          </FolderTree>
         )}
       </ModalContent>
     </StandardModal>
diff --git a/superset-frontend/src/pages/AnalyticsList/index.tsx b/superset-frontend/src/pages/AnalyticsList/index.tsx
index 96c4f00e010..01fabc2c0b3 100644
--- a/superset-frontend/src/pages/AnalyticsList/index.tsx
+++ b/superset-frontend/src/pages/AnalyticsList/index.tsx
@@ -17,6 +17,7 @@
  * under the License.
  */
 import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useSelector } from 'react-redux';
 import { t } from '@apache-superset/core/translation';
 import { SupersetClient } from '@superset-ui/core';
 import { styled, useTheme } from '@apache-superset/core/theme';
@@ -160,6 +161,9 @@ function AnalyticsList({
 }) {
   const history = useHistory();
   const theme = useTheme();
+  const currentUserId: number = useSelector<any, number>(
+    state => state.user?.userId,
+  );
   const [loading, setLoading] = useState(true);
   const [items, setItems] = useState<ContentItem[]>([]);
   const [count, setCount] = useState(0);
@@ -902,6 +906,7 @@ function AnalyticsList({
         <FolderPermissionsModal
           folderUuid={folderToManagePerms.uuid ?? ''}
           folderName={folderToManagePerms.name}
+          currentUserId={currentUserId}
           show
           onHide={() => setFolderToManagePerms(null)}
           addDangerToast={addDangerToast}
diff --git a/superset/folders/api.py b/superset/folders/api.py
index d1d957bffa5..daaf839a276 100644
--- a/superset/folders/api.py
+++ b/superset/folders/api.py
@@ -636,6 +636,53 @@ class FolderRestApi(BaseSupersetApi):
         folder = FolderDAO.get_by_uuid(folder_uuid)
         if not folder:
             return self.response_404()
+        # Moving a folder into another folder = update parent_id
+        if asset_type == "folder":
+            from superset.folders.models import Folder
+
+            child_folder = db.session.query(Folder).filter(Folder.id == asset_id).first()
+            if not child_folder:
+                return self.response_404()
+            if child_folder.id == folder.id:
+                return self.response(400, message="Cannot move a folder into itself")
+            child_folder.parent_id = folder.id
+            # Copy parent's permissions to the moved folder
+            from superset.folders.models import folder_editors, folder_viewers
+
+            # Clear existing permissions on the child
+            db.session.execute(
+                folder_editors.delete().where(
+                    folder_editors.c.folder_id == child_folder.id
+                )
+            )
+            db.session.execute(
+                folder_viewers.delete().where(
+                    folder_viewers.c.folder_id == child_folder.id
+                )
+            )
+            # Copy from new parent
+            for row in db.session.execute(
+                folder_editors.select().where(
+                    folder_editors.c.folder_id == folder.id
+                )
+            ).fetchall():
+                db.session.execute(
+                    folder_editors.insert().values(
+                        folder_id=child_folder.id, user_id=row.user_id
+                    )
+                )
+            for row in db.session.execute(
+                folder_viewers.select().where(
+                    folder_viewers.c.folder_id == folder.id
+                )
+            ).fetchall():
+                db.session.execute(
+                    folder_viewers.insert().values(
+                        folder_id=child_folder.id, user_id=row.user_id
+                    )
+                )
+            db.session.commit()
+            return self.response(200, message="OK")
         if not FolderDAO.asset_exists(asset_type, asset_id):
             return self.response_404()
         FolderDAO.assign_assets(folder, [{"type": asset_type, "id": asset_id}])