Jake Vanderwerf
3 hours ago 56a9a1ccf764ff7a6af8f8a2292cb07443cb4aa7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<?php
namespace JVBase\forms;
 
use JVBase\registrar\Registrar;
use WP_Term;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
 
/**
 * Taxonomy Selector
 *
 * @package TaxonomySelector
 * @version 2.0.0
 */
 
class TaxonomySelector {
    /**
     * Track if any taxonomy selectors are present on the page
     */
 
    protected string $id;
    protected string $name;
    protected string $singular;
    protected string $plural;
    protected string $taxonomy;
    protected string $base;
    protected string $title;
    protected array $config;
    protected Registrar $registrar;
 
    public function __construct(string $id, string $taxonomy, array $config = []) {
        $this->id = sanitize_key($id);
        $this->taxonomy = jvbCheckBase($taxonomy);
        $this->name = jvbNoBase($taxonomy);
 
        $registrar = Registrar::getInstance($this->name);
        if ($registrar) {
            $this->registrar = $registrar;
        }
 
        $this->title = $registrar->getPlural();
        $this->base = $config['base']??'';
        $this->config = wp_parse_args($config, [
            'types'     => false, // for feed block implementation
            'max'       => 0,      // 0 = unlimited
            'search'    => true,
            'label'     => $this->name,
            'icon'      => false,
            'autocomplete'  => false,
            'createNew' => false,
            'required'  => false,
            'hidden'    => false,
            'base'      => '',
            'name'      => $this->taxonomy,
            'update'    => true,   // Whether to update on close
        ]);
 
 
        $this->plural = $registrar->getPlural();
        $this->singular = $registrar->getSingular();
    }
 
 
    /**
     * Get the full path for a term (for hierarchical taxonomies)
     *
     * @param WP_Term $term The term object
     * @param bool $returnArray if true, returns the array. If false, a string of terms separated by ' → '
     * @return string|array An array of terms or the full term path
     */
    public static function getTermPath(WP_Term $term, bool $returnArray = false): string|array {
        if (!is_taxonomy_hierarchical($term->taxonomy)) {
            return html_entity_decode($term->name);
        }
 
        $path = [];
        $currentTerm = $term;
 
        while ($currentTerm) {
            array_unshift($path, html_entity_decode($currentTerm->name));
 
            if ($currentTerm->parent) {
                $currentTerm = get_term($currentTerm->parent);
                if (is_wp_error($currentTerm)) {
                    break;
                }
            } else {
                break;
            }
        }
        return ($returnArray) ? $path : implode(' → ', $path);
    }
 
 
    /**
     * Get the single modal HTML structure
     */
    public static function outputSelectorModal(): string {
        ob_start();
        ?>
        <dialog id="jvb-selector" aria-labelledby="modal-title" aria-modal="true">
            <div class="wrap col">
                <header class="row">
                    <h3 id="modal-title">Select Taxonomy</h3>
                </header>
 
 
                <div class="selected-items row" role="region" aria-label="Selected items"></div>
 
                <div class="items-wrap">
                    <!-- Common/Favorite terms section -->
                    <details class="favourite-terms" hidden>
                        <summary class="title row x-btw">Your Go Tos:</summary>
                        <ul class="favourite-list row x-btw"></ul>
                    </details>
 
                    <!-- Pagination info -->
                    <p class="pagination-info" hidden></p>
 
                    <!-- Navigation breadcrumbs -->
                    <nav class="term-navigation row" aria-label="Term navigation">
                        <button type="button" class="back-to-parent" hidden>
                            <span aria-hidden="true">←</span> Back
                        </button>
                    </nav>
 
 
                    <p class="message" hidden aria-live="polite">
                        { <span>loading items</span> }
                    </p>
                    <!-- Terms list -->
                    <ul class="items-container col top" role="listbox" aria-label="Available terms">
                        <!-- Terms will be populated here -->
                    </ul>
 
                    <button class="submit-term" hidden data-ignore><strong>Create: </strong> "<span></span>"</button>
 
                    <!-- Infinite scroll sentinel -->
                    <div class="scroll-sentinel" aria-hidden="true"></div>
                </div>
 
                <!-- Search section -->
                <div class="search-wrapper">
                    <div class="search-bar">
                        <?= str_replace('class="search-container', 'class="open search-container', jvbSearch('Search terms', 'search-terms')) ?>
                    </div>
                </div>
 
                <!-- Create new term section -->
                <details class="create-term" hidden>
                    <summary class="row x-btw">Add New Term</summary>
                    <div class="create-new-term-section">
                        <form class="create-term" data-nocache data-form-id="create-term" data-save="terms">
                            <div class="form-group">
                                <label for="term_name">Term Name:</label>
                                <input type="text" name="term_name" id="term_name" required>
                            </div>
 
                            <div class="form-group">
                                <label for="select_parent">Nest it under:</label>
                                <select name="parent" id="select_parent">
                                    <option value="0">None (Top Level)</option>
                                </select>
                            </div>
                        </form>
 
                    </div>
                </details>
                <?= jvbModalActions(); ?>
            </div>
        </dialog>
        <template class="loadingItems">
            <p>{ <span>loading items</span> }</p>
        </template>
        <template class="autocompleteItem">
            <li class="autocomplete item btn"></li>
        </template>
        <template class="noTermResults">
            <p>{ <span>nothing found</span> }</p>
        </template>
        <template class="termListItem">
            <li>
                <input type="checkbox">
                <label>
                    <span class="term-name"></span>
                </label>
            </li>
        </template>
        <template class="termChildrenToggle">
            <button type="button" class="toggle-children" aria-expanded="false">
                <?=jvbIcon('plus-square')?>
            </button>
        </template>
        <template class="selectedTerm">
            <div class="selected-item row">
                <span class="item-name"></span>
                <button type="button" class="remove-term"><?=jvbIcon('x')?></button>
            </div>
        </template>
        <template class="termBreadcrumb">
            <button type="button" class="path-level"></button>
        </template>
        <?php
        return ob_get_clean();
    }
 
    /**
     * Render the taxonomy selector toggle and display
     *
     * @param array $selected Array of term IDs that are already selected
     * @param string $extra Additional HTML to append (optional)
     * @return string The rendered HTML
     */
    public function render(array $selected = [], string $extra = ''): string {
 
        if (array_key_exists('output', $this->config) && $this->config['output'] === 'minimal') {
            return $this->renderTaxonomyToggle($selected, $extra);
        }
        // Build data attributes
        $dataAttrs = $this->buildDataAttributes($selected);
 
        $hasAutocomplete = ($this->config['autocomplete']) ? ' data-autocomplete' : '';
 
        // Hidden attribute
        $hidden = $this->config['hidden'] ? ' hidden' : '';
 
        ob_start();
        ?>
        <div class="jvb-selector <?= esc_attr($this->name) ?>"
             id="<?= esc_attr($this->id) ?>"<?= $hidden ?>>
            <div class="field-group-header row x-btw">
                <label for="<?= $this->base ?><?= esc_attr($this->config['name']) ?>-autocomplete">
                    <?= ($this->config['icon']) ? jvbIcon($this->config['icon']) : '' ?>
                    <span><?= $this->config['label'] ?></span>
                </label>
                <button type="button"
                    class="filter-toggle row taxonomy-toggle"
                    data-taxonomy="<?= esc_attr($this->name) ?>"
                    data-single="<?= esc_attr($this->singular) ?>"
                    data-plural="<?= esc_attr($this->plural) ?>"
                    <?= $dataAttrs ?>
                    <?= $hasAutocomplete ?>
                    title="Open <?= $this->singular ?> Selector"
                    aria-label="Select <?= esc_attr($this->plural) ?>">
                    <?= jvbIcon('plus-square') ?>
                </button>
                <?php if ($hasAutocomplete !== '') { ?>
                    <input type="text" id="<?= $this->base ?><?= esc_attr($this->config['name']) ?>-autocomplete" autocomplete="off" data-ignore data-autocomplete>
                    <p class="message" hidden aria-live="polite">
                        { <span>loading items</span> }
                    </p>
                    <div class="auto-wrapper" hidden>
                        <ul class="search-results">
                        </ul>
                        <button class="submit-term" hidden data-ignore><strong>Create: </strong> "<span></span>"</button>
                    </div>
 
                <?php } ?>
            </div>
            <?php
            $selectedItems = '';
            if (!empty($selected)):
                ob_start();
                foreach ($selected as $termId):
                    $this->renderSelectedTerm($termId);
                endforeach;
                $selectedItems = ob_get_clean();
            endif;
            ?>
            <div class="selected-items row left" role="region" aria-label="Selected <?= esc_attr($this->plural) ?>"><?=$selectedItems?></div>
            <?= $extra ?>
        </div>
        <?php
        return ob_get_clean();
    }
 
    protected function renderTaxonomyToggle(array $selected = [], string $extra = ''): string
    {
 
        return sprintf(
            '<button type="button" data-icon="%s" data-filter="taxonomy" data-taxonomy="%s" data-type="selector" data-single="%s" data-plural="%s" %stitle="Filter by %s">%s<span class="label">%s</span></button>',
            $this->registrar->getIcon(),
            $this->name,
            $this->singular,
            $this->plural,
            $this->buildDataAttributes([]),
            $this->singular,
            jvbIcon($this->registrar->getIcon()),
            $this->singular
        );
    }
 
    /**
     * Build data attributes string for the toggle button
     */
    private function buildDataAttributes(array $selected): string {
        $attrs = [];
 
        // Update behavior
        if (!$this->config['update']) {
            $attrs[] = 'data-update="false"';
        }
 
        // Max selection
        if ($this->config['max'] > 0) {
            $attrs[] = 'data-max="' . esc_attr($this->config['max']) . '"';
        }
 
        // Search capability
        if ($this->config['search']) {
            $attrs[] = 'data-search';
        }
 
        // Create new capability
        if ($this->config['createNew']) {
            $attrs[] = 'data-creatable';
        }
 
        // Required
        if ($this->config['required']) {
            $attrs[] = 'data-required';
        }
 
        // Post types filter (for feed blocks)
        if ($this->config['types'] && is_array($this->config['types'])) {
            $attrs[] = 'data-for="' . esc_attr(implode(',', $this->config['types'])) . '"';
        }
 
        // Selected items
        if (!empty($selected)) {
            $attrs[] = 'data-selected="' . esc_attr(implode(',', $selected)) . '"';
        }
 
        return implode(' ', $attrs);
    }
 
    /**
     * Render a single selected term
     */
    private function renderSelectedTerm(int $termId): void {
        $term = get_term($termId, $this->taxonomy);
 
        if (!$term || is_wp_error($term)) {
            return;
        }
 
        $termPath = self::getTermPath($term);
        ?>
        <div class="selected-item row" data-id="<?= esc_attr($termId) ?>">
            <span><?= esc_html($termPath) ?></span>
            <button type="button"
                    class="remove-term row"
                    aria-label="Remove <?= html_entity_decode($term->name) ?>">
                <?= jvbIcon('x') ?>
            </button>
        </div>
        <?php
    }
}