Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Save draft #1352

Merged
merged 7 commits into from
Feb 21, 2024
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
14 changes: 12 additions & 2 deletions app/components/chart-selection-tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ import {
enableLayouting,
getChartConfig,
hasChartConfigs,
initChartStateFromChartEdit,
isConfiguring,
isLayouting,
isPublished,
isPublishing,
saveChartLocally,
useConfiguratorState,
} from "@/configurator";
import { ChartTypeSelector } from "@/configurator/components/chart-type-selector";
Expand Down Expand Up @@ -329,7 +331,7 @@ export const SaveDraftButton = ({
const { data: config, invalidate: invalidateConfig } = useUserConfig(chartId);
const session = useSession();

const [state] = useConfiguratorState();
const [state, dispatch] = useConfiguratorState();

const [snack, enqueueSnackbar, dismissSnack] = useLocalSnack();
const [debouncedSnack] = useDebounce(snack, 500);
Expand Down Expand Up @@ -370,7 +372,15 @@ export const SaveDraftButton = ({
}),
variant: "success",
});
replace(`/create/new?edit=${saved.key}`);
const config = await initChartStateFromChartEdit(saved.key);
if (!config) {
return;
}
dispatch({ type: "INITIALIZED", value: config });
saveChartLocally(saved.key, config);
replace(`/create/${saved.key}`, undefined, {
shallow: true,
});
} else {
throw new Error("Could not save draft");
}
Expand Down
32 changes: 16 additions & 16 deletions app/configurator/configurator-state.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1532,6 +1532,14 @@ export const initChartStateFromLocalStorage = async (
window.localStorage.removeItem(getLocalStorageKey(chartId));
};

export const saveChartLocally = (chartId: string, state: ConfiguratorState) => {
window.localStorage.setItem(
getLocalStorageKey(chartId),
JSON.stringify(state)
);
return;
};

const ConfiguratorStateProviderInternal = (
props: ConfiguratorStateProviderProps
) => {
Expand Down Expand Up @@ -1598,24 +1606,16 @@ const ConfiguratorStateProviderInternal = (
switch (state.state) {
case "CONFIGURING_CHART":
case "LAYOUTING":
if (chartId === "new") {
const chartId =
query.edit && typeof query.edit === "string"
const savedChartId =
chartId === "new"
? query.edit && typeof query.edit === "string"
? query.edit
: createChartId();
replace(`/create/${chartId}`);
window.localStorage.setItem(
getLocalStorageKey(chartId),
JSON.stringify(state)
);
} else {
// Store current state in localstorage
window.localStorage.setItem(
getLocalStorageKey(chartId),
JSON.stringify(state)
);
: createChartId()
: chartId;
if (chartId === "new") {
replace(`/create/${savedChartId}`);
}

saveChartLocally(savedChartId, state);
return;

case "PUBLISHING":
Expand Down
6 changes: 3 additions & 3 deletions app/db/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ export const createConfig = async ({
key,
data,
userId,
publishedState,
published_state,
}: {
key: string;
data: Prisma.ConfigCreateInput["data"];
userId?: User["id"] | undefined;
publishedState: PUBLISHED_STATE;
published_state: PUBLISHED_STATE;
}): Promise<{ key: string }> => {
return await prisma.config.create({
data: {
key,
data,
user_id: userId,
published_state: publishedState,
published_state,
},
});
};
Expand Down
2 changes: 1 addition & 1 deletion app/login/components/profile-content-tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export const ProfileContentTabs = (props: ProfileContentTabsProps) => {
<TabPanel className={classes.tabPanel} value="Home">
<Box
className={classes.tabPanelContent}
sx={{ display: "flex", flexDirection: "column", gap: 6 }}
sx={{ display: "flex", flexDirection: "column", gap: "3rem" }}
>
<ProfileVisualizationsTable
title={t({
Expand Down
70 changes: 33 additions & 37 deletions app/login/components/profile-tables.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,6 @@ const ProfileVisualizationsRow = (props: ProfileVisualizationsRowProps) => {

const { invalidate: invalidateUserConfigs } = useUserConfigs();

const updateConfigMut = useMutate(updateConfig);
const removeConfigMut = useMutate(removeConfig);

const {
Expand Down Expand Up @@ -375,40 +374,40 @@ const ProfileVisualizationsRow = (props: ProfileVisualizationsRowProps) => {
label: t({ id: "login.chart.share", message: "Share" }),
iconName: "linkExternal",
},
{
type: "button",
label:
config.published_state === PUBLISHED_STATE.DRAFT
? t({
id: "login.chart.actions.publish",
message: `Publish`,
})
: t({
id: "login.chart.actions.turn-into-draft",
message: "Turn into draft",
}),
iconName:
updateConfigMut.status === "fetching" ? "loading" : "linkExternal",
// {
// type: "button",
// label:
// config.published_state === PUBLISHED_STATE.DRAFT
// ? t({
// id: "login.chart.actions.publish",
// message: `Publish`,
// })
// : t({
// id: "login.chart.actions.turn-into-draft",
// message: "Turn into draft",
// }),
// iconName:
// updateConfigMut.status === "fetching" ? "loading" : "linkExternal",

onClick: async () => {
await updateConfigMut.mutate({
key: config.key,
user_id: userId,
data: {
...config.data,
state: "PUBLISHING",
},
published_state:
config.published_state === PUBLISHED_STATE.DRAFT
? PUBLISHED_STATE.PUBLISHED
: PUBLISHED_STATE.DRAFT,
});
invalidateUserConfigs();
},
onSuccess: () => {
invalidateUserConfigs();
},
},
// onClick: async () => {
// await updateConfigMut.mutate({
// key: config.key,
// user_id: userId,
// data: {
// ...config.data,
// state: "PUBLISHING",
// },
// published_state:
// config.published_state === PUBLISHED_STATE.DRAFT
// ? PUBLISHED_STATE.PUBLISHED
// : PUBLISHED_STATE.DRAFT,
// });
// invalidateUserConfigs();
// },
// onSuccess: () => {
// invalidateUserConfigs();
// },
// },
{
type: "button",
label: t({ id: "login.chart.rename", message: "Rename" }),
Expand Down Expand Up @@ -443,14 +442,11 @@ const ProfileVisualizationsRow = (props: ProfileVisualizationsRowProps) => {

return sortBy(actions, (x) => x.priority);
}, [
config.data,
config.key,
config.published_state,
invalidateUserConfigs,
openRename,
removeConfigMut,
updateConfigMut,
userId,
]);

const chartTitle = React.useMemo(() => {
Expand Down
22 changes: 3 additions & 19 deletions app/pages/api/config-create.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,8 @@
import { getServerSession } from "next-auth";

import { createConfig } from "@/db/config";

import { api } from "../../server/nextkit";

import { nextAuthOptions } from "./auth/[...nextauth]";
import ConfigController from "@/server/config-controller";
import { api } from "@/server/nextkit";

const route = api({
POST: async ({ req, res }) => {
const session = await getServerSession(req, res, nextAuthOptions);
const userId = session?.user?.id;
const { data, publishedState } = req.body;

return await createConfig({
key: data.key,
data,
userId,
publishedState: publishedState,
});
},
POST: ConfigController.create,
});

export default route;
19 changes: 2 additions & 17 deletions app/pages/api/config-remove.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,9 @@
import { getServerSession } from "next-auth";

import { getConfig, removeConfig } from "@/db/config";
import ConfigController from "@/server/config-controller";

import { api } from "../../server/nextkit";

import { nextAuthOptions } from "./auth/[...nextauth]";

const route = api({
POST: async ({ req, res }) => {
const session = await getServerSession(req, res, nextAuthOptions);
const sessionUserId = session?.user?.id;
const { key } = req.body;

const config = await getConfig(key);
if (sessionUserId !== config?.user_id) {
throw new Error("Unauthorized!");
}

return await removeConfig({ key });
},
POST: ConfigController.remove,
});

export default route;
23 changes: 2 additions & 21 deletions app/pages/api/config-update.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,9 @@
import { getServerSession } from "next-auth";

import { updateConfig } from "@/db/config";
import ConfigController from "@/server/config-controller";

import { api } from "../../server/nextkit";

import { nextAuthOptions } from "./auth/[...nextauth]";

const route = api({
POST: async ({ req, res }) => {
const session = await getServerSession(req, res, nextAuthOptions);
const serverUserId = session?.user?.id;
const { key, user_id, data, published_state } = req.body;

if (serverUserId !== user_id) {
throw new Error("Unauthorized!");
}

return await updateConfig({
key,
data,
user_id,
published_state,
});
},
POST: ConfigController.update,
});

export default route;
57 changes: 57 additions & 0 deletions app/server/config-controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { getServerSession } from "next-auth";

import {
createConfig,
getConfig,
removeConfig,
updateConfig,
} from "@/db/config";
import { nextAuthOptions } from "@/pages/api/auth/[...nextauth]";
import { controller } from "@/server/nextkit";

const ConfigController = controller({
create: async ({ req, res }) => {
const session = await getServerSession(req, res, nextAuthOptions);
const userId = session?.user?.id;
const { data, published_state } = req.body;

return await createConfig({
key: data.key,
data,
userId,
published_state: published_state,
});
},

remove: async ({ req, res }) => {
const session = await getServerSession(req, res, nextAuthOptions);
const sessionUserId = session?.user?.id;
const { key } = req.body;

const config = await getConfig(key);
if (sessionUserId !== config?.user_id) {
throw new Error("Unauthorized!");
}

return await removeConfig({ key });
},

update: async ({ req, res }) => {
const session = await getServerSession(req, res, nextAuthOptions);
const serverUserId = session?.user?.id;
const { key, user_id, data, published_state } = req.body;

if (serverUserId !== user_id) {
throw new Error("Unauthorized!");
}

return await updateConfig({
key,
data,
user_id,
published_state,
});
},
});

export default ConfigController;
11 changes: 10 additions & 1 deletion app/server/nextkit.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import createAPI from "nextkit";
import createAPI, { NextkitHandler } from "nextkit";

/** Provides type hints */
export const controller = <
THandlers extends Record<string, NextkitHandler<null, unknown>>
>(
methods: THandlers
) => {
return methods;
};

export const api = createAPI({
async onError(_req, _res, error) {
Expand Down
Loading