Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
91.01% |
81 / 89 |
|
62.50% |
5 / 8 |
CRAP | |
0.00% |
0 / 1 |
| Conditional_Logic_Container | |
91.01% |
81 / 89 |
|
62.50% |
5 / 8 |
36.94 | |
0.00% |
0 / 1 |
| init | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
12 | |||
| next_id | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| add_container_attributes | |
89.47% |
17 / 19 |
|
0.00% |
0 / 1 |
7.06 | |||
| encode_logic | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| decode_logic | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| harvest | |
95.74% |
45 / 47 |
|
0.00% |
0 / 1 |
13 | |||
| drop_ambiguous_ids | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
4 | |||
| apply_containment | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Conditional logic for container blocks inside a form. |
| 4 | * |
| 5 | * A field carries its conditions through the `[contact-field]` shortcode and arrives here as a |
| 6 | * Contact_Form_Field. A container has no shortcode and is not a field: `core/group` renders to |
| 7 | * plain block markup that merely surrounds the field shortcodes. So its conditions travel a |
| 8 | * different route — stamped onto the rendered element as a data attribute, then harvested off |
| 9 | * the assembled form body, which is the first moment both the container and the fields it |
| 10 | * holds exist in one place. |
| 11 | * |
| 12 | * Harvesting from the body rather than a static registry is deliberate: a page can carry |
| 13 | * several forms, each parsed immediately after its own inner blocks render, and a shared |
| 14 | * registry would need resetting between them. The body is already scoped to one form. |
| 15 | * |
| 16 | * Targets PHP 7.4: no typed class constants, no match expressions. |
| 17 | * |
| 18 | * @package automattic/jetpack-forms |
| 19 | */ |
| 20 | |
| 21 | namespace Automattic\Jetpack\Forms\ContactForm; |
| 22 | |
| 23 | use Automattic\Jetpack\Forms\Jetpack_Forms; |
| 24 | |
| 25 | /** |
| 26 | * Renders and harvests conditional logic on container blocks. |
| 27 | */ |
| 28 | class Conditional_Logic_Container { |
| 29 | |
| 30 | /** |
| 31 | * Blocks that can be shown or hidden as a unit. |
| 32 | * |
| 33 | * Mirrors CONTAINER_BLOCK_NAMES in |
| 34 | * src/blocks/shared/conditional-logic/util/container-blocks.js. `core/row` and `core/stack` |
| 35 | * are variations of `core/group` rather than blocks of their own, so one name covers all |
| 36 | * three. |
| 37 | * |
| 38 | * @var array |
| 39 | */ |
| 40 | const SUPPORTED_BLOCKS = array( 'core/group' ); |
| 41 | |
| 42 | /** |
| 43 | * Attribute the rendered container carries its conditions in. |
| 44 | * |
| 45 | * Removed again once the form has read it: the form emits the whole logic map for the |
| 46 | * interactivity store anyway, so leaving this on the element would ship the same JSON |
| 47 | * twice. |
| 48 | * |
| 49 | * @var string |
| 50 | */ |
| 51 | const LOGIC_ATTRIBUTE = 'data-jp-container-logic'; |
| 52 | |
| 53 | /** |
| 54 | * Prefix for generated container ids. |
| 55 | * |
| 56 | * Prefixed so a container id can never collide with a field id, which is derived from a |
| 57 | * field's label and may be anything a label can slugify to. |
| 58 | * |
| 59 | * @var string |
| 60 | */ |
| 61 | const ID_PREFIX = 'jp-container-'; |
| 62 | |
| 63 | /** |
| 64 | * Per-request counter behind the generated ids. |
| 65 | * |
| 66 | * @var int |
| 67 | */ |
| 68 | private static $sequence = 0; |
| 69 | |
| 70 | /** |
| 71 | * Register the render filter. |
| 72 | * |
| 73 | * @return void |
| 74 | */ |
| 75 | public static function init() { |
| 76 | // Nothing to stamp while the feature is off, and `core/group` is everywhere in a block |
| 77 | // theme -- headers, footers, template parts, patterns. Not registering at all costs a |
| 78 | // site with the feature off nothing per group per render. |
| 79 | if ( ! Jetpack_Forms::is_conditional_logic_enabled() ) { |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | foreach ( self::SUPPORTED_BLOCKS as $block_name ) { |
| 84 | add_filter( 'render_block_' . $block_name, array( __CLASS__, 'add_container_attributes' ), 10, 2 ); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Generate the next container id. |
| 90 | * |
| 91 | * @return string A form-unique id. |
| 92 | */ |
| 93 | private static function next_id() { |
| 94 | ++self::$sequence; |
| 95 | |
| 96 | return self::ID_PREFIX . self::$sequence; |
| 97 | } |
| 98 | |
| 99 | /** |
| 100 | * Stamp a container that carries conditions with everything the runtime needs. |
| 101 | * |
| 102 | * Runs for every `core/group` on the page, including the great majority that sit outside |
| 103 | * any form and carry no conditions; those return untouched on an array read, before the |
| 104 | * feature-flag lookup and before any parsing. |
| 105 | * |
| 106 | * The element is given the same visibility contract a field wrapper gets — the same root |
| 107 | * attribute, the same class binding, the same `data-jp-conditional` marker that scopes the |
| 108 | * transition — so the container hides through the code path that already hides fields |
| 109 | * rather than a second one that could disagree with it. |
| 110 | * |
| 111 | * @param string $block_content The block's rendered HTML. |
| 112 | * @param array $block The parsed block. |
| 113 | * |
| 114 | * @return string The HTML, stamped when the block carries conditions. |
| 115 | */ |
| 116 | public static function add_container_attributes( $block_content, $block ) { |
| 117 | // Cheapest test first: an array read on the block that is already in hand. The |
| 118 | // overwhelming majority of groups carry no conditions and leave here, before the |
| 119 | // feature-flag lookup and before any parsing. |
| 120 | $logic = $block['attrs']['conditionalLogic'] ?? null; |
| 121 | |
| 122 | // `enabled` is derived in the editor from whether any rule exists, so a container the |
| 123 | // author opened the panel on but wrote no conditions in adds nothing to the page. |
| 124 | if ( ! is_array( $logic ) || empty( $logic['enabled'] ) ) { |
| 125 | return $block_content; |
| 126 | } |
| 127 | |
| 128 | // Re-checked here as well as in init(): the filter is registered once per request, but |
| 129 | // the flag is filterable and a caller may change it in between. |
| 130 | if ( ! Jetpack_Forms::is_conditional_logic_enabled() ) { |
| 131 | return $block_content; |
| 132 | } |
| 133 | |
| 134 | if ( ! is_string( $block_content ) || '' === trim( $block_content ) ) { |
| 135 | return $block_content; |
| 136 | } |
| 137 | |
| 138 | $processor = new \WP_HTML_Tag_Processor( $block_content ); |
| 139 | |
| 140 | if ( ! $processor->next_tag() ) { |
| 141 | return $block_content; |
| 142 | } |
| 143 | |
| 144 | $container_id = self::next_id(); |
| 145 | |
| 146 | $processor->set_attribute( 'data-jp-visibility-root', $container_id ); |
| 147 | $processor->set_attribute( 'data-jp-conditional', '1' ); |
| 148 | $processor->set_attribute( self::LOGIC_ATTRIBUTE, self::encode_logic( $logic ) ); |
| 149 | $processor->set_attribute( 'data-wp-interactive', 'jetpack/form' ); |
| 150 | // `fieldId` rather than a key of its own, so `state.isFieldHidden` resolves the |
| 151 | // container through the same getter it uses for a field. Every field inside sets its |
| 152 | // own `fieldId`, so inheriting this one shadows nothing. |
| 153 | $processor->set_attribute( 'data-wp-context', wp_json_encode( array( 'fieldId' => $container_id ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) ); |
| 154 | $processor->set_attribute( 'data-wp-class--jetpack-field--conditionally-hidden', 'state.isFieldHidden' ); |
| 155 | |
| 156 | /* |
| 157 | * The same watch a field wrapper carries. A group can hold focusable content that is |
| 158 | * not a field -- a link, a button, a nested block -- and that content has no wrapper of |
| 159 | * its own to restore focus from, so without this the caret falls to <body> when the |
| 160 | * group hides under the visitor. |
| 161 | */ |
| 162 | $processor->set_attribute( 'data-wp-watch--conditional-focus', 'callbacks.manageConditionalFocus' ); |
| 163 | |
| 164 | return $processor->get_updated_html(); |
| 165 | } |
| 166 | |
| 167 | /** |
| 168 | * Encode a container's conditions for the attribute they travel in. |
| 169 | * |
| 170 | * A rule value is author-supplied text, and the rules are a JSON array, so the payload |
| 171 | * always contains `[` and `]`. Contact_Form runs the whole assembled body through |
| 172 | * do_shortcode() to find its fields, and do_shortcode() does not care that the brackets |
| 173 | * sit inside an HTML attribute: a value that merely looks like a shortcode is expanded |
| 174 | * there, which shatters the tag it sits in, mints a field nobody wrote, and leaves the |
| 175 | * container unreadable so its conditions are silently dropped. |
| 176 | * |
| 177 | * Numeric entities survive do_shortcode() untouched and are turned back by decode_logic(). |
| 178 | * The field path guards the same payload the same way, in Contact_Form_Plugin. |
| 179 | * |
| 180 | * @param array $logic The conditions. |
| 181 | * |
| 182 | * @return string The attribute value. |
| 183 | */ |
| 184 | private static function encode_logic( array $logic ) { |
| 185 | $json = wp_json_encode( $logic, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); |
| 186 | |
| 187 | return str_replace( array( '[', ']' ), array( '[', ']' ), (string) $json ); |
| 188 | } |
| 189 | |
| 190 | /** |
| 191 | * Read conditions back out of the attribute encode_logic() wrote. |
| 192 | * |
| 193 | * @param string $encoded The attribute value. |
| 194 | * |
| 195 | * @return array|null The conditions, or null when the value is not readable. |
| 196 | */ |
| 197 | private static function decode_logic( $encoded ) { |
| 198 | $decoded = json_decode( html_entity_decode( $encoded, ENT_COMPAT ), true ); |
| 199 | |
| 200 | return is_array( $decoded ) ? $decoded : null; |
| 201 | } |
| 202 | |
| 203 | /** |
| 204 | * Read container conditions off an assembled form body. |
| 205 | * |
| 206 | * Returns the containers' logic keyed by id, and which field ids each one encloses. The |
| 207 | * containment is what lets validation treat a required field inside a hidden container as |
| 208 | * one the visitor was never shown; without it the form would refuse to submit and say |
| 209 | * nothing about why. |
| 210 | * |
| 211 | * Nesting comes from WP_HTML_Processor, which parses to the HTML5 spec and reports the |
| 212 | * depth of the element it is on. The tag processor offers no ancestry, so the first version |
| 213 | * of this counted `div` depth by hand -- which missed a group rendered as any of the other |
| 214 | * elements core/group offers, and mis-scoped containment whenever a block inside the group |
| 215 | * emitted unbalanced markup. |
| 216 | * |
| 217 | * Failure is open by design. If the body cannot be parsed, nothing is harvested: every |
| 218 | * container renders visible and every field it holds stays enforced. That is the safe |
| 219 | * direction -- a required field that refuses to hide is a support ticket, while a field |
| 220 | * wrongly attributed to a hidden container has its answer silently discarded. |
| 221 | * |
| 222 | * @param string $body The form body HTML. |
| 223 | * |
| 224 | * @return array `array( 'logic' => array, 'contains' => array, 'body' => string )`. |
| 225 | */ |
| 226 | public static function harvest( $body ) { |
| 227 | $empty = array( |
| 228 | 'logic' => array(), |
| 229 | 'contains' => array(), |
| 230 | 'body' => $body, |
| 231 | ); |
| 232 | |
| 233 | if ( ! is_string( $body ) || false === strpos( $body, self::LOGIC_ATTRIBUTE ) ) { |
| 234 | return $empty; |
| 235 | } |
| 236 | |
| 237 | $processor = \WP_HTML_Processor::create_fragment( $body ); |
| 238 | |
| 239 | if ( null === $processor ) { |
| 240 | return $empty; |
| 241 | } |
| 242 | |
| 243 | $logic = array(); |
| 244 | $contains = array(); |
| 245 | $open = array(); |
| 246 | $root_counts = array(); |
| 247 | |
| 248 | while ( $processor->next_tag() ) { |
| 249 | $depth = $processor->get_current_depth(); |
| 250 | |
| 251 | // Anything opened at or above this depth is a container we have now left. |
| 252 | $last = end( $open ); |
| 253 | while ( false !== $last && $last['depth'] >= $depth ) { |
| 254 | array_pop( $open ); |
| 255 | $last = end( $open ); |
| 256 | } |
| 257 | |
| 258 | $root = $processor->get_attribute( 'data-jp-visibility-root' ); |
| 259 | |
| 260 | if ( ! is_string( $root ) ) { |
| 261 | continue; |
| 262 | } |
| 263 | |
| 264 | $root_counts[ $root ] = ( $root_counts[ $root ] ?? 0 ) + 1; |
| 265 | |
| 266 | $encoded_logic = $processor->get_attribute( self::LOGIC_ATTRIBUTE ); |
| 267 | |
| 268 | if ( ! is_string( $encoded_logic ) ) { |
| 269 | // A field wrapper. Attribute it to every container currently open around it, so |
| 270 | // a field inside nested containers is governed by all of them. |
| 271 | foreach ( $open as $entry ) { |
| 272 | $contains[ $entry['id'] ][] = $root; |
| 273 | } |
| 274 | |
| 275 | continue; |
| 276 | } |
| 277 | |
| 278 | $decoded = self::decode_logic( $encoded_logic ); |
| 279 | |
| 280 | if ( null !== $decoded ) { |
| 281 | // A nested container is governed by its ancestors exactly as a field is, so it |
| 282 | // is attributed to them before it starts governing anything itself. Without |
| 283 | // this the visibility map reports an inner container visible while its parent |
| 284 | // is hidden -- masked today only because the CSS hides it through the ancestor, |
| 285 | // and wrong for anything that reads the map rather than the DOM. |
| 286 | foreach ( $open as $entry ) { |
| 287 | $contains[ $entry['id'] ][] = $root; |
| 288 | } |
| 289 | |
| 290 | $logic[ $root ] = $decoded; |
| 291 | $contains[ $root ] = array(); |
| 292 | |
| 293 | $open[] = array( |
| 294 | 'id' => $root, |
| 295 | 'depth' => $depth, |
| 296 | ); |
| 297 | } |
| 298 | |
| 299 | /* |
| 300 | * Removed whether or not it decoded. The form emits the whole map for the |
| 301 | * interactivity store, so a readable copy on the element is waste; an unreadable |
| 302 | * one is waste that also ships broken JSON to every visitor. |
| 303 | */ |
| 304 | $processor->remove_attribute( self::LOGIC_ATTRIBUTE ); |
| 305 | } |
| 306 | |
| 307 | if ( null !== $processor->get_last_error() ) { |
| 308 | return $empty; |
| 309 | } |
| 310 | |
| 311 | /* |
| 312 | * The updated body even when nothing was harvested, so a payload that could not be |
| 313 | * decoded is still stripped rather than shipped. |
| 314 | */ |
| 315 | return array( |
| 316 | 'logic' => $logic, |
| 317 | 'contains' => self::drop_ambiguous_ids( $contains, $root_counts ), |
| 318 | 'body' => $processor->get_updated_html(), |
| 319 | ); |
| 320 | } |
| 321 | |
| 322 | /** |
| 323 | * Drop ids that more than one element claims from every containment list. |
| 324 | * |
| 325 | * A field id is derived from its label at render time, so two fields in one form can end |
| 326 | * up sharing one -- "Name" inside a conditional group and "Name" outside it both derive |
| 327 | * `name`. Containment keys on that id, so hiding the container would hide, and then |
| 328 | * discard the answer to, every field sharing it -- including the one still on screen. |
| 329 | * `apply_initial_field_visibility()` stamps by the same id, so it would hide both too. |
| 330 | * |
| 331 | * Ambiguity is resolved by not acting: the container still hides, but it stops claiming an |
| 332 | * id it cannot prove belongs to it. Losing a hide is visible and recoverable; discarding an |
| 333 | * answer the visitor typed is neither. |
| 334 | * |
| 335 | * The editor's duplicate-id notice is where this gets fixed properly. This is the runtime |
| 336 | * declining to do damage in the meantime. |
| 337 | * |
| 338 | * @param array $contains Map of container id to the ids it encloses. |
| 339 | * @param array $root_counts Map of id to how many elements carried it. |
| 340 | * |
| 341 | * @return array The containment map, with ambiguous ids removed. |
| 342 | */ |
| 343 | private static function drop_ambiguous_ids( array $contains, array $root_counts ) { |
| 344 | foreach ( $contains as $container_id => $ids ) { |
| 345 | $unambiguous = array(); |
| 346 | |
| 347 | foreach ( $ids as $id ) { |
| 348 | if ( 1 === ( $root_counts[ $id ] ?? 0 ) ) { |
| 349 | $unambiguous[] = $id; |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | $contains[ $container_id ] = $unambiguous; |
| 354 | } |
| 355 | |
| 356 | return $contains; |
| 357 | } |
| 358 | |
| 359 | /** |
| 360 | * Hide every field enclosed by a hidden container. |
| 361 | * |
| 362 | * A separate pass after the evaluator rather than part of it: containment is not a |
| 363 | * condition, it is a consequence. A field inside a hidden container is hidden whatever its |
| 364 | * own rules say, and a container's own visibility is settled by the evaluator before this |
| 365 | * runs. |
| 366 | * |
| 367 | * @param array $visibility Map of id to bool, as resolved by Conditional_Logic. |
| 368 | * @param array $contains Map of container id to the field ids it encloses. |
| 369 | * |
| 370 | * @return array The visibility map, with enclosed fields hidden. |
| 371 | */ |
| 372 | public static function apply_containment( array $visibility, array $contains ) { |
| 373 | foreach ( $contains as $container_id => $field_ids ) { |
| 374 | if ( ! isset( $visibility[ $container_id ] ) || false !== $visibility[ $container_id ] ) { |
| 375 | continue; |
| 376 | } |
| 377 | |
| 378 | foreach ( $field_ids as $field_id ) { |
| 379 | $visibility[ $field_id ] = false; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | return $visibility; |
| 384 | } |
| 385 | } |