@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,102 @@
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\CssLocalProps;
9
+
10
+ /**
11
+ * Applies --local-* CSS properties (text, bg, border colors) to allowed blocks
12
+ * during `render_block` (frontend) and localizes the filtered block list for editor JS.
13
+ */
14
+ class CssLocalProps
15
+ {
16
+ public function __construct()
17
+ {
18
+ add_filter('render_block', [$this, 'addCSSLocalPropsToBlock'], 10, 2);
19
+ add_action('enqueue_block_editor_assets', [$this, 'localizeToEditor']);
20
+ }
21
+
22
+ /**
23
+ * Adds CSS local properties to the block content for allowed blocks.
24
+ *
25
+ * This function processes core/button blocks and adds custom CSS properties
26
+ * for text color, background color, and border color based on the block's attributes.
27
+ *
28
+ * @param string $block_content The HTML content of the block.
29
+ * @param array $block The block data array containing attributes and block name.
30
+ * @return string The modified block content with added CSS properties.
31
+ */
32
+ public function addCSSLocalPropsToBlock($block_content, $block)
33
+ {
34
+ $allowedBlocks = $this->getAddToBlocks();
35
+
36
+ if (!in_array($block['blockName'], $allowedBlocks)) {
37
+ return $block_content;
38
+ }
39
+
40
+ $attrs = $block['attrs'] ?? [];
41
+
42
+ $varWpColorTemplate = 'var(--wp--preset--color--%s)';
43
+
44
+ $textColor =
45
+ $attrs['textColor'] ?? null
46
+ ? sprintf($varWpColorTemplate, $attrs['textColor'])
47
+ : $attrs['style']['color']['text'] ?? null;
48
+
49
+ $bgColor =
50
+ $attrs['backgroundColor'] ?? null
51
+ ? sprintf($varWpColorTemplate, $attrs['backgroundColor'])
52
+ : $attrs['style']['color']['background'] ?? null;
53
+
54
+ $borderColor =
55
+ $attrs['borderColor'] ?? null
56
+ ? sprintf($varWpColorTemplate, $attrs['borderColor'])
57
+ : $attrs['style']['border']['color'] ?? null;
58
+
59
+ $styleProps = array_filter([
60
+ $textColor ? "--local-text-color:{$textColor}" : null,
61
+ $bgColor ? "--local-bg-color:{$bgColor}" : null,
62
+ $borderColor ? "--local-border-color:{$borderColor}" : null,
63
+ ]);
64
+
65
+ if (empty($styleProps)) {
66
+ return $block_content;
67
+ }
68
+
69
+ $propsString = implode(';', $styleProps) . ';';
70
+
71
+ $tags = new \WP_HTML_Tag_Processor($block_content);
72
+
73
+ // Target ONLY the first (outer wrapper) tag.
74
+ // Use while ($tags->next_tag()) if you intentionally want to apply to ALL tags inside the block.
75
+ if ($tags->next_tag()) {
76
+ $existing_style = $tags->get_attribute('style');
77
+ $existing_style = is_string($existing_style) ? $existing_style : '';
78
+
79
+ // Not completely sure whether prepending or appending is the right choice here,
80
+ // or if it actually matters at all.
81
+ // $new_style = $propsString . $existing_style; //prepend
82
+ $new_style = $existing_style . $propsString; //append
83
+
84
+ $tags->set_attribute('style', $new_style);
85
+ }
86
+
87
+ return $tags->get_updated_html();
88
+ }
89
+
90
+ protected function getAddToBlocks()
91
+ {
92
+ return apply_filters('iop/add_css_local_props_allowed_blocks', ['core/button']);
93
+ }
94
+
95
+ public function localizeToEditor()
96
+ {
97
+ $themeSlug = get_stylesheet();
98
+ wp_localize_script("{$themeSlug}-editor", 'iopLocalProps', [
99
+ 'addToBlocks' => $this->getAddToBlocks(),
100
+ ]);
101
+ }
102
+ }
@@ -0,0 +1,79 @@
1
+ // @ts-check
2
+
3
+ import { addFilter } from "@wordpress/hooks";
4
+ import { createHigherOrderComponent } from "@wordpress/compose";
5
+
6
+ /**
7
+ * Helper function to convert theme.json named colors to CSS variables.
8
+ * @param {string} color
9
+ */
10
+ const varWpColor = (color) => `var(--wp--preset--color--${color})`;
11
+
12
+ /** @type {string[]} */
13
+ let _blockNames = [];
14
+
15
+ const addCSSLocalPropsToBlock = createHigherOrderComponent((BlockListBlock) => {
16
+ return (props) => {
17
+ if (!_blockNames.includes(props.name)) {
18
+ return <BlockListBlock {...props} />;
19
+ }
20
+
21
+ const { attributes } = props;
22
+ const blockStyle = attributes.style || {};
23
+
24
+ const textColor = attributes.textColor
25
+ ? varWpColor(attributes.textColor)
26
+ : (blockStyle.color?.text ?? null);
27
+
28
+ const bgColor = attributes.backgroundColor
29
+ ? varWpColor(attributes.backgroundColor)
30
+ : (blockStyle.color?.background ?? null);
31
+
32
+ const borderColor = attributes.borderColor
33
+ ? varWpColor(attributes.borderColor)
34
+ : (blockStyle.border?.color ?? null);
35
+
36
+ const styleProps = {};
37
+ if (textColor) styleProps["--local-text-color"] = textColor;
38
+ if (bgColor) styleProps["--local-bg-color"] = bgColor;
39
+ if (borderColor) styleProps["--local-border-color"] = borderColor;
40
+
41
+ // Return early if no custom variables
42
+ if (!Object.keys(styleProps).length) {
43
+ return <BlockListBlock {...props} />;
44
+ }
45
+
46
+ // If any custom variables exist, inject them
47
+ const newProps = {
48
+ ...props,
49
+ wrapperProps: {
50
+ ...props.wrapperProps,
51
+ style: { ...props.wrapperProps?.style, ...styleProps },
52
+ },
53
+ };
54
+
55
+ console.log(
56
+ `Injecting local color variables: ${JSON.stringify(styleProps)} into ${props.name} block ${props.clientId}`,
57
+ );
58
+
59
+ return <BlockListBlock {...newProps} />;
60
+ };
61
+ }, "addCSSLocalPropsToBlock");
62
+
63
+ /**
64
+ * @param {string[]} [newBlockNames] Omit to use PHP-localized list (or `core/button`).
65
+ */
66
+ export function initCssLocalProps(newBlockNames) {
67
+ if (newBlockNames === undefined) {
68
+ const fromPhp =
69
+ /** @type {{ iopLocalProps?: { addToBlocks?: string[] } }} */ (globalThis)
70
+ .iopLocalProps?.addToBlocks;
71
+ newBlockNames = Array.isArray(fromPhp) ? fromPhp : ["core/button"];
72
+ }
73
+ _blockNames = newBlockNames;
74
+ addFilter(
75
+ "editor.BlockListBlock",
76
+ "iop/add-css-local-props-to-block",
77
+ addCSSLocalPropsToBlock,
78
+ );
79
+ }
package/README.md ADDED
@@ -0,0 +1,168 @@
1
+ # WordPress Theme Addons
2
+
3
+ #### Version 0.2.2
4
+
5
+ This repository contains JavaScript add-ons for the WordPress Block Editor. The project is currently private and under continual development.
6
+
7
+ ## What's in here
8
+
9
+ ### Block Variations
10
+
11
+ #### Linked Group Block
12
+
13
+ A variation on the Group block which adds standard Link controls. The link implementation uses ideas from [Accessible cards](https://kittygiraudel.com/2022/04/02/accessible-cards/) and [Inclusive Components: Cards](https://inclusive-components.design/cards/).
14
+
15
+ #### Related Posts Query
16
+
17
+ A variation on the Query Loop block which replaces the query with ranked related posts. Ranking lives in `lib/RelatedPosts` (`IdeasOnPurpose\WP\RelatedPosts`) — weighted shared taxonomies, post type, and recency, with optional REST at `GET /wp-json/ideasonpurpose/v1/related_posts/{id}`.
18
+
19
+ ### CSS Local Props
20
+
21
+ Injects block color attributes as CSS custom properties (`--local-text-color`, `--local-bg-color`, `--local-border-color`) so theme styles can use them.
22
+
23
+ This feature include a pair of front-end and block editor files:
24
+
25
+ | File | Runtime | Role |
26
+ | ---------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
+ | `CssLocalProps/CssLocalProps.php` | PHP (frontend + editor bootstrap) | On `render_block`, writes the local props onto the outer wrapper tag. On `enqueue_block_editor_assets`, localizes the allowed-block list to `window.iopLocalProps`. |
28
+ | `CssLocalProps/css-local-props.js` | Block editor | Higher-order component on `editor.BlockListBlock` that injects the same vars into `wrapperProps.style` for live editor preview. |
29
+
30
+ Named colors from theme.json are converted to `var(--wp--preset--color--*)`; custom hex/rgb values pass through as-is.
31
+
32
+ By default only `core/button` is targeted. Change the list from PHP:
33
+
34
+ ```php
35
+ add_filter('iop/add_css_local_props_allowed_blocks', fn() => ['core/button', 'core/group']);
36
+ ```
37
+
38
+ Both sides must stay in sync: enable PHP for frontend output and call `initCssLocalProps()` in the editor bundle so the canvas matches the saved markup.
39
+
40
+ ### Utilities
41
+
42
+ A few utility classes are exported. `usePublicPostTypes` and `usePublicTaxonomies` are direct lifts from the [WordPress Gutenberg source code](https://github.com/WordPress/gutenberg/blob/e90c88fee31120e0091e044c149f8b4f5f947f4a/packages/edit-site/src/components/add-new-template/utils.js#L91-L125). These functions are useful for pre-populating a WordPress data-store with all PostType and Taxonomy data for use in interfaces or block rendering.
43
+
44
+ ## Installation
45
+
46
+ ### Prerequisites
47
+
48
+ - SSH access to GitHub configured (your SSH key must be added to your GitHub account)
49
+ - You or the consuming project must have access to this private repository
50
+
51
+ ### npm
52
+
53
+ ```sh
54
+ npm install git+ssh://git@github.com:ideasonpurpose/wp-theme-addons.git
55
+ ```
56
+
57
+ Or in `package.json`:
58
+
59
+ ```json
60
+ {
61
+ "dependencies": {
62
+ "@ideasonpurpose/wp-theme-addons": "git+ssh://git@github.com:ideasonpurpose/wp-theme-addons.git"
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### Composer
68
+
69
+ Add the VCS repository and require the package in your project's `composer.json`:
70
+
71
+ ```json
72
+ {
73
+ "repositories": [
74
+ {
75
+ "type": "vcs",
76
+ "url": "git@github.com:ideasonpurpose/wp-theme-addons.git"
77
+ }
78
+ ],
79
+ "require": {
80
+ "ideasonpurpose/wp-theme-addons": "dev-main"
81
+ }
82
+ }
83
+ ```
84
+
85
+ ## Usage
86
+
87
+ ### JavaScript
88
+
89
+ Import one of the included packages into **editor.js** or whatever script loads in your editor:
90
+
91
+ ```javascript
92
+ // @link https://github.com/ideasonpurpose/wp-theme-addons
93
+ import { initLinkedGroupBlock, initCssLocalProps } from "@ideasonpurpose/wp-theme-addons";
94
+
95
+ // Instantiate the function
96
+ initLinkedGroupBlock();
97
+ initCssLocalProps();
98
+ ```
99
+
100
+ Also add the matching Sass frontend styles:
101
+
102
+ ```scss
103
+ // Import linked-group-front-end styles
104
+ // @link https://github.com/ideasonpurpose/wp-theme-addons
105
+ @use "@ideasonpurpose/wp-theme-addons/editor/block/variation/group-linked-group/linked-group-front-end";
106
+ ```
107
+
108
+ ### PHP
109
+
110
+ ```php
111
+ use IdeasOnPurpose\WP\RelatedPosts;
112
+ use IdeasOnPurpose\WP\Theme\Addons\Block\Variation\Group\LinkedGroup\LinkedGroup;
113
+ use IdeasOnPurpose\WP\Theme\Addons\Block\Variation\Query\RelatedPostsQuery\RelatedPostsQuery;
114
+ use IdeasOnPurpose\WP\Theme\Addons\CssLocalProps\CssLocalProps;
115
+
116
+ new LinkedGroup();
117
+ new RelatedPostsQuery(); // also loads RelatedPosts for ranking + REST
118
+ new CssLocalProps();
119
+
120
+ // Optional: use the ranker directly
121
+ // $posts = (new RelatedPosts())->get(['post' => $id, 'posts_per_page' => 4]);
122
+ ```
123
+
124
+ ## Coexistence
125
+
126
+ npm and Composer operate independently in the same repository:
127
+
128
+ | | npm | Composer |
129
+ | ----------------------- | --------------------------------- | -------------------------------- |
130
+ | **Config** | `package.json` | `composer.json` |
131
+ | **Package name** | `@ideasonpurpose/wp-theme-addons` | `ideasonpurpose/wp-theme-addons` |
132
+ | **Installs to** | `node_modules/` | `vendor/` |
133
+ | **Serves** | JS + SCSS | PHP |
134
+ | **Imports resolve via** | npm package name | PSR-4 autoloading |
135
+
136
+ No conflicts: separate config files, separate dependency directories, separate language ecosystems.
137
+
138
+ ```mermaid
139
+ graph TD
140
+ subgraph REPO["Single Git Repository: ideasonpurpose/wp-theme-addons"]
141
+ PJ[package.json]
142
+ CJ[composer.json]
143
+ JS[JS + SCSS files]
144
+ PHP[PHP files]
145
+ end
146
+
147
+ subgraph NPM_CONSUMER["npm Consumer Project"]
148
+ NPJ[package.json]
149
+ NM[node_modules/]
150
+ end
151
+
152
+ subgraph COMPOSER_CONSUMER["Composer Consumer Project"]
153
+ CPJ[composer.json]
154
+ VD[vendor/]
155
+ end
156
+
157
+ NPJ -- "npm install" --> PJ
158
+ PJ -- "resolves to" --> NM
159
+ JS -- "import from" --> NM
160
+
161
+ CPJ -- "composer require" --> CJ
162
+ CJ -- "resolves to" --> VD
163
+ PHP -- "PSR-4 autoload" --> VD
164
+ ```
165
+
166
+ - **npm** reads `package.json` → installs to `node_modules/` → JS/SCSS imports resolve via `@ideasonpurpose/wp-theme-addons`
167
+ - **Composer** reads `composer.json` → installs to `vendor/` → PHP classes autoload via PSR-4
168
+ - No conflicts: separate config files, separate dependency directories, separate language ecosystems.
@@ -0,0 +1,84 @@
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\Group\LinkedGroup;
9
+
10
+ class LinkedGroup
11
+ {
12
+ public $original_callback;
13
+
14
+ public $src_block_name = 'core/group';
15
+ public $variationNamespace = 'ideasonpurpose/group-linked';
16
+
17
+ public function __construct()
18
+ {
19
+ /**
20
+ * Callbacks are per block, and cannot be specific to a single variation
21
+ */
22
+ add_filter('register_block_type_args', [$this, 'wrap_render_callback'], 10, 2);
23
+ add_action('wp_enqueue_scripts', [$this, 'enqueue_styles']);
24
+ }
25
+
26
+ public function enqueue_styles()
27
+ {
28
+ $css_file = __DIR__ . '/linked-group.css';
29
+ $css_url = home_url(str_replace(ABSPATH, '', $css_file));
30
+ wp_enqueue_style('iop-linked-group', $css_url, [], filemtime($css_file));
31
+ }
32
+
33
+ public function wrap_render_callback($args, $block_type)
34
+ {
35
+ if ($block_type === $this->src_block_name) {
36
+ // Store existing callback
37
+ $this->original_callback = $args['render_callback'];
38
+ $args['render_callback'] = [$this, 'wrapped_render_callback'];
39
+ }
40
+ return $args;
41
+ }
42
+
43
+ public function wrapped_render_callback($attributes, $content, $block)
44
+ {
45
+ global $post;
46
+
47
+ if (($attributes['namespace'] ?? null) !== $this->variationNamespace) {
48
+ return $content;
49
+ }
50
+
51
+ // Ensure the wrapper has the correct namespace
52
+ $tags = new \WP_HTML_Tag_Processor($content);
53
+ if ($tags->next_tag()) {
54
+ $tags->add_class('iop-linked-group');
55
+ }
56
+ $blockHTML = $tags->get_updated_html();
57
+
58
+ if (!isset($attributes['linkToSelf']) && !isset($attributes['url'])) {
59
+ return $blockHTML;
60
+ }
61
+
62
+ $href =
63
+ isset($attributes['linkToSelf']) && $attributes['linkToSelf']
64
+ ? get_permalink($post)
65
+ : $attributes['url'];
66
+
67
+ $target = isset($attributes['linkTarget'])
68
+ ? ' target="' . esc_attr($attributes['linkTarget']) . '"'
69
+ : '';
70
+
71
+ $rel = isset($attributes['rel']) ? ' rel="' . esc_attr($attributes['rel']) . '"' : '';
72
+
73
+ $linkHTML = sprintf(
74
+ '<a href="%s" class="iop-linked-group__link"%s%s></a>',
75
+ esc_attr($href),
76
+ $target,
77
+ $rel,
78
+ );
79
+
80
+ $blockHTML = preg_replace('/<\/div>$/', $linkHTML . '</div>', $blockHTML);
81
+
82
+ return $blockHTML;
83
+ }
84
+ }
@@ -0,0 +1,22 @@
1
+ .iop-linked-group {
2
+ position: relative;
3
+ }
4
+
5
+ .iop-linked-group a.iop-linked-group__link {
6
+ position: absolute;
7
+ top: 0;
8
+ left: 0;
9
+ z-index: 10;
10
+
11
+ width: 100%;
12
+ max-width: 100%;
13
+ height: 100%;
14
+ margin: 0;
15
+ }
16
+
17
+ /* every clickable element in the group needs to be position:relative */
18
+ .iop-linked-group button,
19
+ .iop-linked-group a:not(.iop-linked-group__link) {
20
+ position: relative;
21
+ z-index: 20;
22
+ }