@ideasonpurpose/wp-theme-addons 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,366 @@
1
+ // @ts-check
2
+
3
+ import {
4
+ BlockControls,
5
+ InspectorControls,
6
+ LinkControl,
7
+ } from "@wordpress/block-editor";
8
+ import { registerBlockVariation, createBlock } from "@wordpress/blocks";
9
+ import {
10
+ ExternalLink,
11
+ Popover,
12
+ TextControl,
13
+ ToggleControl,
14
+ ToolbarButton,
15
+ ToolbarGroup,
16
+ __experimentalToolsPanel as ToolsPanel,
17
+ __experimentalToolsPanelItem as ToolsPanelItem,
18
+ } from "@wordpress/components";
19
+ import { createHigherOrderComponent } from "@wordpress/compose";
20
+ import { useState } from "@wordpress/element";
21
+ import { addFilter } from "@wordpress/hooks";
22
+ import { SVG, Path } from "@wordpress/primitives";
23
+ import { __ } from "@wordpress/i18n";
24
+ // import { select, useSelect, withSelect } from "@wordpress/data";
25
+ import { createInterpolateElement } from "@wordpress/element";
26
+
27
+ export default {};
28
+
29
+ /**
30
+ * Include the SVG icons so we don't need the heavy @wordpress/icons dependency
31
+ */
32
+ const icon_link = (
33
+ <SVG xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
34
+ <Path d="M10 17.389H8.444A5.194 5.194 0 1 1 8.444 7H10v1.5H8.444a3.694 3.694 0 0 0 0 7.389H10v1.5ZM14 7h1.556a5.194 5.194 0 0 1 0 10.39H14v-1.5h1.556a3.694 3.694 0 0 0 0-7.39H14V7Zm-4.5 6h5v-1.5h-5V13Z" />
35
+ </SVG>
36
+ );
37
+
38
+ const icon_linkOff = (
39
+ <SVG xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
40
+ <Path d="M17.031 4.703 15.576 4l-1.56 3H14v.03l-2.324 4.47H9.5V13h1.396l-1.502 2.889h-.95a3.694 3.694 0 0 1 0-7.389H10V7H8.444a5.194 5.194 0 1 0 0 10.389h.17L7.5 19.53l1.416.719L15.049 8.5h.507a3.694 3.694 0 0 1 0 7.39H14v1.5h1.556a5.194 5.194 0 0 0 .273-10.383l1.202-2.304Z" />
41
+ </SVG>
42
+ );
43
+
44
+ const icon = (
45
+ <SVG xmlns="" fill="currentColor" viewBox="0 0 48 48">
46
+ <Path d="M39.335 5.246H22.384c-2.2 0-4 1.8-4 4v1h3v-1c0-.6.4-1 1-1h16.951c.6 0 1 .4 1 1v23.137c0 .6-.4 1-1 1H22.384c-.6 0-1-.4-1-1v-1h-3v1c0 2.2 1.8 4 4 4h16.951c2.2 0 4-1.8 4-4V9.246c0-2.2-1.8-4-4-4" />
47
+ <Path d="M9.665 18.383v3h-1c-.6 0-1 .4-1 1v16.37c0 .6.4 1 1 1h17.71c.6 0 1-.4 1-1v-7.37h3v7.37c0 2.2-1.8 4-4 4H8.665c-2.2 0-4-1.8-4-4v-16.37c0-2.2 1.8-4 4-4zM27.438 25.383h2c2.8 0 5-2.2 5-5s-2.2-5-5-5h-2v-3h2c4.4 0 8 3.6 8 8s-3.6 8-8 8h-2z" />
48
+ <Path d="M21.438 25.383v3h-2c-4.4 0-8-3.6-8-8s3.6-8 8-8h2v3h-2c-2.8 0-5 2.2-5 5s2.2 5 5 5z" />
49
+ <Path d="M29.438 21.983h-10v-3h10z" />
50
+ </SVG>
51
+ );
52
+
53
+ /**
54
+ * Generate a unique ID
55
+ * @returns {string} A unique identifier string
56
+ * NOTE: toString(36) starts with '0.', so slice from 22 for a valid ID
57
+ */
58
+ // const generateUniqueId = () => Math.random().toString(36).slice(2, 10);
59
+
60
+ export function initLinkedGroupBlock() {
61
+ registerBlockVariation("core/group", {
62
+ name: "group-linked",
63
+ title: "Linked Group",
64
+ description: "Group block with link support",
65
+ attributes: {
66
+ namespace: "ideasonpurpose/group-linked",
67
+ className: "iop-linked-group",
68
+ url: "",
69
+ opensInNewTab: false,
70
+ linkToSelf: false,
71
+ rel: "",
72
+ linkTarget: "_self",
73
+ },
74
+ icon,
75
+ isActive: ["namespace"],
76
+ });
77
+
78
+ addFilter(
79
+ "editor.BlockEdit",
80
+ "ideasonpurpose/group-linked/add-controls",
81
+ wrappedEdit,
82
+ );
83
+
84
+ // addFilter(
85
+ // "blocks.getSaveElement",
86
+ // "ideasonpurpose/group-linked/save-element",
87
+ // makeSaveElement,
88
+ // );
89
+
90
+ addFilter(
91
+ "blocks.registerBlockType",
92
+ "ideasonpurpose/group-linked/define-attributes",
93
+ defineAttributes,
94
+ );
95
+ }
96
+
97
+ /**
98
+ * Add controls to the Block Editor sidebar
99
+ * This is basically a wrapped copy of the block's Edit function
100
+ * @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/
101
+ */
102
+ const wrappedEdit = createHigherOrderComponent((BlockEdit) => {
103
+ return (props) => {
104
+ const { name, attributes, setAttributes } = props;
105
+ const { url, opensInNewTab, linkToSelf, rel, linkTarget } = attributes;
106
+
107
+ const { postId, queryId } = props.context;
108
+
109
+ if (
110
+ name !== "core/group" ||
111
+ attributes?.namespace !== "ideasonpurpose/group-linked"
112
+ ) {
113
+ return <BlockEdit {...props} />;
114
+ }
115
+
116
+ const [isLinkOpen, setIsLinkOpen] = useState(false);
117
+ const [popoverAnchor, setPopoverAnchor] = useState(null);
118
+
119
+ const newProps = { ...props };
120
+
121
+ return (
122
+ <>
123
+ <BlockEdit {...newProps} />
124
+
125
+ {queryId && (
126
+ <InspectorControls>
127
+ <ToolsPanel
128
+ label={__("Settings")}
129
+ resetAll={() => {
130
+ setAttributes({
131
+ rel: "",
132
+ linkTarget: "_self",
133
+ isLink: false,
134
+ });
135
+ }}
136
+ >
137
+ <ToolsPanelItem
138
+ label={"Link to Queried Item"}
139
+ isShownByDefault
140
+ hasValue={() => linkToSelf}
141
+ onDeselect={() => setAttributes({ linkToSelf: false })}
142
+ >
143
+ <ToggleControl
144
+ label={"Link to Queried Item"}
145
+ onChange={() => setAttributes({ linkToSelf: !linkToSelf })}
146
+ checked={linkToSelf}
147
+ />
148
+ </ToolsPanelItem>
149
+
150
+ {linkToSelf && (
151
+ <>
152
+ <ToolsPanelItem
153
+ label={__("Open in new tab")}
154
+ isShownByDefault
155
+ hasValue={() => linkTarget === "_blank"}
156
+ onDeselect={() =>
157
+ setAttributes({
158
+ linkTarget: "_self",
159
+ })
160
+ }
161
+ >
162
+ <ToggleControl
163
+ label={__("Open in new tab")}
164
+ onChange={(value) =>
165
+ setAttributes({
166
+ linkTarget: value ? "_blank" : "_self",
167
+ })
168
+ }
169
+ checked={linkTarget === "_blank"}
170
+ />
171
+ </ToolsPanelItem>
172
+ <ToolsPanelItem
173
+ label={__("Link relation")}
174
+ isShownByDefault
175
+ hasValue={() => !!rel}
176
+ onDeselect={() => setAttributes({ rel: "" })}
177
+ >
178
+ <TextControl
179
+ __next40pxDefaultSize
180
+ label={__("Link relation")}
181
+ help={createInterpolateElement(
182
+ __(
183
+ "The <a>Link Relation</a> attribute defines the relationship between a linked resource and the current document.",
184
+ ),
185
+ {
186
+ a: (
187
+ <ExternalLink href="https://developer.mozilla.org/docs/Web/HTML/Attributes/rel" />
188
+ ),
189
+ },
190
+ )}
191
+ value={rel}
192
+ onChange={(newRel) => setAttributes({ rel: newRel })}
193
+ />
194
+ </ToolsPanelItem>
195
+ </>
196
+ )}
197
+ </ToolsPanel>
198
+ </InspectorControls>
199
+ )}
200
+
201
+ {!linkToSelf && (
202
+ <BlockControls group="block">
203
+ <ToolbarGroup>
204
+ <ToolbarButton
205
+ name="link"
206
+ icon={!url ? icon_link : icon_linkOff}
207
+ onClick={() => setIsLinkOpen(!isLinkOpen)}
208
+ isActive={!url}
209
+ title={!url ? "Link" : "Unlink"}
210
+ isPressed={isLinkOpen}
211
+ ref={(el) => setPopoverAnchor(el)}
212
+ />
213
+ </ToolbarGroup>
214
+ </BlockControls>
215
+ )}
216
+
217
+ {isLinkOpen && (
218
+ <Popover
219
+ placement="bottom"
220
+ offset={16}
221
+ onClose={() => setIsLinkOpen(false)}
222
+ anchor={popoverAnchor}
223
+ __unstableSlotName={"__unstable-block-tools-after"}
224
+ shift
225
+ >
226
+ <LinkControl
227
+ value={{ url, opensInNewTab: linkTarget === "_blank" }}
228
+ onChange={(val) =>
229
+ setAttributes({
230
+ url: val.url,
231
+ // opensInNewTab: val.opensInNewTab,
232
+ linkTarget: val.opensInNewTab ? "_blank" : "_self",
233
+ })
234
+ }
235
+ onRemove={() => setAttributes({ url: "" })}
236
+ showInitialSuggestions={true}
237
+ />
238
+ </Popover>
239
+ )}
240
+ </>
241
+ );
242
+ };
243
+ }, "withInspectorControl");
244
+
245
+ /**
246
+ * This updates components in the Save representation of the block.
247
+ * This affects what will appear on the public-facing display of the page
248
+ *
249
+ * NOTE: Similar to the `save` method when creating a block from scratch?
250
+ */
251
+ const makeSaveElement = (element, blockType, attributes) => {
252
+ if (!element) {
253
+ return;
254
+ }
255
+
256
+ if (
257
+ blockType.name !== "core/group" ||
258
+ attributes?.namespace !== "ideasonpurpose/group-linked"
259
+ ) {
260
+ return element;
261
+ }
262
+
263
+ const { url, linkToSelf, rel, linkTarget } = attributes;
264
+
265
+ // console.log({ "save-props": element.props });
266
+
267
+ // TODO: Only replace the group if there's a url set
268
+ if (!url && !linkToSelf) {
269
+ return element;
270
+ }
271
+
272
+ const href = linkToSelf ? "#__LINKED_GROUP_PLACEHOLDER__" : url;
273
+
274
+
275
+ const link = (
276
+ <a
277
+ href={href}
278
+ className={"linked-group__link iop-linked-group__link"}
279
+ target={linkTarget}
280
+ rel={rel}
281
+ ></a>
282
+ );
283
+
284
+ // append a link to the block's children to avoid :first-child issues
285
+ const originalChildren = element.props.children;
286
+ const newChildren = Array.isArray(originalChildren)
287
+ ? [...originalChildren, link]
288
+ : [originalChildren, link];
289
+
290
+ attributes.className = "iop-linked-group";
291
+ return { ...element, props: { ...element.props, children: newChildren } };
292
+ };
293
+
294
+ const linkedGroupTransformTo = {
295
+ type: "block",
296
+ blocks: ["core/group"],
297
+ transform: (attributes, innerBlocks) => {
298
+ console.log(attributes);
299
+
300
+ return createBlock(
301
+ "core/group",
302
+ {
303
+ ...attributes,
304
+ className: "iop-linked-group",
305
+ url: "",
306
+ namespace: "ideasonpurpose/group-linked",
307
+ },
308
+ innerBlocks,
309
+ );
310
+ },
311
+ };
312
+
313
+ // TODO: this isn't working
314
+ const linkedGroupTransformFrom = {
315
+ type: "block",
316
+ blocks: ["core/group"],
317
+ transform: (attributes, innerBlocks) => {
318
+ const newAttributes = { ...attributes };
319
+
320
+ delete newAttributes.url;
321
+ delete newAttributes.opensInNewTab;
322
+ delete newAttributes.namespace;
323
+ return createBlock("core/group", { ...newAttributes }, innerBlocks);
324
+ },
325
+ };
326
+
327
+ /**
328
+ * In order to save values from the injected controls, we need to declare
329
+ * the attributes so WordPress knows where to store the data.
330
+ *
331
+ * Called from the blocks.registerBlockType hook.
332
+ * @link https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype
333
+ */
334
+ const defineAttributes = (settings, name) => {
335
+ // TODO: When this runs, variations haven't been defined yet, only add attributes to core/embed,
336
+ // More specific checks are performed by other filters
337
+ if (name !== "core/group") {
338
+ return settings;
339
+ }
340
+
341
+ const newSettings = {
342
+ ...settings,
343
+ usesContext: ["postId", "queryId"],
344
+ attributes: {
345
+ ...settings.attributes,
346
+ namespace: { type: "string", default: "" },
347
+ url: { type: "string", default: "" },
348
+ // opensInNewTab: { type: "boolean", default: false },
349
+
350
+ // isLink: { type: "boolean", default: false },
351
+ linkToSelf: { type: "boolean", default: false },
352
+ rel: { type: "string", attribute: "rel", default: "" },
353
+ linkTarget: { type: "string", default: "_self" },
354
+ },
355
+ };
356
+
357
+ if (!newSettings.hasLinkedGroupTransform) {
358
+ newSettings.hasLinkedGroupTransform = true;
359
+
360
+ if (!newSettings.transforms.to) {
361
+ newSettings.transforms.to = [linkedGroupTransformTo];
362
+ }
363
+ }
364
+
365
+ return newSettings;
366
+ };
@@ -0,0 +1,168 @@
1
+ <?php
2
+
3
+ /**
4
+ * This file is part of the WordPress Theme Addons.
5
+ * @link https://github.com/ideasonpurpose/wp-theme-addons
6
+ */
7
+
8
+ namespace IdeasOnPurpose\WP\Theme\Addons\Block\Variation\Query\RelatedPostsQuery;
9
+
10
+ use IdeasOnPurpose\WP\RelatedPosts;
11
+
12
+ class RelatedPostsQuery
13
+ {
14
+ public $namespace = 'ideasonpurpose/query-related-posts';
15
+
16
+ public function __construct()
17
+ {
18
+ /**
19
+ * rest_{post_type}_query filters need to be added for each post_type.
20
+ * If the filter is assigned before the init hook, custom post_types
21
+ * don't exist yet and the filter doesn't seem to work.
22
+ */
23
+ add_action('init', [$this, 'init'], 50);
24
+
25
+ add_filter('pre_render_block', [$this, 'pre_render_block_filter'], 10, 3);
26
+ }
27
+
28
+ /**
29
+ * Add rest{post_type}_query filters for all public post_types except attachments
30
+ *
31
+ * This has to be done late in the init hook, after all custom post_types have
32
+ * been defined.
33
+ * ;@link https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/
34
+ */
35
+ public function init()
36
+ {
37
+ $post_types = get_post_types(['public' => true]);
38
+ unset($post_types['attachment']);
39
+
40
+ foreach ($post_types as $post_type) {
41
+ add_filter("rest_{$post_type}_query", [$this, 'editor_intercept_query_filter'], 10, 2);
42
+ }
43
+ }
44
+
45
+ /**
46
+ * This filter adds an additional `query_loop_block_query_vars` filter if the block's namespace attribute matches.
47
+ */
48
+ public function pre_render_block_filter($pre_render, $parsed_block, $parent_block)
49
+ {
50
+ $blockName = $parsed_block['blockName'];
51
+ $namespace = $parsed_block['attrs']['namespace'] ?? null;
52
+ if ($blockName === 'core/query' && $namespace == $this->namespace) {
53
+ add_filter('query_loop_block_query_vars', [$this, 'front_end_query_filter'], 10, 3);
54
+ }
55
+
56
+ return $pre_render;
57
+ }
58
+
59
+ // NOTE: $request is a monster WP_REST_Request object which isn't particularly useful.
60
+ /**
61
+ * Called from the `query_loop_block_query_vars` filter (added from the `pre_render_block` filter above)
62
+ * @link https://developer.wordpress.org/reference/hooks/query_loop_block_query_vars/
63
+ *
64
+ * $request is a WP_REST_Request
65
+ * @link https://developer.wordpress.org/reference/classes/wp_rest_request/
66
+ *
67
+ * @param mixed $args
68
+ * @param mixed $request WP_REST_Request
69
+ * @param mixed $more
70
+ * @return mixed
71
+ */
72
+ public function editor_intercept_query_filter($args, $request)
73
+ {
74
+ global $post;
75
+ $postTypes = $request->get_param('postTypes') ?? [];
76
+ $weights = $request->get_param('weights') ?? [];
77
+ $relatedPost = $request->get_param('relatedPost') ?? ($post->ID ?? 0);
78
+
79
+ if ($weights) {
80
+ $rpArgs = [
81
+ 'post' => $relatedPost,
82
+ 'post_types' => $postTypes,
83
+ 'weights' => $weights,
84
+
85
+ 'posts_per_page' => $args['posts_per_page'],
86
+ 'offset' => $args['offset'],
87
+ ];
88
+
89
+ $rp = new RelatedPosts();
90
+ $posts = $rp->get($rpArgs);
91
+
92
+ $ids = wp_list_pluck($posts, 'ID');
93
+ $post_types = array_unique(wp_list_pluck($posts, 'post_type'));
94
+
95
+ $newArgs = [
96
+ 'post__in' => $ids,
97
+ 'post_type' => $post_types,
98
+ 'ignore_sticky_posts' => true,
99
+ 'orderby' => 'post__in',
100
+ 'posts_per_page' => count($ids),
101
+ ];
102
+
103
+ return $newArgs;
104
+ }
105
+
106
+ return $args;
107
+ }
108
+
109
+ /**
110
+ * The query for the visitor-facing front-end block will be replaced with a new query
111
+ * derived from Posts collected by RelatedPosts. A `post__in` list of the related IDs
112
+ * will be returned as is, with order determined by the RelatedPosts library.
113
+ *
114
+ * NOTE: The $query property is a set of arguments to be passed to a new WP_Query()
115
+ * call in PHP.
116
+ *
117
+ * The $block->context->query property is the query used by the Query Loop block in
118
+ * a JavaScript/React context. THEY. ARE. NOT. THE. SAME. Also not interchangeable.
119
+ *
120
+ * Called from the query_loop_block_query_vars hook
121
+ * @link https://developer.wordpress.org/reference/hooks/query_loop_block_query_vars/
122
+ *
123
+ * @param Array $query - Query args for WP_Query
124
+ * @param mixed $block - A block, likely include attributes and context
125
+ * @param Integer $page - the page of content for paginated lists
126
+ * @return array
127
+ */
128
+ public function front_end_query_filter($query, $block, $page)
129
+ {
130
+ $rpQuery = $block->context['query'];
131
+
132
+ if (!isset($rpQuery['weights']) || empty((array) $rpQuery['weights'])) {
133
+ error_log('no related content, returning early');
134
+ return $query;
135
+ }
136
+
137
+ $rpArgs = [
138
+ 'post' => $rpQuery['relatedPost'],
139
+ 'post_types' => $rpQuery['postTypes'],
140
+ 'weights' => $rpQuery['weights'],
141
+
142
+ 'posts_per_page' => $rpQuery['perPage'],
143
+ 'offset' => $rpQuery['offset'] ?? 0,
144
+ ];
145
+
146
+ /**
147
+ * Call RelatedPosts::get to fetch a set of IDs, then replace the
148
+ * returned query with those IDs and associated post_types
149
+ *
150
+ * TODO: This instantiation is too late to register the JSON-API routes
151
+ */
152
+ $rp = new RelatedPosts();
153
+ $posts = $rp->get($rpArgs);
154
+
155
+ $ids = wp_list_pluck($posts, 'ID');
156
+ $post_types = array_unique(wp_list_pluck($posts, 'post_type'));
157
+
158
+ $newArgs = [
159
+ 'post__in' => $ids,
160
+ 'post_type' => $post_types,
161
+ 'ignore_sticky_posts' => true,
162
+ 'orderby' => 'post__in',
163
+ 'posts_per_page' => -1,
164
+ ];
165
+
166
+ return $newArgs;
167
+ }
168
+ }