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
2 changes: 1 addition & 1 deletion dist/main.js

Large diffs are not rendered by default.

79 changes: 50 additions & 29 deletions src/ChunkCollection.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
import React, { useEffect, useState, useContext } from "react";
import { ChunkCollectionContext } from "./ChunkCollectionContext";
import { EditmodeContext } from "./EditmodeContext";
import { getCachedData, storeCache, computeClassName, api } from "./utilities";
import {
getCachedData,
storeCache,
computeClassName,
api,
filterByTag,
} from "./utilities";

export function ChunkCollection({
children,
Expand All @@ -16,39 +22,54 @@ export function ChunkCollection({
const [chunks, setChunk] = useState([]);
const cacheId = identifier + limit + tags.join("");
// const { collection } = useCollectionData(["Featured Projects"]);
const { projectId, branch } = useContext(EditmodeContext);
const { projectId, branch, defaultChunks, next } =
useContext(EditmodeContext);

useEffect(() => {
// Get data from localStorage
const cachedChunk = getCachedData(cacheId);
if (cachedChunk) {
const data = JSON.parse(cachedChunk);
setChunk(data);
}
let params = new URL(document.location.href).searchParams;
const branchId = branch || params.get("em_branch_id") || "";
const urlParams = new URLSearchParams({
limit,
collection_identifier: identifier || contentKey,
project_id: projectId,
branch_id: branchId,
});
if (!next) {
const cachedChunk = getCachedData(cacheId);
if (cachedChunk) {
const data = JSON.parse(cachedChunk);
setChunk(data);
}
let params = new URL(document.location.href).searchParams;
const branchId = branch || params.get("em_branch_id") || "";
const urlParams = new URLSearchParams({
limit,
collection_identifier: identifier || contentKey,
project_id: projectId,
branch_id: branchId,
});

tags.forEach((tag) => urlParams.append("tags[]", tag));
tags.forEach((tag) => urlParams.append("tags[]", tag));

api
.get(`chunks?${urlParams}`)
.then((res) => {
if (res.data.error) throw res.data.error;
storeCache(cacheId, res.data.chunks);
if (!cachedChunk) setChunk(res.data.chunks);
})
.catch((error) => {
console.error(
`Something went wrong trying to retrieve chunk collection: ${error}. Have you provided the correct Editmode identifier as a prop to your ChunkCollection component instance?`
);
});
}, [identifier]);
api
.get(`chunks?${urlParams}`)
.then((res) => {
if (res.data.error) throw res.data.error;
storeCache(cacheId, res.data.chunks);
if (!cachedChunk) setChunk(res.data.chunks);
})
.catch((error) => {
console.error(
`Something went wrong trying to retrieve chunk collection: ${error}. Have you provided the correct Editmode identifier as a prop to your ChunkCollection component instance?`
);
});
} else if (next && defaultChunks) {
let collection_chunks;
collection_chunks = defaultChunks.filter(
(chunk) =>
(chunk.collection && chunk.collection.identifier == identifier) ||
(chunk.collection && chunk.collection.name == identifier) ||
(chunk.collection && chunk.collection.content_key == identifier)
);
if (tags) {
collection_chunks = filterByTag(collection_chunks, tags);
}
setChunk(collection_chunks);
}
}, [identifier, defaultChunks]);

if (!chunks?.length) {
return null;
Expand Down
6 changes: 5 additions & 1 deletion src/Editmode.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export function Editmode({
projectId,
defaultChunks,
branchId = "",
next = false,
}) {
const [branch, setbranch] = useState("");
const [hasWaterMark, setHasWaterMark] = useState(null);
Expand Down Expand Up @@ -44,6 +45,7 @@ export function Editmode({

script.src =
"https://unpkg.com/editmode-magic-editor@^0/dist/magic-editor.js";
script.setAttribute("async", "");
document.body.append(script);

if (!cachedItem) {
Expand All @@ -66,7 +68,9 @@ export function Editmode({
}, [branch, isEditorActive]);

return (
<EditmodeContext.Provider value={{ branch, projectId, defaultChunks }}>
<EditmodeContext.Provider
value={{ branch, projectId, defaultChunks, next }}
>
{children}
{hasWaterMark && <Watermark projectId={projectId} />}
</EditmodeContext.Provider>
Expand Down
1 change: 1 addition & 0 deletions src/EditmodeContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export const EditmodeContext = createContext({
branch: null,
projectId: null,
defaultChunks: [],
next: false,
});
82 changes: 51 additions & 31 deletions src/useChunk.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ export function useChunk(
defaultContent,
{ identifier, type, contentKey, field }
) {
const { projectId, defaultChunks, branch } = useContext(EditmodeContext);
const { projectId, defaultChunks, branch, next } =
useContext(EditmodeContext);
let [chunk, setChunk] = useState(undefined);

if (!contentKey) {
Expand All @@ -41,40 +42,59 @@ export function useChunk(
}

useEffect(() => {
let params = new URL(document.location.href).searchParams;
const branchId = branch || params.get("em_branch_id") || "";
const branchParams = (branchId && `branch_id=${branchId}`) || "";
let url = `chunks/${
identifier || contentKey
}?project_id=${projectId}&${branchParams}`;
if (branchId) cacheId += branchId;
let cachedChunk = getCachedData(cacheId);
let newChunk = cachedChunk
? JSON.parse(cachedChunk)
: fallbackChunk || {
chunk_type: type || "single_line_text",
content: defaultContent,
content_key: contentKey,
};
if (!next) {
let params = new URL(document.location.href).searchParams;
const branchId = branch || params.get("em_branch_id") || "";
const branchParams = (branchId && `branch_id=${branchId}`) || "";
let url = `chunks/${
identifier || contentKey
}?project_id=${projectId}&${branchParams}`;
if (branchId) cacheId += branchId;
let cachedChunk = getCachedData(cacheId);
let newChunk = cachedChunk
? JSON.parse(cachedChunk)
: fallbackChunk || {
chunk_type: type || "single_line_text",
content: defaultContent,
content_key: contentKey,
};

if (newChunk) setChunk(newChunk);
if (newChunk) setChunk(newChunk);

// Fetch new data
let error;
api
.get(url)
.then((res) => {
storeCache(cacheId, res.data);
if (!cachedChunk) setChunk(res.data);
}) // Store chunk to localstorage
.catch((error) => console.log(error)); // Set error state
// Fetch new data
let error;
api
.get(url)
.then((res) => {
storeCache(cacheId, res.data);
if (!cachedChunk) setChunk(res.data);
}) // Store chunk to localstorage
.catch((error) => console.log(error)); // Set error state

if (error && identifier) {
console.warn(
`Something went wrong trying to retrieve chunk data: ${error}. Have you provided the correct Editmode identifier (${identifier}) as a prop to your Chunk component instance?`
);
if (error && identifier) {
console.warn(
`Something went wrong trying to retrieve chunk data: ${error}. Have you provided the correct Editmode identifier (${identifier}) as a prop to your Chunk component instance?`
);
}
} else if (next && defaultChunks) {
let fallbackChunk;
if (identifier) {
fallbackChunk = defaultChunks.find((chunkItem) => {
return (
chunkItem.identifier === identifier ||
chunkItem.content_key === identifier
);
});
} else {
fallbackChunk = defaultChunks.find(
(chunkItem) =>
chunkItem.content_key === contentKey &&
chunkItem.project_id == projectId
);
}
setChunk(fallbackChunk);
}
}, [cacheId, branch]);
}, [cacheId, branch, defaultChunks]);

// Modify chunk if field is present and chunk_type is collection
// e.g. <Chunk identifier="identifier_......" field="Title"/>
Expand Down
89 changes: 55 additions & 34 deletions src/useGetChunk.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,71 @@


import { storeCache, getCachedData, api } from './utilities'
import { EditmodeContext } from "./EditmodeContext"
import {useEffect, useState, useContext} from 'react'
import { storeCache, getCachedData, api } from "./utilities";
import { EditmodeContext } from "./EditmodeContext";
import { useEffect, useState, useContext } from "react";

export const useGetChunk = (identifier, field = "") => {
const { projectId } = useContext(EditmodeContext);
const [project, setProject] = useState(projectId)
const { projectId, defaultChunks, next } = useContext(EditmodeContext);
const [project, setProject] = useState(projectId);
const [chunk, setChunk] = useState(undefined);

const cacheId = identifier + project + field;

useEffect(() => {
if (!project && window["chunksProjectIdentifier"]) {
setProject(window["chunksProjectIdentifier"])
}
let fallbackChunk;
if (!next) {
if (!project && window["chunksProjectIdentifier"]) {
setProject(window["chunksProjectIdentifier"]);
}

const cachedChunk = getCachedData(cacheId);
if (cachedChunk) setChunk(JSON.parse(cachedChunk))
const cachedChunk = getCachedData(cacheId);
if (cachedChunk) setChunk(JSON.parse(cachedChunk));

let url = `chunks/${identifier}?project_id=${project}`;
let url = `chunks/${identifier}?project_id=${project}`;

api
.get(url)
.then((res) => {
const error = res.data.error || res.data.message
if (!error) {
storeCache(cacheId, res.data);
if (!cachedChunk) setChunk(res.data)
}
})
.catch((error) => console.error(error, identifier, field)); // Set error state
}, [cacheId])
api
.get(url)
.then((res) => {
const error = res.data.error || res.data.message;
if (!error) {
storeCache(cacheId, res.data);
if (!cachedChunk) setChunk(res.data);
}
})
.catch((error) => console.error(error, identifier, field));
} else if (next && defaultChunks) {
if (identifier) {
fallbackChunk = defaultChunks.find((chunkItem) => {
return (
chunkItem.content_key === identifier ||
chunkItem.identifier === identifier
);
});
} else {
fallbackChunk = defaultChunks.find(
(chunkItem) =>
chunkItem.content_key === contentKey &&
chunkItem.project_id == projectId
);
}
setChunk(fallbackChunk);
}
}, [cacheId, defaultChunks]);

if (field && chunk && chunk.chunk_type == "collection_item") {
field = field.toLowerCase()
const fieldChunk = chunk.content.find(c =>
c.custom_field_identifier.toLowerCase() == field || c.custom_field_name.toLowerCase() == field
)
field = field.toLowerCase();
const fieldChunk = chunk.content.find(
(c) =>
c.custom_field_identifier.toLowerCase() == field ||
c.custom_field_name.toLowerCase() == field
);
if (fieldChunk) {
setChunk(fieldChunk)
setChunk(fieldChunk);
} else {
console.error(`We can't find a ${identifier} content with ${field} field`)
return ""
console.error(
`We can't find a ${identifier} content with ${field} field`
);
return "";
}
}
return chunk && chunk.content || ""
}

return (chunk && chunk.content) || "";
};
10 changes: 10 additions & 0 deletions src/utilities/filterTags.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const filterByTag = (
/** @type {any[]} */ chunks,
/** @type {any[]} */ filters
) => {
return chunks.filter((chunk) =>
filters.every(
(tag) => chunk.collection && chunk.tags && chunk.tags.includes(tag)
)
);
};
1 change: 1 addition & 0 deletions src/utilities/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { transformImage } from "./transformImage";
export { computeClassName } from "./computeClassName";
export { api } from "./api";
export { renderChunk } from "./renderChunk.jsx";
export { filterByTag } from "./filterTags";