Skip to content

Commit

Permalink
feat(dev): fix themes (#84)
Browse files Browse the repository at this point in the history
Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
jwartofsky-yext and github-actions[bot] authored Oct 11, 2024
1 parent eb01dbb commit e19ec2e
Show file tree
Hide file tree
Showing 6 changed files with 169 additions and 71 deletions.
Binary file added .DS_Store
Binary file not shown.
107 changes: 68 additions & 39 deletions src/components/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import "@measured/puck/puck.css";
import { DevLogger } from "../utils/devLogger.ts";
import { ThemeConfig } from "../utils/themeResolver.ts";
import { ThemeSaveState } from "../internal/types/themeSaveState.ts";
import { updateThemeInEditor } from "../utils/applyTheme.ts";

export const Role = {
GLOBAL: "global",
Expand Down Expand Up @@ -62,15 +63,18 @@ export const Editor = ({
const [templateMetadata, setTemplateMetadata] = useState<TemplateMetadata>();
const [puckConfig, setPuckConfig] = useState<Config>();
const [parentLoaded, setParentLoaded] = useState<boolean>(false);
const [puckRendered, setPuckRendered] = useState(false);

// theming
const [themeInitialHistory, setThemeInitialHistory] =
useState<any>(undefined);
useState<ThemeSaveState>({ history: [{}], index: 0 });
const [themeInitialHistoryFetched, setThemeInitialHistoryFetched] =
useState<boolean>(false);
const [themeData, setThemeData] = useState<any>(); // json data
const [themeDataFetched, setThemeDataFetched] = useState<boolean>(false); // needed because themeData can be empty
const [themeSaveState, setThemeSaveState] = useState<ThemeSaveState>();
const [themeSaveState, setThemeSaveState] = useState<
ThemeSaveState | undefined
>(undefined);
const [themeSaveStateFetched, setThemeSaveStateFetched] =
useState<boolean>(false); // needed because themeSaveState can be empty

Expand Down Expand Up @@ -192,6 +196,7 @@ export const Editor = ({
templateMetadata,
saveStateFetched,
visualConfigurationDataFetched,
themeDataFetched,
themeSaveStateFetched,
]);

Expand Down Expand Up @@ -328,6 +333,9 @@ export const Editor = ({
}, [puckInitialHistory]);

const loadThemeInitialHistory = useCallback(() => {
console.log(
`themeData is ${JSON.stringify(themeData)}, themeSaveState is ${JSON.stringify(themeSaveState)}`
);
if (
!themeSaveStateFetched ||
!templateMetadata ||
Expand All @@ -350,7 +358,7 @@ export const Editor = ({
const localHistories = JSON.parse(localHistoryArray);
const localHistoryIndex = localHistories.length - 1;
setThemeInitialHistory({
histories: localHistories,
history: localHistories,
index: localHistoryIndex,
});
setThemeInitialHistoryFetched(true);
Expand All @@ -362,8 +370,9 @@ export const Editor = ({
"Dev Mode - No localStorage. Using theme data from Content"
);
if (themeData) {
console.log(`starting fresh from content: ${themeData}`);
setThemeInitialHistory({
histories: [themeData],
history: [themeData],
index: 0,
});
}
Expand All @@ -378,7 +387,7 @@ export const Editor = ({
devLogger.log("Prod Mode - No saveState. Using theme data from Content");
if (themeData) {
setThemeInitialHistory({
histories: [themeData],
history: [themeData],
index: 0,
});
}
Expand All @@ -388,51 +397,50 @@ export const Editor = ({
}

// Check localStorage for existing themes
const localHistoryArray = window.localStorage.getItem(
buildThemeLocalStorageKey()
);
// const localHistoryArray = window.localStorage.getItem(
// buildThemeLocalStorageKey()
// );

// No localStorage for themes, start from themeSaveState
if (!localHistoryArray) {
//if (!localHistoryArray) {
if (themeData) {
devLogger.log("Prod Mode - No themeLocalStorage. Using themeSaveState");
setThemeInitialHistory({
histories: themeData
? [themeData, themeSaveState.history]
: [themeSaveState.history],
index: themeData ? 1 : 0,
});
const history = themeData
? [themeData, ...themeSaveState.history]
: [...themeSaveState.history];
const themeInitialHistory = {
history: history,
index: history.length - 1,
};
setThemeInitialHistory(themeInitialHistory);
setThemeInitialHistoryFetched(true);
console.log(
`themeInitialHistory is ${JSON.stringify(themeInitialHistory)}`
);
return;
}

const localHistoryIndex = JSON.parse(localHistoryArray).findIndex(
(item: any) => item.id === saveState?.hash
);

console.log("Setting blank now");
setThemeInitialHistory({
history: [{}],
index: 0,
});
setThemeInitialHistoryFetched(true);
// If local storage reset theme history to it
if (localHistoryIndex !== -1) {
devLogger.log("Prod Mode - Using themeLocalStorage");
setThemeInitialHistory({
histories: JSON.parse(localHistoryArray),
index: localHistoryIndex,
appendData: false,
});
setPuckInitialHistoryFetched(true);
return;
}
// devLogger.log("Prod Mode - Using themeLocalStorage");
// setThemeInitialHistory({
// history: JSON.parse(localHistoryArray),
// index: themeSaveState.index,
// });
// setThemeInitialHistoryFetched(true);
// return;
}, [
setThemeInitialHistory,
setThemeInitialHistoryFetched,
clearLocalStorage,
getThemeLocalStorageKey,
]);

useEffect(() => {
if (themeInitialHistory) {
devLogger.logData("THEME_INITIAL_HISTORY", themeInitialHistory);
}
}, [themeInitialHistory]);

const { sendToParent: iFrameLoaded } = useSendMessageToParent(
"iFrameLoaded",
TARGET_ORIGINS
Expand Down Expand Up @@ -471,7 +479,14 @@ export const Editor = ({

useReceiveMessage("getThemeSaveState", TARGET_ORIGINS, (send, payload) => {
devLogger.logData("THEME_SAVE_STATE", payload);
setThemeSaveState(payload as ThemeSaveState);
console.log("themeSaveState", JSON.stringify(payload));
const themeSaveState = {
history: payload?.history
? jsonFromEscapedJsonString(payload?.history)
: [],
index: payload?.index ?? 0,
};
setThemeSaveState(themeSaveState);
setThemeSaveStateFetched(true);
send({
status: "success",
Expand All @@ -495,9 +510,10 @@ export const Editor = ({
);

useReceiveMessage("getThemeData", TARGET_ORIGINS, (send, payload) => {
const themeConfig = jsonFromEscapedJsonString(payload.themeConfig);
devLogger.logData("THEME_DATA", themeConfig);
setThemeData(themeConfig);
console.log(`payload in getThemeData is ${JSON.stringify(payload)}`);
const themeData = jsonFromEscapedJsonString(payload as any);
devLogger.logData("THEME_DATA", themeData);
setThemeData(themeData);
setThemeDataFetched(true);
send({
status: "success",
Expand Down Expand Up @@ -582,6 +598,17 @@ export const Editor = ({
!themeSaveStateFetched ||
!themeInitialHistoryFetched));

useEffect(() => {
console.log("theme useEffect");
if (puckRendered && themeInitialHistory && themeConfig) {
devLogger.logData("THEME_INITIAL_HISTORY", themeInitialHistory);
updateThemeInEditor(
themeInitialHistory.history[themeInitialHistory.index],
themeConfig
);
}
}, [themeInitialHistory, themeConfig, puckRendered]);

const progress: number =
(100 * // @ts-expect-error adding bools is fine
(!!puckConfig +
Expand Down Expand Up @@ -621,6 +648,8 @@ export const Editor = ({
themeData={themeData}
saveThemeSaveState={saveThemeSaveState}
themeHistory={themeInitialHistory}
setThemeHistory={setThemeInitialHistory}
setPuckRendered={setPuckRendered}
/>
) : (
parentLoaded && <LoadingScreen progress={progress} />
Expand Down
32 changes: 20 additions & 12 deletions src/internal/components/InternalEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { SaveState } from "../types/saveState.ts";
import { DevLogger } from "../../utils/devLogger.ts";
import ThemeSidebar from "../puck/components/ThemeSidebar.tsx";
import { ThemeConfig } from "../../utils/themeResolver.ts";
import { ThemeSaveState } from "../types/themeSaveState.ts";

interface InternalEditorProps {
puckConfig: Config;
Expand All @@ -33,7 +34,9 @@ interface InternalEditorProps {
themeConfig?: ThemeConfig;
themeData: any;
saveThemeSaveState: (data: any) => void;
themeHistory: any;
themeHistory?: ThemeSaveState;
setThemeHistory: (themeHistory: ThemeSaveState) => void;
setPuckRendered: (isRendered: boolean) => void;
}

// Render Puck editor
Expand All @@ -51,9 +54,10 @@ export const InternalEditor = ({
buildVisualConfigLocalStorageKey,
devLogger,
themeConfig,
themeData,
saveThemeSaveState,
themeHistory,
setThemeHistory,
setPuckRendered,
}: InternalEditorProps) => {
const [canEdit, setCanEdit] = useState<boolean>(false);
const historyIndex = useRef<number>(0);
Expand Down Expand Up @@ -109,15 +113,15 @@ export const InternalEditor = ({
historyIndex.current = 0;
};

const handleSaveTheme = () => {
saveThemeSaveState(themeConfig);
};

const handleSave = async (data: Data) => {
const handlePublish = async (data: Data) => {
if (isThemeMode) {
devLogger.logFunc("saveThemeData");
saveThemeData({
payload: { saveThemeData: JSON.stringify(data) },
payload: {
saveThemeData: JSON.stringify(
themeHistory?.history[themeHistory?.index]
),
},
});
return;
}
Expand Down Expand Up @@ -147,6 +151,7 @@ export const InternalEditor = ({
overrides={{
header: () => {
const { refreshPermissions, config } = usePuck();
setPuckRendered(true);

useEffect(() => {
// set permissions on the component level to allow for dynamic updating
Expand Down Expand Up @@ -181,9 +186,11 @@ export const InternalEditor = ({
return customHeader(
handleClearLocalChanges,
handleHistoryChange,
handleSave,
handlePublish,
templateMetadata.isDevMode && !templateMetadata.devOverride,
!!templateMetadata.isThemeMode,
templateMetadata.isThemeMode,
setThemeHistory,
themeConfig,
themeHistory
);
},
Expand All @@ -193,8 +200,9 @@ export const InternalEditor = ({
? () => (
<ThemeSidebar
themeConfig={themeConfig}
saveTheme={handleSaveTheme}
savedThemeValues={themeData}
saveTheme={saveThemeSaveState}
themeHistory={themeHistory!}
setThemeHistory={setThemeHistory}
/>
)
: undefined,
Expand Down
42 changes: 35 additions & 7 deletions src/internal/puck/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,19 @@ import {
TooltipTrigger,
} from "../ui/Tooltip.tsx";
import "../../../components/index.css";
import { ThemeSaveState } from "../../types/themeSaveState.ts";
import { ThemeConfig } from "../../../utils/themeResolver.ts";
import { updateThemeInEditor } from "../../../utils/applyTheme.ts";

export const customHeader = (
handleClearLocalChanges: () => void,
handleHistoryChange: (histories: History[], index: number) => void,
handleSaveData: (data: Data) => Promise<void>,
isDevMode: boolean,
isThemeMode: boolean,
themeHistory: any
setThemeHistory: (themeHistory: ThemeSaveState) => void,
themeConfig?: ThemeConfig,
themeHistory?: ThemeSaveState
) => {
const {
appState,
Expand Down Expand Up @@ -80,25 +85,48 @@ export const customHeader = (
)}
<ClearLocalChangesButton
disabled={
isThemeMode ? themeHistory.length === 1 : histories.length === 1
isThemeMode
? themeHistory?.history.length === 1
: histories.length === 1
}
onClearLocalChanges={() => {
handleClearLocalChanges();
setHistories([
{ id: "root", state: { data: histories[0].state.data } },
]);
if (isThemeMode) {
if (themeConfig) {
updateThemeInEditor(themeHistory?.history[0], themeConfig);
}
setThemeHistory({
history: [themeHistory?.history[0]],
index: 0,
});
} else {
setHistories([
{ id: "root", state: { data: histories[0].state.data } },
]);
}
}}
/>
{!isDevMode && (
<Button
variant="secondary"
disabled={
isThemeMode ? themeHistory.length === 1 : histories.length === 1
isThemeMode
? themeHistory?.history.length === 1
: histories.length === 1
}
onClick={async () => {
await handleSaveData(appState.data);
handleClearLocalChanges();
setHistories([{ id: "root", state: { data: appState.data } }]);
if (isThemeMode) {
setThemeHistory({
history: [
themeHistory?.history[themeHistory?.history.length - 1],
],
index: 0,
});
} else {
setHistories([{ id: "root", state: { data: appState.data } }]);
}
}}
>
Publish
Expand Down
Loading

0 comments on commit e19ec2e

Please sign in to comment.