-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtocflow.php
More file actions
203 lines (178 loc) · 5.39 KB
/
Copy pathtocflow.php
File metadata and controls
203 lines (178 loc) · 5.39 KB
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
<?php
/**
* Plugin Name: TOCflow
* Plugin URI: https://github.com/matthummel-pa/tocflow
* Description: A lightweight Table of Contents block that auto-generates a linked outline from your post headings. Developed by <a href="https://matthummel.com">Matt Hummel</a>.
* Version: 0.1.0
* Requires at least: 6.4
* Requires PHP: 7.4
* Author: Matt Hummel
* Author URI: https://matthummel.com
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: tocflow
*
* @package TOCflow
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Register the block using the metadata in build/block.json.
*/
function tocflow_block_init() {
register_block_type( __DIR__ . '/build' );
}
add_action( 'init', 'tocflow_block_init' );
/**
* Create a URL-safe, unique anchor slug from heading text.
*
* @param string $text Heading text.
* @param array $used Slugs already used on this page (passed by reference for dedup).
* @return string
*/
function tocflow_make_slug( $text, &$used ) {
$slug = sanitize_title( $text );
if ( '' === $slug ) {
$slug = 'section';
}
$base = $slug;
$index = 2;
while ( isset( $used[ $slug ] ) ) {
$slug = $base . '-' . $index;
$index++;
}
$used[ $slug ] = true;
return $slug;
}
/**
* Recursively walk parsed blocks and collect heading data in document order.
*
* @param array $blocks Parsed blocks from parse_blocks().
* @param array $used Used slugs (by reference) for dedup.
* @param array $collected Growing list of headings (by reference).
*/
function tocflow_collect_headings( $blocks, &$used, &$collected ) {
foreach ( $blocks as $block ) {
if ( 'core/heading' === $block['blockName'] ) {
$html = isset( $block['innerHTML'] ) ? $block['innerHTML'] : '';
$text = trim( wp_strip_all_tags( $html ) );
$level = 2; // Core headings default to H2.
if ( isset( $block['attrs']['level'] ) ) {
$level = (int) $block['attrs']['level'];
} elseif ( preg_match( '/<h([1-6])/i', $html, $m ) ) {
$level = (int) $m[1];
}
if ( '' !== $text ) {
$collected[] = array(
'level' => $level,
'text' => $text,
'slug' => tocflow_make_slug( $text, $used ),
);
}
}
if ( ! empty( $block['innerBlocks'] ) ) {
tocflow_collect_headings( $block['innerBlocks'], $used, $collected );
}
}
}
/**
* Get the full, slug-stamped heading map for a post.
*
* This is the single source of truth: the TOC list and the IDs injected into
* the post's headings both derive from this, so the anchor links always match.
*
* @param int $post_id Post ID.
* @return array
*/
function tocflow_get_all_headings( $post_id ) {
static $cache = array();
if ( isset( $cache[ $post_id ] ) ) {
return $cache[ $post_id ];
}
$post = get_post( $post_id );
$used = array();
$collected = array();
if ( $post ) {
tocflow_collect_headings( parse_blocks( $post->post_content ), $used, $collected );
}
$cache[ $post_id ] = $collected;
return $collected;
}
/**
* Render nested list markup from heading data.
*
* Levels are expected to be normalized to sequential depths (1, 2, 3...).
*
* @param array $headings Heading data with normalized 'level'.
* @param string $list_tag 'ol' or 'ul'.
* @return string
*/
function tocflow_render_list( $headings, $list_tag ) {
if ( empty( $headings ) ) {
return '';
}
$html = '';
$prev = 0; // Forces the first item to open one list.
$open = 0; // Count of currently open lists.
foreach ( $headings as $heading ) {
$level = (int) $heading['level'];
if ( $level > $prev ) {
for ( $i = 0; $i < ( $level - $prev ); $i++ ) {
$class = 0 === $open ? '' : ' class="tocflow__sub"';
$html .= '<' . $list_tag . $class . '>';
$open++;
}
} else {
$html .= '</li>';
if ( $level < $prev ) {
for ( $i = 0; $i < ( $prev - $level ); $i++ ) {
$html .= '</' . $list_tag . '></li>';
$open--;
}
}
}
$html .= '<li><a href="#' . esc_attr( $heading['slug'] ) . '">' . esc_html( $heading['text'] ) . '</a>';
$prev = $level;
}
$html .= '</li>';
for ( $i = 0; $i < $open; $i++ ) {
$html .= '</' . $list_tag . '>';
if ( $i < $open - 1 ) {
$html .= '</li>';
}
}
return $html;
}
/**
* Inject matching anchor IDs into core/heading blocks on the front end so the
* TOC links have a target to scroll to.
*
* @param string $block_content Rendered block HTML.
* @param array $block Parsed block.
* @return string
*/
function tocflow_add_heading_ids( $block_content, $block ) {
if ( is_admin() || ! is_singular() || empty( $block['blockName'] ) || 'core/heading' !== $block['blockName'] ) {
return $block_content;
}
$post_id = get_the_ID();
if ( ! $post_id ) {
return $block_content;
}
$headings = tocflow_get_all_headings( $post_id );
// Walk through headings in document order as each one renders.
static $pointers = array();
$pointer = isset( $pointers[ $post_id ] ) ? $pointers[ $post_id ] : 0;
if ( ! isset( $headings[ $pointer ] ) ) {
return $block_content;
}
$pointers[ $post_id ] = $pointer + 1;
// Respect an author-supplied id if one already exists.
if ( preg_match( '/<h[1-6][^>]*\sid=/i', $block_content ) ) {
return $block_content;
}
$slug = $headings[ $pointer ]['slug'];
return preg_replace( '/(<h[1-6])(\s|>)/i', '$1 id="' . esc_attr( $slug ) . '"$2', $block_content, 1 );
}
add_filter( 'render_block', 'tocflow_add_heading_ids', 10, 2 );