homegrade_blocks_production/blocks/post-card/src/edit.js
2024-07-02 16:11:53 +02:00

116 lines
2.8 KiB
JavaScript

import { __ } from "@wordpress/i18n";
import { useBlockProps } from "@wordpress/block-editor";
import { useSelect } from "@wordpress/data"; // pour les querry
import "./editor.scss";
import { RawHTML } from "@wordpress/element";
import { useEffect } from "@wordpress/element";
import { decodeEntities } from "@wordpress/html-entities";
import OptionsSelectControl from "./OptionsSelectControl";
import { useEntityProp } from "@wordpress/core-data";
export default function Edit({ attributes, setAttributes }) {
const { relatedPostId, postType } = attributes;
const currentRelatedPost = useSelect(
(select) =>
relatedPostId && postType
? select("core").getEntityRecord("postType", postType, relatedPostId)
: null,
[relatedPostId, postType],
);
const post = useSelect((select) =>
select("core").getEntityRecord("postType", postType, relatedPostId),
);
const postMainTaxonomy = useSelect(
(select) => {
return select("core").getEntityRecord(
"taxonomy",
"thematiques",
post?.thematiques ?? null,
);
},
[post],
);
const postParentTaxonomy = useSelect(
(select) => {
if (!postMainTaxonomy) return null;
if (postMainTaxonomy && !postMainTaxonomy.parent) return postMainTaxonomy;
return select("core").getEntityRecord(
"taxonomy",
"thematiques",
postMainTaxonomy?.parent ?? null,
);
},
[postMainTaxonomy],
);
const thematiqueCoverUrl = useSelect(
(select) => {
let thematiqueMediaId = postParentTaxonomy?.acf?.taxonomy_pictures?.icon;
const media = select("core").getMedia(thematiqueMediaId);
return media?.source_url ?? null;
},
[postParentTaxonomy],
);
const postTypeDatas = useSelect((select) =>
select("core").getEntityConfig("postType", postType),
);
return (
<>
<OptionsSelectControl
relatedPostId={relatedPostId}
postType={postType}
setAttributes={setAttributes}
/>
<div
{...useBlockProps({
className: `post-card`,
})}
>
{/* postParentTaxonomy */}
<img class="post-card__cover" alt="" src={thematiqueCoverUrl} />
<div class="post-card__details">
<div class="post-card__tags">
{postParentTaxonomy && (
<div
class={
"tag thematique-tag thematique-tag--" +
postParentTaxonomy.slug
}
>
{postParentTaxonomy.name}
</div>
)}
{postTypeDatas && (
<div class="tag post-type-tag">{postTypeDatas.label}</div>
)}
</div>
{currentRelatedPost && currentRelatedPost.title && (
<h2 class="post-card__title">
{decodeEntities(currentRelatedPost.title.rendered)}
</h2>
)}
</div>
{!relatedPostId && (
<>
<p>
{__(
"Ce bloc n'est relié à aucun post. Rattachez-le à un post dans la barre latérale.",
"homegrade-blocks__texte-backoffice",
)}
</p>
</>
)}
</div>
</>
);
}