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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions archived/moon/.env
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

# Add MEGA_HOST, MEGA_INTERNAL_HOST to your environment for development
# MEGA_HOST and MEGA_INTERNAL_HOST default to http://localhost:8000
MEGA_HOST=$MEGA_HOST
MEGA_INTERNAL_HOST=$MEGA_INTERNAL_HOST
# MEGA_HOST=$MEGA_HOST
# MEGA_INTERNAL_HOST=$MEGA_INTERNAL_HOST
MEGA_HOST=http://git.gitmega.com
MEGA_INTERNAL_HOST= http://git.gitmega.com
Comment thread
benjamin-747 marked this conversation as resolved.

SECRET_KEY=$YOUR_SECRET_KEY #(not prefixed with NEXT_PUBLIC_ )
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,26 @@ const CodeTable = ({ directory, readmeContent}:any) => {
], []);

const handleRowClick = (record: DataType) => {
if (record.content_type === "file") {
const newPath = `/blob/${real_path}/${record.name}`;
const normalizedPath = real_path?.replace(/^\/|\/$/g, '');
const pathParts = normalizedPath?.split('/') || [];

if (record.content_type === "file") {
const newPath = `/blob/${normalizedPath}/${encodeURIComponent(record.name)}`;

router.push(newPath);
} else {
var newPath = '';

if (real_path === '/') {
newPath = `/tree/${record.name}`;
} else {
newPath = `/tree/${real_path}/${record.name}`;
}
router.push(
newPath,
);
}
router.push(newPath);
} else {
let newPath: string;

const hasTree = pathParts?.includes('tree');

if (!hasTree && pathParts.length >= 2) {
pathParts?.splice(2, 0, 'tree');
}
pathParts?.push(encodeURIComponent(record.name));

newPath = `/${pathParts?.join('/')}`;
router.push(newPath);
}
}

return (
Expand Down
31 changes: 31 additions & 0 deletions moon/apps/web/components/CodeView/TreeView/BreadCrumb.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'github-markdown-css/github-markdown-light.css'
import { Breadcrumb } from 'antd'
import { useRouter } from 'next/router';

const Bread = ({ path }:any) => {
const router = useRouter();
const scope = router.query.org as string

const breadCrumbItems = path?.map((sub_path: any, index: number) => {
if (index == path?.length - 1) {
return {
title: sub_path,
};
} else {
const href = `/${scope}/code/tree/${path?.slice(0, index + 1).join('/')}`;

return {
title: sub_path,
href: href,
};
}
});

return (
<div className='m-4'>
<Breadcrumb items={breadCrumbItems}/>
</div>
);
};

export default Bread;
69 changes: 69 additions & 0 deletions moon/apps/web/components/CodeView/TreeView/CloneTabs.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React, { useEffect, useState } from 'react';
import { Tabs, TabsProps, Button, Space, Popover, Input } from 'antd';
import copy from 'copy-to-clipboard';
import {CopyIcon, AlarmCheckIcon, DownloadIcon} from '@gitmono/ui/Icons'
// import { CopyOutlined, CheckOutlined, DownloadOutlined } from '@ant-design/icons';
import { usePathname } from 'next/navigation';


const CloneTabs = ({ endpoint }:any) => {
const pathname = usePathname();
const [text, setText] = useState<string>(pathname||'');
const [copied, setCopied] = useState<boolean>(false);
const [active_tab, setActiveTab] = useState<string>('1')

const onChange = (key: string) => {
setActiveTab(key)
};

useEffect(() => {
if (endpoint) {
const url = new URL(endpoint);

if (active_tab === '1') {
setText(`${url.href}${pathname?.replace('/tree/', '')}.git`);
} else {
setText(`ssh://git@${url.host}${pathname?.replace('/tree', '')}.git`);
}
}
}, [pathname, active_tab, endpoint]);



const handleCopy = () => {
copy(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000); // Reset after 2 seconds
};

const tab_items: TabsProps['items'] = [
{
key: '1',
label: 'HTTP',
children:
<Space style={{ width: '100%' }}>
<Input value={text} />
<Button onClick={handleCopy} icon={copied ? <AlarmCheckIcon /> : <CopyIcon />} size={'small'} />
</Space>
},
{
key: '2',
label: 'SSH',
children: <Space style={{ width: '100%' }}>
<Input value={text} />
<Button onClick={handleCopy} icon={copied ? <AlarmCheckIcon /> : <CopyIcon />} size={'small'} />
</Space>
}
];

return (
<Popover placement="bottomRight"
content={<Tabs defaultActiveKey="1" items={tab_items} onChange={onChange} />}
trigger="click">
<Button icon={<DownloadIcon />}>Code</Button>
</Popover>
)

}

export default CloneTabs;
208 changes: 208 additions & 0 deletions moon/apps/web/components/CodeView/TreeView/RepoTree.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import 'github-markdown-css/github-markdown-light.css'
// import { DownloadIcon} from '@gitmono/ui/Icons'
import { DownOutlined } from '@ant-design/icons/lib'
import { useState, useEffect, useCallback } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { Tree, TreeProps } from 'antd/lib'
import { DataNode, EventDataNode } from 'antd/lib/tree'

interface TreeNode extends DataNode {
title: string;
key: string;
isLeaf: boolean;
path: string;
children?: TreeNode[];
}

const RepoTree = ({ directory }:any) => {
const router = useRouter();
const pathname = usePathname();
const [treeData, setTreeData] = useState<TreeNode[]>([]);
const [updateTree, setUpdateTree] = useState(false);
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

const convertToTreeData = useCallback((directory: any) => {
return sortProjectsByType(directory)?.map((item) => {
const treeItem = {
title: item.name,
key: item.id,
isLeaf: item.content_type !== 'directory',
path: item.path,
expanded: false, // initialize expanded state to false
children: [] // eneure every node having the children element
};

return treeItem;
});
}, []);

useEffect(() => {
setTreeData(convertToTreeData(directory));
}, [directory, convertToTreeData]);


useEffect(() => {
if (updateTree) {
setUpdateTree(false);
}
}, [updateTree]);

// sortProjectsByType function to sort projects by file type
const sortProjectsByType = (projects: any[]) => {
return projects?.sort((a, b) => {
if (a.content_type === 'directory' && b.content_type === 'file') {
return -1; // directory comes before file
} else if (a.content_type === 'file' && b.content_type === 'directory') {
return 1; // file comes after directory
} else {
return 0; // maintain original order
}
});
};

// append the clicked dir to the treeData
const appendTreeData = (treeData:any, subItems:object, clickedNodeTitle: string) => {
return treeData.map((item: { title: string; children: any }) => {
if (item.title === clickedNodeTitle) {
return {
...item,
children: subItems
};
} else if (Array.isArray(item.children)) {
return {
...item,
children: appendTreeData(item.children, subItems, clickedNodeTitle)
};
}
});
};

const onExpand = async (expandedKeys: any[], {expanded, node}: any) => {
if (expanded) {
let responseData;

try {
// query tree by path
const reqPath = pathname?.replace('/tree', '') + '/' + node.title;

if (node.path && node.path !== '' && node.path !== undefined) {
responseData = await fetch(`/api/tree?path=${node.path}`)
.then(response => response.json())
.catch(e => {
throw new Error('Failed to fetch tree data');
})
} else {
responseData = await fetch(`/api/tree?path=${reqPath}`)
.then(response => response.json())
.catch(e => {
throw new Error('Failed to fetch tree data');
})
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error fetching tree data:', error);

}
const subTreeData = convertToTreeData(responseData?.data?.data);
const newTreeData = appendTreeData(treeData, subTreeData, node.title);

setExpandedKeys([...expandedKeys, node.key]);
setTreeData(newTreeData);
} else {
setExpandedKeys(expandedKeys.filter(key => key !== node.key));
}
};

const onSelect: TreeProps<TreeNode>['onSelect'] = (
selectedKeys: React.Key[],
_info: {
event: 'select';
selected: boolean;
node: EventDataNode<TreeNode>;
selectedNodes: TreeNode[];
nativeEvent: MouseEvent;
}
) => {
const selectedKey = selectedKeys[0]?.toString();
// only click one, example: click the first one is ['0-0'], then the array index is 0
const pathArray = selectedKey.split('-').map((part: string) => parseInt(part, 10));
// according to the current route, splicing the next route and determine the type to jump
const real_path = pathname?.replace('/tree', '');

if (Array.isArray(treeData) && treeData?.length > 0) {
if (Array.isArray(pathArray) && pathArray.length === 2) {
// root folder
const clickNode = treeData[pathArray[1]] as TreeNode
// determine file type and router push

if (clickNode.isLeaf) {
router.push(`/blob/${real_path}/${clickNode.title}`);
} else {
router.push(`${pathname}/${clickNode.title}`);
}
} else {
// child list, recursively find the target node
const findNode = (data: TreeNode[], indices: number[]): TreeNode | null => {
if (indices.length === 0) return null;
if (indices.length === 1) return data[indices[0]];

const node = data[indices[1]] as TreeNode;
let current = node;

for (let i = 2; i < indices.length; i++) {
if (!current.children) return null;
current = current.children[indices[i]] as TreeNode;
}

return current;
};

// build the path
const buildPath = (indices: number[]): string => {
let path = '';
let current = treeData[indices[1]] as TreeNode;

path += current.title;

for (let i = 2; i < indices.length; i++) {
if (!current.children) break;
current = current.children[indices[i]] as TreeNode;
path += '/' + current.title;
}

return path;
};

const targetNode = findNode(treeData, pathArray);

if (targetNode) {
const fullPath = buildPath(pathArray);

if (targetNode.isLeaf) {
router.push(`/blob/${real_path}/${fullPath}`);
} else {
router.push(`${pathname}/${fullPath}`);
}
}
}
} else {
router.push(`${pathname}`)
}
};

return (
<div className="mt-4">
<Tree
// multiple
onSelect={onSelect}
onExpand={onExpand}
treeData={treeData}
showLine={true}
switcherIcon={<DownOutlined />}
expandedKeys={expandedKeys}
/>
</div >
);
};

export default RepoTree;
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';
import { useGetTreeCommitInfo } from '@/hooks/useGetTreeCommitInfo';
import { CommonResultVecTreeCommitItem } from '@gitmono/types/generated';

export default function TestView() {
export default function CodeView() {
const { data:TreeCommitInfo } = useGetTreeCommitInfo('/')

type DirectoryType = NonNullable<CommonResultVecTreeCommitItem['data']>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ import { SidebarLink } from './SidebarLink'
import { useScope } from '@/contexts/scope'
import { ComponentIcon } from '@gitmono/ui/Icons'

export function SidebarTest() {
export function SidebarCode() {
const { scope } = useScope()

return (
<>
<SidebarLink
id='test'
label='Test'
href={`/${scope}/test`}
active={router.pathname === '/[org]/test'}
id='code'
label='Code'
href={`/${scope}/code`}
active={router.pathname === '/[org]/code'}
leadingAccessory={<ComponentIcon />}
/>
</>
Expand Down
Loading