Skip to content

Commit

Permalink
Merge pull request #82 from alleyinteractive/feature/posts-attribute
Browse files Browse the repository at this point in the history
Misc changes - Part 2
  • Loading branch information
renatonascalves authored Oct 24, 2023
2 parents 98b8fce + c693646 commit 6358743
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 94 deletions.
108 changes: 26 additions & 82 deletions blocks/query/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { PostPicker, TermSelector, Checkboxes } from '@alleyinteractive/block-editor-tools';
import classnames from 'classnames';
import { useDebounce } from '@uidotdev/usehooks';
import ApiFetch from '@wordpress/api-fetch';
import apiFetch from '@wordpress/api-fetch';
import { InnerBlocks, InspectorControls, useBlockProps } from '@wordpress/block-editor';
import {
PanelBody,
Expand All @@ -18,62 +18,20 @@ import { addQueryArgs } from '@wordpress/url';

import type { WP_REST_API_Post, WP_REST_API_Posts } from 'wp-types';
import { Template } from '@wordpress/blocks';
import type {
EditProps,
Option,
Taxonomies,
Term,
Types,
} from './types';

import {
mainDedupe,
} from '../../services/deduplicate';

import './index.scss';

interface EditProps {
attributes: {
backfillPosts?: number[];
deduplication?: string;
maxNumberOfPosts?: number;
minNumberOfPosts?: number;
numberOfPosts?: number;
offset?: number;
posts?: any[];
query: {
[key: string]: string | number | number[] | string[];
}
postTypes?: string[];
searchTerm?: string;
terms?: {
[key: string]: any[];
};
};
setAttributes: (attributes: any) => void;
}

interface Taxonomies {
[key: string]: {
name: string;
slug: string;
rest_base: string;
};
}

interface Types {
[key: string]: {
name: string;
slug: string;
rest_base: string;
};
}

interface Option {
label: string;
value: string;
}

interface Term {
id: number;
title: string;
url: string;
type: string;
}

interface Window {
wpCurateQueryBlock: {
allowedPostTypes: Array<string>;
Expand All @@ -99,7 +57,7 @@ export default function Edit({
offset = 0,
posts: manualPosts = [],
postTypes = ['post'],
searchTerm,
searchTerm = '',
terms = {},
},
setAttributes,
Expand Down Expand Up @@ -153,10 +111,7 @@ export default function Edit({
// Fetch available taxonomies.
useEffect(() => {
const fetchTaxonomies = async () => {
const path = '/wp/v2/taxonomies';
ApiFetch({
path,
}).then((response) => {
apiFetch({ path: '/wp/v2/taxonomies' }).then((response) => {
setAvailableTaxonomies(response as Taxonomies);
});
};
Expand All @@ -166,10 +121,7 @@ export default function Edit({
// Fetch available post types.
useEffect(() => {
const fetchTypes = async () => {
const path = '/wp/v2/types';
ApiFetch({
path,
}).then((response) => {
apiFetch({ path: '/wp/v2/types' }).then((response) => {
setAvailableTypes(response as Types);
});
};
Expand All @@ -193,7 +145,7 @@ export default function Edit({
);
path += termQueryArgs;

ApiFetch({
apiFetch({
path,
}).then((response) => {
const postIds: number[] = (response as WP_REST_API_Posts).map(
Expand Down Expand Up @@ -260,6 +212,7 @@ export default function Edit({
manualPosts[i] = null; // eslint-disable-line no-param-reassign
}
}

manualPosts = manualPosts.slice(0, numberOfPosts); // eslint-disable-line no-param-reassign

const TEMPLATE: Template[] = [
Expand Down Expand Up @@ -294,31 +247,24 @@ export default function Edit({
return (
<>
<div {...useBlockProps()}>
<InnerBlocks
template={TEMPLATE}
/>
<InnerBlocks template={TEMPLATE} />
</div>

<InspectorControls>
{ /* @ts-ignore */ }
<PanelBody
title={__('Setup', 'wp-curate')}
initialOpen
>
{minNumberOfPosts !== undefined && minNumberOfPosts !== maxNumberOfPosts ? (
<>
{ /* @ts-ignore */ }
<RangeControl
label={__('Number of Posts', 'wp-curate')}
help={__('The maximum number of posts to show.', 'wp-curate')}
value={numberOfPosts}
onChange={setNumberOfPosts}
min={minNumberOfPosts}
max={maxNumberOfPosts}
/>
</>
<RangeControl
label={__('Number of Posts', 'wp-curate')}
help={__('The maximum number of posts to show.', 'wp-curate')}
value={numberOfPosts}
onChange={setNumberOfPosts}
min={minNumberOfPosts}
max={maxNumberOfPosts}
/>
) : null}
{ /* @ts-ignore */ }
<RangeControl
label={__('Offset', 'wp-curate')}
help={__('The number of posts to pass over.', 'wp-curate')}
Expand All @@ -334,8 +280,7 @@ export default function Edit({
initialOpen={false}
className="manual-posts"
>
{manualPosts.map((post, index) => (
/* @ts-ignore */
{manualPosts.map((_post, index) => (
<PanelRow className={classnames(
'manual-posts__container',
{ 'manual-posts__container--selected': manualPosts[index] },
Expand All @@ -346,7 +291,7 @@ export default function Edit({
allowedTypes={allowedPostTypes}
onReset={() => setManualPost(0, index)}
onUpdate={(id: number) => { setManualPost(id, index); }}
value={manualPosts[index] ?? 0}
value={manualPosts[index] || 0}
className="manual-posts__picker"
/>
</PanelRow>
Expand All @@ -368,7 +313,7 @@ export default function Edit({
<>
{ /* @ts-ignore */ }
<TermSelector
label={availableTaxonomies[taxonomy].name}
label={availableTaxonomies[taxonomy].name || taxonomy}
subTypes={[taxonomy]}
selected={terms[taxonomy] ?? []}
onSelect={(newCategories: Term[]) => setTerms(taxonomy, newCategories)}
Expand All @@ -377,11 +322,10 @@ export default function Edit({
</>
))
) : null}
{ /* @ts-ignore */ }
<TextControl
label={__('Search Term', 'wp-curate')}
onChange={(next) => setAttributes({ searchTerm: next })}
value={searchTerm as string}
value={searchTerm}
/>
</PanelBody>
</InspectorControls>
Expand Down
56 changes: 56 additions & 0 deletions blocks/query/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
interface EditProps {
attributes: {
backfillPosts?: number[];
deduplication?: string;
maxNumberOfPosts?: number;
minNumberOfPosts?: number;
numberOfPosts?: number;
offset?: number;
posts?: any[];
query: {
[key: string]: string | number | number[] | string[];
}
postTypes?: string[];
searchTerm?: string;
terms?: {
[key: string]: any[];
};
};
setAttributes: (attributes: any) => void;
}

interface Taxonomies {
[key: string]: {
name: string;
slug: string;
rest_base: string;
};
}

interface Types {
[key: string]: {
name: string;
slug: string;
rest_base: string;
};
}

interface Option {
label: string;
value: string;
}

interface Term {
id: number;
title: string;
url: string;
type: string;
}

export type {
EditProps,
Taxonomies,
Types,
Option,
Term,
};
37 changes: 25 additions & 12 deletions services/deduplicate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,16 @@ export function mainDedupe() {
}
const postTypeString = postTypes.join(',');
let postIndex = 0;

// New array to hold our final list of posts.
const allPosts: Array<number | undefined> = [];
const allPostIds: Array<number | undefined> = [];

// New array to hold the pinned posts in the order they should be.
const manualPostIdArray: Array<number | null> = posts;

// Remove any pinned posts from the backfilled posts list.
const filteredPosts = backfillPosts.filter((post) => !manualPostIdArray.includes(post));

// Fill out the array with nulls where there isn't a pinned post.
for (let i = 0; i < numberOfPosts; i += 1) {
if (!manualPostIdArray[i]) {
Expand All @@ -147,10 +150,11 @@ export function mainDedupe() {
}

// Loop through the pinned posts/null and generate the final list.
manualPostIdArray.forEach((post, index) => {
manualPostIdArray.forEach((_post, index) => {
let manualPost;
let backfillPost;
let isUnique = false;

// If there is a pinned post, use it. Otherwise, use the next unused backfilled post.
if (manualPostIdArray[index] !== null) {
manualPost = manualPostIdArray[index];
Expand All @@ -170,21 +174,30 @@ export function mainDedupe() {
postIndex += 1;
} while (isUnique === false && postIndex <= filteredPosts.length);
}
allPosts.push(manualPost ?? backfillPost);
allPostIds.push(manualPost || backfillPost);
});
// Set the query attribute to pass to the child blocks.
const query = {
perPage: numberOfPosts,
postType: 'post',
type: postTypeString,
include: allPosts.join(','),
orderby: 'include',
};

// Update the query block with the new query.
// @ts-ignore
dispatch('core/block-editor').updateBlockAttributes(queryBlock.clientId, { query, queryId: 0 });
dispatch('core/block-editor')
.updateBlockAttributes(
queryBlock.clientId,
{
// Set the query attribute to pass to the child blocks.
query: {
perPage: numberOfPosts,
postType: 'post',
type: postTypeString,
include: allPostIds.join(','),
orderby: 'include',
},
queryId: 0,
},
);
});

running = false;

if (redo) {
// Another run has been requested. Let's run it.
mainDedupe();
Expand Down

0 comments on commit 6358743

Please sign in to comment.