Skip to content

Feature: Query Loop Block Support #98

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

Open
wants to merge 25 commits into
base: feature/classic-editor-support
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
f111a95
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
d86a2c8
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
d747367
Add QueryLoop integration scaffold
s3rgiosan Feb 21, 2025
3d55313
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
69149c8
Rename class for clarity
s3rgiosan Feb 21, 2025
278be0b
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
ff6658f
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Mar 14, 2025
bdca82a
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Mar 14, 2025
f593472
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Mar 14, 2025
afeae34
Merge branch 'feature/classic-editor-support' into feature/query-loop…
s3rgiosan Mar 14, 2025
31d0285
Add query loop block extension
s3rgiosan Mar 14, 2025
860ac4e
Update help texts
s3rgiosan Mar 14, 2025
fad2d96
Update query block extension
s3rgiosan Mar 17, 2025
8c30bcc
Rename extended attributes and add initial support for the relationsh…
s3rgiosan Mar 17, 2025
150c31e
Updates for Query Loop editor and front-end queries
s3rgiosan Mar 18, 2025
89ef678
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Mar 18, 2025
48977e9
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Apr 4, 2025
e33921d
Merge branch 'feature/classic-editor-support' into feature/query-loop…
s3rgiosan Apr 4, 2025
7a7a66d
Merge branch 'feature/classic-editor-support' into feature/query-loop…
s3rgiosan May 6, 2025
4260c99
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan May 6, 2025
668c8d0
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan May 9, 2025
0476cd5
Merge branch 'feature/classic-editor-support' into feature/query-loop…
s3rgiosan May 9, 2025
01c68d6
Merge branch 'feature/classic-editor-support' into feature/query-loop…
s3rgiosan May 26, 2025
2793617
Replace PanelBody with ToolsPanel for better integration with the Que…
s3rgiosan May 26, 2025
cdee5fe
Rename label
s3rgiosan May 26, 2025
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
5 changes: 5 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": [
"@10up/eslint-config/wordpress"
]
}
273 changes: 273 additions & 0 deletions assets/js/block-extensions/core-query.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,273 @@
/* eslint-disable @wordpress/no-unsafe-wp-apis */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable import/extensions */
/**
* External dependencies
*/
import { v4 as uuidv4 } from 'uuid';
import { registerBlockExtension, ContentPicker } from '@10up/block-components';

/**
* WordPress dependencies
*/
import {
ToggleControl,
Notice,
SelectControl,
BaseControl,
__experimentalToolsPanel as ToolsPanel,
__experimentalToolsPanelItem as ToolsPanelItem,
} from '@wordpress/components';
import { InspectorControls } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { store as coreStore } from '@wordpress/core-data';
import { store as editorStore } from '@wordpress/editor';
import { useMemo, useEffect, useRef } from '@wordpress/element';

/**
* Internal dependencies
*/
import { store } from '../store';

const BlockEdit = ({ setAttributes, attributes }) => {
const { query, showRelated, relationshipKey, sourcePost, orderByRelationship } = attributes;
const { postType: queriedPostType } = query;

const { postTypes, relationships, hasRelationships, currentPostId, currentPostType } =
useSelect(
(select) => {
const { getPostTypes } = select(coreStore);
const excludedPostTypes = ['attachment'];
const filteredPostTypes = getPostTypes({ per_page: -1 })?.filter(
({ viewable, slug }) => viewable && !excludedPostTypes.includes(slug),
);

const currentPostId = select(editorStore).getCurrentPostId();
const currentPostType = select(editorStore).getCurrentPostType();

const postRelationships = select(store).getRelationships(
sourcePost?.[0]?.id || currentPostId,
);
const filteredRelationships = Object.values(postRelationships).filter(
(relationship) =>
Array.isArray(relationship.post_type) &&
relationship.post_type.includes(queriedPostType),
);

return {
postTypes: filteredPostTypes,
relationships: filteredRelationships,
hasRelationships: filteredRelationships.length > 0,
currentPostId,
currentPostType,
};
},
[queriedPostType, sourcePost?.length],
);

const postTypesSlugs = useMemo(() => (postTypes || []).map(({ slug }) => slug), [postTypes]);

const relationshipsOptions = useMemo(
() =>
relationships.map((relationship) => ({
value: relationship.rel_key,
label: relationship.labels.name,
})),
[relationships],
);

const selectedRelationshipKey = useMemo(
() =>
relationshipKey && relationships.some((rel) => rel.rel_key === relationshipKey)
? relationshipKey
: relationships[0]?.rel_key,
[relationshipKey, relationships],
);

const selectedRelationship = useMemo(
() =>
relationships.find((relationship) => relationship.rel_key === selectedRelationshipKey),
[relationships, selectedRelationshipKey],
);

const lastQueryRef = useRef(query);

const updatedQuery = useMemo(() => {
if (!showRelated || !selectedRelationship) {
const { relationshipQuery, orderByRelationship, ...cleanQuery } = query;
return cleanQuery;
}

return {
...query,
orderByRelationship: orderByRelationship && selectedRelationship.sortable,
relationshipQuery: [
{
name: selectedRelationship.rel_name,
related_to_post: sourcePost?.[0]?.id || currentPostId,
},
],
};
}, [query, showRelated, orderByRelationship, selectedRelationship, sourcePost, currentPostId]);

useEffect(() => {
if (JSON.stringify(lastQueryRef.current) !== JSON.stringify(updatedQuery)) {
setAttributes({ query: updatedQuery });
lastQueryRef.current = updatedQuery;
}
}, [updatedQuery, setAttributes]);

const relationshipsControlLabel = __('Relationship', 'tenup-content-connect');
const relationshipsControlHelp = __(
'Select a relationship to determine how related entities are retrieved.',
'tenup-content-connect',
);
const sourcePostControlHelp = __(
'Choose the post from which related entities will be pulled. Defaults to the current post.',
'tenup-content-connect',
);

const resetAll = () => {
setAttributes({
showRelated: false,
sourcePost: undefined,
relationshipKey: undefined,
orderByRelationship: true,
});
};

const onShowRelatedChange = (value) => {
if (!value) {
resetAll();
} else {
setAttributes({
showRelated: value,
sourcePost: [
{
id: currentPostId,
type: currentPostType,
uuid: uuidv4(),
},
],
});
}
};

const onSourcePostChange = (ids) => {
setAttributes({ sourcePost: ids.length ? ids : undefined });
};

const onRelationshipChange = (value) => {
setAttributes({ relationshipKey: value });
};

const onOrderByRelationshipChange = (value) => {
setAttributes({ orderByRelationship: value });
};

return (
<InspectorControls>
<ToolsPanel label={__('Related', 'tenup-content-connect')} resetAll={resetAll}>
<ToolsPanelItem
hasValue={() => !!showRelated}
label={__('Related entities', 'tenup-content-connect')}
onDeselect={() => resetAll()}
isShownByDefault
>
<ToggleControl
label={__('Only show related entities', 'tenup-content-connect')}
checked={showRelated}
onChange={onShowRelatedChange}
/>
</ToolsPanelItem>
{showRelated && (
<ToolsPanelItem
hasValue={() => !!sourcePost}
label={__('Source post', 'tenup-content-connect')}
onDeselect={() => setAttributes({ sourcePost: undefined })}
isShownByDefault
>
<BaseControl help={sourcePostControlHelp}>
<ContentPicker
onPickChange={onSourcePostChange}
mode="post"
content={sourcePost}
contentTypes={postTypesSlugs}
maxContentItems={1}
singlePickedLabel={__('Selected post:', 'tenup-content-connect')}
/>
</BaseControl>
</ToolsPanelItem>
)}
{showRelated && (
<ToolsPanelItem
hasValue={() => !!relationshipKey}
label={__('Relationship', 'tenup-content-connect')}
onDeselect={() => setAttributes({ relationshipKey: undefined })}
isShownByDefault
>
{hasRelationships && (
<SelectControl
options={relationshipsOptions}
value={relationshipKey}
label={relationshipsControlLabel}
onChange={onRelationshipChange}
help={relationshipsControlHelp}
__nextHasNoMarginBottom
/>
)}
{!hasRelationships && (
<Notice spokenMessage={null} status="warning" isDismissible={false}>
{__(
'No relationships exist for the selected post type or post. Try selecting a different post or post type.',
'tenup-content-connect',
)}
</Notice>
)}
</ToolsPanelItem>
)}
{showRelated && selectedRelationship?.sortable && (
<ToolsPanelItem
hasValue={() => !!orderByRelationship}
label={__('Order by relationship', 'tenup-content-connect')}
onDeselect={() => setAttributes({ orderByRelationship: undefined })}
>
<ToggleControl
__nextHasNoMarginBottom
label={__('Order by relationship', 'tenup-content-connect')}
checked={orderByRelationship}
onChange={onOrderByRelationshipChange}
help={__(
'If enabled, the order of the posts will be determined by the selected relationship. This supersedes any other ordering.',
'tenup-content-connect',
)}
/>
</ToolsPanelItem>
)}
</ToolsPanel>
</InspectorControls>
);
};

registerBlockExtension('core/query', {
extensionName: 'content-connect',
attributes: {
showRelated: {
type: 'boolean',
default: false,
},
sourcePost: {
type: 'array',
},
relationshipKey: {
type: 'string',
},
orderByRelationship: {
type: 'boolean',
default: true,
},
},
classNameGenerator: () => '',
Edit: BlockEdit,
});
1 change: 1 addition & 0 deletions assets/js/block-extensions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './core-query';
3 changes: 1 addition & 2 deletions assets/js/components/relationships-panel.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from 'react';
import { useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import { PluginDocumentSettingPanel } from '@wordpress/edit-post';
import { store as editorStore, PluginDocumentSettingPanel } from '@wordpress/editor';
import { store } from '../store';
import { RelationshipManager } from './relationship-manager';

Expand Down
3 changes: 2 additions & 1 deletion assets/js/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import './store';
import './hooks';
import './block-extensions';

import { registerPlugin } from '@wordpress/plugins';
import { RelationshipsPanel } from './components/relationships-panel';

registerPlugin('wp-content-connect', {
registerPlugin('content-connect', {
render: RelationshipsPanel,
});
Loading