This commit is contained in:
Philipinho
2025-04-16 20:19:16 +01:00
parent 418e61614c
commit 5bdefda9c7
16 changed files with 412 additions and 151 deletions

View File

@ -9,17 +9,15 @@ import classes from "./theme-toggle.module.css";
export function ThemeToggle() {
const { setColorScheme } = useMantineColorScheme();
const computedColorScheme = useComputedColorScheme("light", {
getInitialValueInEffect: true,
});
const computedColorScheme = useComputedColorScheme();
return (
<Tooltip label="Toggle Color Scheme">
<ActionIcon
variant="default"
onClick={() =>
setColorScheme(computedColorScheme === "light" ? "dark" : "light")
}
onClick={() => {
setColorScheme(computedColorScheme === "light" ? "dark" : "light");
}}
aria-label="Toggle color scheme"
>
<IconSun className={classes.light} size={18} stroke={1.5} />

View File

@ -70,6 +70,10 @@
background-color: light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-5));
}
.row:focus .node:global(.isFocused) {
background-color: light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-5));
}
.row {
white-space: nowrap;
cursor: pointer;

View File

@ -0,0 +1,13 @@
import { atomWithWebStorage } from "@/lib/jotai-helper.ts";
import { atom } from 'jotai/index';
export const tableOfContentAsideAtom = atomWithWebStorage<boolean>(
"showTOC",
true,
);
export const mobileTableOfContentAsideAtom = atom<boolean>(false);
const sidebarWidthAtom = atomWithWebStorage<number>('sidebarWidth', 300);

View File

@ -1,31 +1,83 @@
import {
Button,
Group,
MantineSize,
Popover,
Switch,
Text,
TextInput,
} from "@mantine/core";
import { IconWorld } from "@tabler/icons-react";
import React, { useState } from "react";
import { useShareStatusQuery } from "@/features/share/queries/share-query.ts";
import React, { useEffect, useState } from "react";
import {
useCreateShareMutation,
useShareForPageQuery,
useUpdateShareMutation,
} from "@/features/share/queries/share-query.ts";
import { useParams } from "react-router-dom";
import { extractPageSlugId } from "@/lib";
import { useTranslation } from "react-i18next";
import CopyTextButton from "@/components/common/copy.tsx";
import { getAppUrl } from "@/lib/config.ts";
export default function ShareModal() {
const { t } = useTranslation();
const { pageSlug } = useParams();
const { data } = useShareStatusQuery(extractPageSlugId(pageSlug));
const pageId = extractPageSlugId(pageSlug);
const { data: share } = useShareForPageQuery(pageId);
const createShareMutation = useCreateShareMutation();
const updateShareMutation = useUpdateShareMutation();
// pageIsShared means that the share exists and its level equals zero.
const pageIsShared = share && share.level === 0;
// if level is greater than zero, then it is a descendant page from a shared page
const isDescendantShared = share && share.level > 0;
const publicLink =
window.location.protocol +'//' + window.location.host +
"/share/" +
data?.["share"]?.["key"] +
"/" +
pageSlug;
const publicLink = `${getAppUrl()}/share/${share?.key}/${pageSlug}`;
// TODO: think of permissions
// controls should be read only for non space editors.
// we could use the same shared content but have it have a share status
// when you unshare, we hide the rest menu
// todo, is public only if this is the shared page
// if this is not the shared page and include chdilren == false, then set it to false
const [isPagePublic, setIsPagePublic] = useState<boolean>(false);
useEffect(() => {
if (share) {
setIsPagePublic(true);
} else {
setIsPagePublic(false);
}
}, [share, pageId]);
const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.currentTarget.checked;
createShareMutation.mutateAsync({ pageId: pageId });
setIsPagePublic(value);
// on create refetch share
};
const handleSubPagesChange = async (
event: React.ChangeEvent<HTMLInputElement>,
) => {
const value = event.currentTarget.checked;
updateShareMutation.mutateAsync({
shareId: share.id,
includeSubPages: value,
});
};
const handleIndexSearchChange = async (
event: React.ChangeEvent<HTMLInputElement>,
) => {
const value = event.currentTarget.checked;
updateShareMutation.mutateAsync({
shareId: share.id,
searchIndexing: value,
});
};
return (
<Popover width={350} position="bottom" withArrow shadow="md">
@ -39,50 +91,69 @@ export default function ShareModal() {
</Button>
</Popover.Target>
<Popover.Dropdown>
<Group justify="space-between" wrap="nowrap" gap="xl">
<div>
<Text size="md">{t("Make page public")}</Text>
</div>
<ToggleShare isChecked={true}></ToggleShare>
</Group>
{isDescendantShared ? (
<Text>
{t("This page was shared via")} {share.sharedPage.title}
</Text>
) : (
<>
<Group justify="space-between" wrap="nowrap" gap="xl">
<div>
<Text>Share page</Text>
<Text size="xs" c="dimmed">
Make it public to the internet
</Text>
</div>
<Switch
onChange={handleChange}
defaultChecked={isPagePublic}
size="sm"
/>
</Group>
<Group my="sm" grow>
<TextInput
variant="filled"
value={publicLink}
pointer
readOnly
rightSection={<CopyTextButton text={publicLink} />}
/>
</Group>
{pageIsShared && (
<>
<Group my="sm" grow>
<TextInput
variant="filled"
value={publicLink}
readOnly
rightSection={<CopyTextButton text={publicLink} />}
/>
</Group>
<Group justify="space-between" wrap="nowrap" gap="xl">
<div>
<Text>{t("Include sub pages")}</Text>
<Text size="xs" c="dimmed">
Include children of this page
</Text>
</div>
<Switch
onChange={handleSubPagesChange}
checked={share.includeSubPages}
size="xs"
/>
</Group>
<Group justify="space-between" wrap="nowrap" gap="xl" mt="sm">
<div>
<Text>{t("Enable search indexing")}</Text>
<Text size="xs" c="dimmed">
Allow search engine indexing
</Text>
</div>
<Switch
onChange={handleIndexSearchChange}
checked={share.searchIndexing}
size="xs"
/>
</Group>
</>
)}
</>
)}
</Popover.Dropdown>
</Popover>
);
}
interface PageWidthToggleProps {
isChecked: boolean;
size?: MantineSize;
label?: string;
}
export function ToggleShare({ isChecked, size, label }: PageWidthToggleProps) {
const { t } = useTranslation();
const [checked, setChecked] = useState(isChecked);
const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.currentTarget.checked;
setChecked(value);
};
return (
<Switch
size={size}
label={label}
labelPosition="left"
defaultChecked={checked}
onChange={handleChange}
aria-label={t("Toggle share")}
/>
);
}

View File

@ -2,13 +2,12 @@ import React from "react";
import {
Affix,
AppShell,
Burger,
Button,
Group,
ScrollArea,
Text,
Tooltip,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { useGetSharedPageTreeQuery } from "@/features/share/queries/share-query.ts";
import { useParams } from "react-router-dom";
import SharedTree from "@/features/share/components/shared-tree.tsx";
@ -16,6 +15,18 @@ import { TableOfContents } from "@/features/editor/components/table-of-contents/
import { readOnlyEditorAtom } from "@/features/editor/atoms/editor-atoms.ts";
import { ThemeToggle } from "@/components/theme-toggle.tsx";
import { useAtomValue } from "jotai";
import { useAtom } from "jotai";
import {
desktopSidebarAtom,
mobileSidebarAtom,
} from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
import SidebarToggle from "@/components/ui/sidebar-toggle-button.tsx";
import { useTranslation } from "react-i18next";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
import {
mobileTableOfContentAsideAtom,
tableOfContentAsideAtom,
} from "@/features/share/atoms/sidebar-atom.ts";
const MemoizedSharedTree = React.memo(SharedTree);
@ -24,7 +35,15 @@ export default function ShareShell({
}: {
children: React.ReactNode;
}) {
const [opened, { toggle }] = useDisclosure();
const { t } = useTranslation();
const [mobileOpened] = useAtom(mobileSidebarAtom);
const [desktopOpened] = useAtom(desktopSidebarAtom);
const toggleMobile = useToggleSidebar(mobileSidebarAtom);
const toggleDesktop = useToggleSidebar(desktopSidebarAtom);
const [tocOpened] = useAtom(tableOfContentAsideAtom);
const [mobileTocOpened] = useAtom(mobileTableOfContentAsideAtom);
const { shareId } = useParams();
const { data } = useGetSharedPageTreeQuery(shareId);
const readOnlyEditor = useAtomValue(readOnlyEditorAtom);
@ -35,19 +54,51 @@ export default function ShareShell({
navbar={{
width: 300,
breakpoint: "sm",
collapsed: { mobile: !opened, desktop: false },
collapsed: {
mobile: !mobileOpened,
desktop: !desktopOpened,
},
}}
aside={{
width: 300,
breakpoint: "sm",
collapsed: { mobile: true, desktop: false },
breakpoint: "md",
collapsed: {
mobile: mobileTocOpened,
desktop: tocOpened,
},
}}
padding="md"
>
<AppShell.Header>
<Group wrap="nowrap" justify="space-between" p="sm">
<Burger opened={opened} onClick={toggle} size="sm" />
<ThemeToggle />
<Group>
{data?.pageTree?.length > 0 && (
<>
<Tooltip label={t("Sidebar toggle")}>
<SidebarToggle
aria-label={t("Sidebar toggle")}
opened={mobileOpened}
onClick={toggleMobile}
hiddenFrom="sm"
size="sm"
/>
</Tooltip>
<Tooltip label={t("Sidebar toggle")}>
<SidebarToggle
aria-label={t("Sidebar toggle")}
opened={desktopOpened}
onClick={toggleDesktop}
visibleFrom="sm"
size="sm"
/>
</Tooltip>
</>
)}
</Group>
<Group>
<ThemeToggle />
</Group>
</Group>
</AppShell.Header>

View File

@ -22,6 +22,8 @@ import { extractPageSlugId } from "@/lib";
import { OpenMap } from "react-arborist/dist/main/state/open-slice";
import classes from "@/features/page/tree/styles/tree.module.css";
import styles from "./share.module.css";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
interface SharedTree {
sharedPageTree: ISharedPageTree;
@ -40,6 +42,7 @@ export default function SharedTree({ sharedPageTree }: SharedTree) {
const [openTreeNodes, setOpenTreeNodes] = useAtom<OpenMap>(
openSharedTreeNodesAtom,
);
const currentNodeId = extractPageSlugId(pageSlug);
const treeData: SharedPageTreeNode[] = useMemo(() => {
@ -99,6 +102,11 @@ export default function SharedTree({ sharedPageTree }: SharedTree) {
setOpenTreeNodes(tree?.openState);
}}
initialOpenState={openTreeNodes}
onClick={(e) => {
if (tree && tree.focusedNode) {
tree.select(tree.focusedNode);
}
}}
>
{Node}
</Tree>
@ -108,9 +116,9 @@ export default function SharedTree({ sharedPageTree }: SharedTree) {
}
function Node({ node, style, tree }: NodeRendererProps<any>) {
const navigate = useNavigate();
const { shareId } = useParams();
const { t } = useTranslation();
const [, setMobileSidebarState] = useAtom(mobileSidebarAtom);
const pageUrl = buildSharedPageUrl({
shareId: shareId,
@ -125,6 +133,9 @@ function Node({ node, style, tree }: NodeRendererProps<any>) {
className={clsx(classes.node, node.state, styles.treeNode)}
component={Link}
to={pageUrl}
onClick={() => {
setMobileSidebarState(false);
}}
>
<PageArrow node={node} />
<span className={classes.text}>{node.data.name || t("untitled")}</span>

View File

@ -2,23 +2,26 @@ import {
keepPreviousData,
useMutation,
useQuery,
useQueryClient,
UseQueryResult,
} from "@tanstack/react-query";
import { notifications } from "@mantine/notifications";
import { useTranslation } from "react-i18next";
import {
ICreateShare,
ISharedItem,
ISharedItem, ISharedPage,
ISharedPageTree,
IShareForPage,
IShareInfoInput,
} from "@/features/share/types/share.types.ts";
IUpdateShare,
} from '@/features/share/types/share.types.ts';
import {
createShare,
deleteShare,
getSharedPageTree,
getShareForPage,
getShareInfo,
getShares,
getShareStatus,
updateShare,
} from "@/features/share/services/share-service.ts";
import { IPage } from "@/features/page/types/page.types.ts";
@ -36,7 +39,7 @@ export function useGetSharesQuery(
export function useShareQuery(
shareInput: Partial<IShareInfoInput>,
): UseQueryResult<IPage, Error> {
): UseQueryResult<ISharedPage, Error> {
const query = useQuery({
queryKey: ["shares", shareInput],
queryFn: () => getShareInfo(shareInput),
@ -46,12 +49,12 @@ export function useShareQuery(
return query;
}
export function useShareStatusQuery(
export function useShareForPageQuery(
pageId: string,
): UseQueryResult<IPage, Error> {
): UseQueryResult<IShareForPage, Error> {
const query = useQuery({
queryKey: ["share-status", pageId],
queryFn: () => getShareStatus(pageId),
queryKey: ["share-for-page", pageId],
queryFn: () => getShareForPage(pageId),
enabled: !!pageId,
staleTime: 5 * 60 * 1000,
});
@ -63,7 +66,6 @@ export function useCreateShareMutation() {
const { t } = useTranslation();
return useMutation<any, Error, ICreateShare>({
mutationFn: (data) => createShare(data),
onSuccess: (data) => {},
onError: (error) => {
notifications.show({ message: t("Failed to share page"), color: "red" });
},
@ -71,8 +73,15 @@ export function useCreateShareMutation() {
}
export function useUpdateShareMutation() {
return useMutation<any, Error, Partial<IShareInfoInput>>({
const queryClient = useQueryClient();
return useMutation<any, Error, IUpdateShare>({
mutationFn: (data) => updateShare(data),
onSuccess: (data) => {
queryClient.refetchQueries({
predicate: (item) =>
["share-for-page"].includes(item.queryKey[0] as string),
});
},
});
}

View File

@ -3,10 +3,12 @@ import { IPage } from "@/features/page/types/page.types";
import {
ICreateShare,
ISharedItem,
ISharedItem, ISharedPage,
ISharedPageTree,
IShareForPage,
IShareInfoInput,
} from "@/features/share/types/share.types.ts";
IUpdateShare,
} from '@/features/share/types/share.types.ts';
import { IPagination, QueryParams } from "@/lib/types.ts";
export async function getShares(
@ -21,22 +23,20 @@ export async function createShare(data: ICreateShare): Promise<any> {
return req.data;
}
export async function getShareStatus(pageId: string): Promise<any> {
const req = await api.post<any>("/shares/status", { pageId });
export async function updateShare(data: IUpdateShare): Promise<any> {
const req = await api.post<any>("/shares/update", data);
return req.data;
}
export async function getShareForPage(pageId: string): Promise<IShareForPage> {
const req = await api.post<any>("/shares/for-page", { pageId });
return req.data;
}
export async function getShareInfo(
shareInput: Partial<IShareInfoInput>,
): Promise<IPage> {
const req = await api.post<IPage>("/shares/info", shareInput);
return req.data;
}
export async function updateShare(
data: Partial<IShareInfoInput>,
): Promise<any> {
const req = await api.post<any>("/shares/update", data);
): Promise<ISharedPage> {
const req = await api.post<ISharedPage>("/shares/page-info", shareInput);
return req.data;
}

View File

@ -5,6 +5,7 @@ export interface IShare {
key: string;
pageId: string;
includeSubPages: boolean;
searchIndexing: boolean;
creatorId: string;
spaceId: string;
workspaceId: string;
@ -32,11 +33,36 @@ export interface ISharedItem extends IShare {
};
}
export interface ICreateShare {
pageId: string;
includeSubPages?: boolean;
export interface ISharedPage extends IShare {
page: IPage;
share: IShare & {
level: number;
sharedPage: { id: string; slugId: string; title: string };
};
}
export interface IShareForPage extends IShare {
level: number;
page: {
id: string;
title: string;
slugId: string;
};
sharedPage: {
id: string;
slugId: string;
title: string;
};
}
export interface ICreateShare {
pageId?: string;
includeSubPages?: boolean;
searchIndexing?: boolean;
}
export type IUpdateShare = ICreateShare & { shareId: string; pageId?: string };
export interface IShareInfoInput {
pageId: string;
}

View File

@ -1,9 +1,9 @@
import { useParams } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import { Helmet } from "react-helmet-async";
import { useTranslation } from "react-i18next";
import { useShareQuery } from "@/features/share/queries/share-query.ts";
import { Container } from "@mantine/core";
import React from "react";
import React, { useEffect } from "react";
import ReadonlyPageEditor from "@/features/editor/readonly-page-editor.tsx";
import { extractPageSlugId } from "@/lib";
import { Error404 } from "@/components/ui/error-404.tsx";
@ -11,19 +11,27 @@ import { Error404 } from "@/components/ui/error-404.tsx";
export default function SingleSharedPage() {
const { t } = useTranslation();
const { pageSlug } = useParams();
const { shareId } = useParams();
const navigate = useNavigate();
const {
data: page,
isLoading,
isError,
error,
} = useShareQuery({ pageId: extractPageSlugId(pageSlug) });
const { data, isLoading, isError, error } = useShareQuery({
pageId: extractPageSlugId(pageSlug),
});
useEffect(() => {
if (shareId && data) {
if (data.share.key !== shareId) {
// affects parent share, what to do?
//navigate(`/share/${data.share.key}/${pageSlug}`);
}
}
}, [shareId, data]);
if (isLoading) {
return <></>;
}
if (isError || !page) {
if (isError || !data) {
if ([401, 403, 404].includes(error?.["status"])) {
return <Error404 />;
}
@ -33,14 +41,14 @@ export default function SingleSharedPage() {
return (
<div>
<Helmet>
<title>{`${page?.icon || ""} ${page?.title || t("untitled")}`}</title>
<title>{`${data?.page?.icon || ""} ${data?.page?.title || t("untitled")}`}</title>
</Helmet>
<Container size={900}>
<ReadonlyPageEditor
key={page.id}
title={page.title}
content={page.content}
key={data.page.id}
title={data.page.title}
content={data.page.content}
/>
</Container>
</div>