class-wp-theme-json.php 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153
  1. <?php
  2. /**
  3. * WP_Theme_JSON class
  4. *
  5. * @package WordPress
  6. * @subpackage Theme
  7. * @since 5.8.0
  8. */
  9. /**
  10. * Class that encapsulates the processing of structures that adhere to the theme.json spec.
  11. *
  12. * This class is for internal core usage and is not supposed to be used by extenders (plugins and/or themes).
  13. * This is a low-level API that may need to do breaking changes. Please,
  14. * use get_global_settings, get_global_styles, and get_global_stylesheet instead.
  15. *
  16. * @access private
  17. */
  18. #[AllowDynamicProperties]
  19. class WP_Theme_JSON {
  20. /**
  21. * Container of data in theme.json format.
  22. *
  23. * @since 5.8.0
  24. * @var array
  25. */
  26. protected $theme_json = null;
  27. /**
  28. * Holds block metadata extracted from block.json
  29. * to be shared among all instances so we don't
  30. * process it twice.
  31. *
  32. * @since 5.8.0
  33. * @since 6.1.0 Initialize as an empty array.
  34. * @var array
  35. */
  36. protected static $blocks_metadata = array();
  37. /**
  38. * The CSS selector for the top-level styles.
  39. *
  40. * @since 5.8.0
  41. * @var string
  42. */
  43. const ROOT_BLOCK_SELECTOR = 'body';
  44. /**
  45. * The sources of data this object can represent.
  46. *
  47. * @since 5.8.0
  48. * @since 6.1.0 Added 'blocks'.
  49. * @var string[]
  50. */
  51. const VALID_ORIGINS = array(
  52. 'default',
  53. 'blocks',
  54. 'theme',
  55. 'custom',
  56. );
  57. /**
  58. * Presets are a set of values that serve
  59. * to bootstrap some styles: colors, font sizes, etc.
  60. *
  61. * They are a unkeyed array of values such as:
  62. *
  63. * ```php
  64. * array(
  65. * array(
  66. * 'slug' => 'unique-name-within-the-set',
  67. * 'name' => 'Name for the UI',
  68. * <value_key> => 'value'
  69. * ),
  70. * )
  71. * ```
  72. *
  73. * This contains the necessary metadata to process them:
  74. *
  75. * - path => Where to find the preset within the settings section.
  76. * - prevent_override => Disables override of default presets by theme presets.
  77. * The relationship between whether to override the defaults
  78. * and whether the defaults are enabled is inverse:
  79. * - If defaults are enabled => theme presets should not be overriden
  80. * - If defaults are disabled => theme presets should be overriden
  81. * For example, a theme sets defaultPalette to false,
  82. * making the default palette hidden from the user.
  83. * In that case, we want all the theme presets to be present,
  84. * so they should override the defaults by setting this false.
  85. * - use_default_names => whether to use the default names
  86. * - value_key => the key that represents the value
  87. * - value_func => optionally, instead of value_key, a function to generate
  88. * the value that takes a preset as an argument
  89. * (either value_key or value_func should be present)
  90. * - css_vars => template string to use in generating the CSS Custom Property.
  91. * Example output: "--wp--preset--duotone--blue: <value>" will generate as many CSS Custom Properties as presets defined
  92. * substituting the $slug for the slug's value for each preset value.
  93. * - classes => array containing a structure with the classes to
  94. * generate for the presets, where for each array item
  95. * the key is the class name and the value the property name.
  96. * The "$slug" substring will be replaced by the slug of each preset.
  97. * For example:
  98. * 'classes' => array(
  99. * '.has-$slug-color' => 'color',
  100. * '.has-$slug-background-color' => 'background-color',
  101. * '.has-$slug-border-color' => 'border-color',
  102. * )
  103. * - properties => array of CSS properties to be used by kses to
  104. * validate the content of each preset
  105. * by means of the remove_insecure_properties method.
  106. *
  107. * @since 5.8.0
  108. * @since 5.9.0 Added the `color.duotone` and `typography.fontFamilies` presets,
  109. * `use_default_names` preset key, and simplified the metadata structure.
  110. * @since 6.0.0 Replaced `override` with `prevent_override` and updated the
  111. * `prevent_overried` value for `color.duotone` to use `color.defaultDuotone`.
  112. * @var array
  113. */
  114. const PRESETS_METADATA = array(
  115. array(
  116. 'path' => array( 'color', 'palette' ),
  117. 'prevent_override' => array( 'color', 'defaultPalette' ),
  118. 'use_default_names' => false,
  119. 'value_key' => 'color',
  120. 'css_vars' => '--wp--preset--color--$slug',
  121. 'classes' => array(
  122. '.has-$slug-color' => 'color',
  123. '.has-$slug-background-color' => 'background-color',
  124. '.has-$slug-border-color' => 'border-color',
  125. ),
  126. 'properties' => array( 'color', 'background-color', 'border-color' ),
  127. ),
  128. array(
  129. 'path' => array( 'color', 'gradients' ),
  130. 'prevent_override' => array( 'color', 'defaultGradients' ),
  131. 'use_default_names' => false,
  132. 'value_key' => 'gradient',
  133. 'css_vars' => '--wp--preset--gradient--$slug',
  134. 'classes' => array( '.has-$slug-gradient-background' => 'background' ),
  135. 'properties' => array( 'background' ),
  136. ),
  137. array(
  138. 'path' => array( 'color', 'duotone' ),
  139. 'prevent_override' => array( 'color', 'defaultDuotone' ),
  140. 'use_default_names' => false,
  141. 'value_func' => 'wp_get_duotone_filter_property',
  142. 'css_vars' => '--wp--preset--duotone--$slug',
  143. 'classes' => array(),
  144. 'properties' => array( 'filter' ),
  145. ),
  146. array(
  147. 'path' => array( 'typography', 'fontSizes' ),
  148. 'prevent_override' => false,
  149. 'use_default_names' => true,
  150. 'value_func' => 'wp_get_typography_font_size_value',
  151. 'css_vars' => '--wp--preset--font-size--$slug',
  152. 'classes' => array( '.has-$slug-font-size' => 'font-size' ),
  153. 'properties' => array( 'font-size' ),
  154. ),
  155. array(
  156. 'path' => array( 'typography', 'fontFamilies' ),
  157. 'prevent_override' => false,
  158. 'use_default_names' => false,
  159. 'value_key' => 'fontFamily',
  160. 'css_vars' => '--wp--preset--font-family--$slug',
  161. 'classes' => array( '.has-$slug-font-family' => 'font-family' ),
  162. 'properties' => array( 'font-family' ),
  163. ),
  164. array(
  165. 'path' => array( 'spacing', 'spacingSizes' ),
  166. 'prevent_override' => false,
  167. 'use_default_names' => true,
  168. 'value_key' => 'size',
  169. 'css_vars' => '--wp--preset--spacing--$slug',
  170. 'classes' => array(),
  171. 'properties' => array( 'padding', 'margin' ),
  172. ),
  173. );
  174. /**
  175. * Metadata for style properties.
  176. *
  177. * Each element is a direct mapping from the CSS property name to the
  178. * path to the value in theme.json & block attributes.
  179. *
  180. * @since 5.8.0
  181. * @since 5.9.0 Added the `border-*`, `font-family`, `font-style`, `font-weight`,
  182. * `letter-spacing`, `margin-*`, `padding-*`, `--wp--style--block-gap`,
  183. * `text-decoration`, `text-transform`, and `filter` properties,
  184. * simplified the metadata structure.
  185. * @since 6.1.0 Added the `border-*-color`, `border-*-width`, `border-*-style`,
  186. * `--wp--style--root--padding-*`, and `box-shadow` properties,
  187. * removed the `--wp--style--block-gap` property.
  188. * @var array
  189. */
  190. const PROPERTIES_METADATA = array(
  191. 'background' => array( 'color', 'gradient' ),
  192. 'background-color' => array( 'color', 'background' ),
  193. 'border-radius' => array( 'border', 'radius' ),
  194. 'border-top-left-radius' => array( 'border', 'radius', 'topLeft' ),
  195. 'border-top-right-radius' => array( 'border', 'radius', 'topRight' ),
  196. 'border-bottom-left-radius' => array( 'border', 'radius', 'bottomLeft' ),
  197. 'border-bottom-right-radius' => array( 'border', 'radius', 'bottomRight' ),
  198. 'border-color' => array( 'border', 'color' ),
  199. 'border-width' => array( 'border', 'width' ),
  200. 'border-style' => array( 'border', 'style' ),
  201. 'border-top-color' => array( 'border', 'top', 'color' ),
  202. 'border-top-width' => array( 'border', 'top', 'width' ),
  203. 'border-top-style' => array( 'border', 'top', 'style' ),
  204. 'border-right-color' => array( 'border', 'right', 'color' ),
  205. 'border-right-width' => array( 'border', 'right', 'width' ),
  206. 'border-right-style' => array( 'border', 'right', 'style' ),
  207. 'border-bottom-color' => array( 'border', 'bottom', 'color' ),
  208. 'border-bottom-width' => array( 'border', 'bottom', 'width' ),
  209. 'border-bottom-style' => array( 'border', 'bottom', 'style' ),
  210. 'border-left-color' => array( 'border', 'left', 'color' ),
  211. 'border-left-width' => array( 'border', 'left', 'width' ),
  212. 'border-left-style' => array( 'border', 'left', 'style' ),
  213. 'color' => array( 'color', 'text' ),
  214. 'font-family' => array( 'typography', 'fontFamily' ),
  215. 'font-size' => array( 'typography', 'fontSize' ),
  216. 'font-style' => array( 'typography', 'fontStyle' ),
  217. 'font-weight' => array( 'typography', 'fontWeight' ),
  218. 'letter-spacing' => array( 'typography', 'letterSpacing' ),
  219. 'line-height' => array( 'typography', 'lineHeight' ),
  220. 'margin' => array( 'spacing', 'margin' ),
  221. 'margin-top' => array( 'spacing', 'margin', 'top' ),
  222. 'margin-right' => array( 'spacing', 'margin', 'right' ),
  223. 'margin-bottom' => array( 'spacing', 'margin', 'bottom' ),
  224. 'margin-left' => array( 'spacing', 'margin', 'left' ),
  225. 'padding' => array( 'spacing', 'padding' ),
  226. 'padding-top' => array( 'spacing', 'padding', 'top' ),
  227. 'padding-right' => array( 'spacing', 'padding', 'right' ),
  228. 'padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
  229. 'padding-left' => array( 'spacing', 'padding', 'left' ),
  230. '--wp--style--root--padding' => array( 'spacing', 'padding' ),
  231. '--wp--style--root--padding-top' => array( 'spacing', 'padding', 'top' ),
  232. '--wp--style--root--padding-right' => array( 'spacing', 'padding', 'right' ),
  233. '--wp--style--root--padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
  234. '--wp--style--root--padding-left' => array( 'spacing', 'padding', 'left' ),
  235. 'text-decoration' => array( 'typography', 'textDecoration' ),
  236. 'text-transform' => array( 'typography', 'textTransform' ),
  237. 'filter' => array( 'filter', 'duotone' ),
  238. 'box-shadow' => array( 'shadow' ),
  239. );
  240. /**
  241. * Protected style properties.
  242. *
  243. * These style properties are only rendered if a setting enables it
  244. * via a value other than `null`.
  245. *
  246. * Each element maps the style property to the corresponding theme.json
  247. * setting key.
  248. *
  249. * @since 5.9.0
  250. */
  251. const PROTECTED_PROPERTIES = array(
  252. 'spacing.blockGap' => array( 'spacing', 'blockGap' ),
  253. );
  254. /**
  255. * The top-level keys a theme.json can have.
  256. *
  257. * @since 5.8.0 As `ALLOWED_TOP_LEVEL_KEYS`.
  258. * @since 5.9.0 Renamed from `ALLOWED_TOP_LEVEL_KEYS` to `VALID_TOP_LEVEL_KEYS`,
  259. * added the `customTemplates` and `templateParts` values.
  260. * @var string[]
  261. */
  262. const VALID_TOP_LEVEL_KEYS = array(
  263. 'customTemplates',
  264. 'patterns',
  265. 'settings',
  266. 'styles',
  267. 'templateParts',
  268. 'version',
  269. 'title',
  270. );
  271. /**
  272. * The valid properties under the settings key.
  273. *
  274. * @since 5.8.0 As `ALLOWED_SETTINGS`.
  275. * @since 5.9.0 Renamed from `ALLOWED_SETTINGS` to `VALID_SETTINGS`,
  276. * added new properties for `border`, `color`, `spacing`,
  277. * and `typography`, and renamed others according to the new schema.
  278. * @since 6.0.0 Added `color.defaultDuotone`.
  279. * @since 6.1.0 Added `layout.definitions` and `useRootPaddingAwareAlignments`.
  280. * @var array
  281. */
  282. const VALID_SETTINGS = array(
  283. 'appearanceTools' => null,
  284. 'useRootPaddingAwareAlignments' => null,
  285. 'border' => array(
  286. 'color' => null,
  287. 'radius' => null,
  288. 'style' => null,
  289. 'width' => null,
  290. ),
  291. 'color' => array(
  292. 'background' => null,
  293. 'custom' => null,
  294. 'customDuotone' => null,
  295. 'customGradient' => null,
  296. 'defaultDuotone' => null,
  297. 'defaultGradients' => null,
  298. 'defaultPalette' => null,
  299. 'duotone' => null,
  300. 'gradients' => null,
  301. 'link' => null,
  302. 'palette' => null,
  303. 'text' => null,
  304. ),
  305. 'custom' => null,
  306. 'layout' => array(
  307. 'contentSize' => null,
  308. 'definitions' => null,
  309. 'wideSize' => null,
  310. ),
  311. 'spacing' => array(
  312. 'customSpacingSize' => null,
  313. 'spacingSizes' => null,
  314. 'spacingScale' => null,
  315. 'blockGap' => null,
  316. 'margin' => null,
  317. 'padding' => null,
  318. 'units' => null,
  319. ),
  320. 'typography' => array(
  321. 'fluid' => null,
  322. 'customFontSize' => null,
  323. 'dropCap' => null,
  324. 'fontFamilies' => null,
  325. 'fontSizes' => null,
  326. 'fontStyle' => null,
  327. 'fontWeight' => null,
  328. 'letterSpacing' => null,
  329. 'lineHeight' => null,
  330. 'textDecoration' => null,
  331. 'textTransform' => null,
  332. ),
  333. );
  334. /**
  335. * The valid properties under the styles key.
  336. *
  337. * @since 5.8.0 As `ALLOWED_STYLES`.
  338. * @since 5.9.0 Renamed from `ALLOWED_STYLES` to `VALID_STYLES`,
  339. * added new properties for `border`, `filter`, `spacing`,
  340. * and `typography`.
  341. * @since 6.1.0 Added new side properties for `border`,
  342. * added new property `shadow`,
  343. * updated `blockGap` to be allowed at any level.
  344. * @var array
  345. */
  346. const VALID_STYLES = array(
  347. 'border' => array(
  348. 'color' => null,
  349. 'radius' => null,
  350. 'style' => null,
  351. 'width' => null,
  352. 'top' => null,
  353. 'right' => null,
  354. 'bottom' => null,
  355. 'left' => null,
  356. ),
  357. 'color' => array(
  358. 'background' => null,
  359. 'gradient' => null,
  360. 'text' => null,
  361. ),
  362. 'filter' => array(
  363. 'duotone' => null,
  364. ),
  365. 'shadow' => null,
  366. 'spacing' => array(
  367. 'margin' => null,
  368. 'padding' => null,
  369. 'blockGap' => null,
  370. ),
  371. 'typography' => array(
  372. 'fontFamily' => null,
  373. 'fontSize' => null,
  374. 'fontStyle' => null,
  375. 'fontWeight' => null,
  376. 'letterSpacing' => null,
  377. 'lineHeight' => null,
  378. 'textDecoration' => null,
  379. 'textTransform' => null,
  380. ),
  381. );
  382. /**
  383. * Defines which pseudo selectors are enabled for which elements.
  384. *
  385. * The order of the selectors should be: visited, hover, focus, active.
  386. * This is to ensure that 'visited' has the lowest specificity
  387. * and the other selectors can always overwrite it.
  388. *
  389. * See https://core.trac.wordpress.org/ticket/56928.
  390. * Note: this will affect both top-level and block-level elements.
  391. *
  392. * @since 6.1.0
  393. */
  394. const VALID_ELEMENT_PSEUDO_SELECTORS = array(
  395. 'link' => array( ':visited', ':hover', ':focus', ':active' ),
  396. 'button' => array( ':visited', ':hover', ':focus', ':active' ),
  397. );
  398. /**
  399. * The valid elements that can be found under styles.
  400. *
  401. * @since 5.8.0
  402. * @since 6.1.0 Added `heading`, `button`. and `caption` elements.
  403. * @var string[]
  404. */
  405. const ELEMENTS = array(
  406. 'link' => 'a:where(:not(.wp-element-button))', // The `where` is needed to lower the specificity.
  407. 'heading' => 'h1, h2, h3, h4, h5, h6',
  408. 'h1' => 'h1',
  409. 'h2' => 'h2',
  410. 'h3' => 'h3',
  411. 'h4' => 'h4',
  412. 'h5' => 'h5',
  413. 'h6' => 'h6',
  414. // We have the .wp-block-button__link class so that this will target older buttons that have been serialized.
  415. 'button' => '.wp-element-button, .wp-block-button__link',
  416. // The block classes are necessary to target older content that won't use the new class names.
  417. 'caption' => '.wp-element-caption, .wp-block-audio figcaption, .wp-block-embed figcaption, .wp-block-gallery figcaption, .wp-block-image figcaption, .wp-block-table figcaption, .wp-block-video figcaption',
  418. 'cite' => 'cite',
  419. );
  420. const __EXPERIMENTAL_ELEMENT_CLASS_NAMES = array(
  421. 'button' => 'wp-element-button',
  422. 'caption' => 'wp-element-caption',
  423. );
  424. /**
  425. * List of block support features that can have their related styles
  426. * generated under their own feature level selector rather than the block's.
  427. *
  428. * @since 6.1.0
  429. * @var string[]
  430. */
  431. const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = array(
  432. '__experimentalBorder' => 'border',
  433. 'color' => 'color',
  434. 'spacing' => 'spacing',
  435. 'typography' => 'typography',
  436. );
  437. /**
  438. * Returns a class name by an element name.
  439. *
  440. * @since 6.1.0
  441. *
  442. * @param string $element The name of the element.
  443. * @return string The name of the class.
  444. */
  445. public static function get_element_class_name( $element ) {
  446. $class_name = '';
  447. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  448. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  449. if ( array_key_exists( $element, static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES ) ) {
  450. $class_name = static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ];
  451. }
  452. return $class_name;
  453. }
  454. /**
  455. * Options that settings.appearanceTools enables.
  456. *
  457. * @since 6.0.0
  458. * @var array
  459. */
  460. const APPEARANCE_TOOLS_OPT_INS = array(
  461. array( 'border', 'color' ),
  462. array( 'border', 'radius' ),
  463. array( 'border', 'style' ),
  464. array( 'border', 'width' ),
  465. array( 'color', 'link' ),
  466. array( 'spacing', 'blockGap' ),
  467. array( 'spacing', 'margin' ),
  468. array( 'spacing', 'padding' ),
  469. array( 'typography', 'lineHeight' ),
  470. );
  471. /**
  472. * The latest version of the schema in use.
  473. *
  474. * @since 5.8.0
  475. * @since 5.9.0 Changed value from 1 to 2.
  476. * @var int
  477. */
  478. const LATEST_SCHEMA = 2;
  479. /**
  480. * Constructor.
  481. *
  482. * @since 5.8.0
  483. *
  484. * @param array $theme_json A structure that follows the theme.json schema.
  485. * @param string $origin Optional. What source of data this object represents.
  486. * One of 'default', 'theme', or 'custom'. Default 'theme'.
  487. */
  488. public function __construct( $theme_json = array(), $origin = 'theme' ) {
  489. if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
  490. $origin = 'theme';
  491. }
  492. $this->theme_json = WP_Theme_JSON_Schema::migrate( $theme_json );
  493. $valid_block_names = array_keys( static::get_blocks_metadata() );
  494. $valid_element_names = array_keys( static::ELEMENTS );
  495. $theme_json = static::sanitize( $this->theme_json, $valid_block_names, $valid_element_names );
  496. $this->theme_json = static::maybe_opt_in_into_settings( $theme_json );
  497. // Internally, presets are keyed by origin.
  498. $nodes = static::get_setting_nodes( $this->theme_json );
  499. foreach ( $nodes as $node ) {
  500. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  501. $path = $node['path'];
  502. foreach ( $preset_metadata['path'] as $subpath ) {
  503. $path[] = $subpath;
  504. }
  505. $preset = _wp_array_get( $this->theme_json, $path, null );
  506. if ( null !== $preset ) {
  507. // If the preset is not already keyed by origin.
  508. if ( isset( $preset[0] ) || empty( $preset ) ) {
  509. _wp_array_set( $this->theme_json, $path, array( $origin => $preset ) );
  510. }
  511. }
  512. }
  513. }
  514. }
  515. /**
  516. * Enables some opt-in settings if theme declared support.
  517. *
  518. * @since 5.9.0
  519. *
  520. * @param array $theme_json A theme.json structure to modify.
  521. * @return array The modified theme.json structure.
  522. */
  523. protected static function maybe_opt_in_into_settings( $theme_json ) {
  524. $new_theme_json = $theme_json;
  525. if (
  526. isset( $new_theme_json['settings']['appearanceTools'] ) &&
  527. true === $new_theme_json['settings']['appearanceTools']
  528. ) {
  529. static::do_opt_in_into_settings( $new_theme_json['settings'] );
  530. }
  531. if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) {
  532. foreach ( $new_theme_json['settings']['blocks'] as &$block ) {
  533. if ( isset( $block['appearanceTools'] ) && ( true === $block['appearanceTools'] ) ) {
  534. static::do_opt_in_into_settings( $block );
  535. }
  536. }
  537. }
  538. return $new_theme_json;
  539. }
  540. /**
  541. * Enables some settings.
  542. *
  543. * @since 5.9.0
  544. *
  545. * @param array $context The context to which the settings belong.
  546. */
  547. protected static function do_opt_in_into_settings( &$context ) {
  548. foreach ( static::APPEARANCE_TOOLS_OPT_INS as $path ) {
  549. // Use "unset prop" as a marker instead of "null" because
  550. // "null" can be a valid value for some props (e.g. blockGap).
  551. if ( 'unset prop' === _wp_array_get( $context, $path, 'unset prop' ) ) {
  552. _wp_array_set( $context, $path, true );
  553. }
  554. }
  555. unset( $context['appearanceTools'] );
  556. }
  557. /**
  558. * Sanitizes the input according to the schemas.
  559. *
  560. * @since 5.8.0
  561. * @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters.
  562. *
  563. * @param array $input Structure to sanitize.
  564. * @param array $valid_block_names List of valid block names.
  565. * @param array $valid_element_names List of valid element names.
  566. * @return array The sanitized output.
  567. */
  568. protected static function sanitize( $input, $valid_block_names, $valid_element_names ) {
  569. $output = array();
  570. if ( ! is_array( $input ) ) {
  571. return $output;
  572. }
  573. // Preserve only the top most level keys.
  574. $output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) );
  575. /*
  576. * Remove any rules that are annotated as "top" in VALID_STYLES constant.
  577. * Some styles are only meant to be available at the top-level (e.g.: blockGap),
  578. * hence, the schema for blocks & elements should not have them.
  579. */
  580. $styles_non_top_level = static::VALID_STYLES;
  581. foreach ( array_keys( $styles_non_top_level ) as $section ) {
  582. // array_key_exists() needs to be used instead of isset() because the value can be null.
  583. if ( array_key_exists( $section, $styles_non_top_level ) && is_array( $styles_non_top_level[ $section ] ) ) {
  584. foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) {
  585. if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) {
  586. unset( $styles_non_top_level[ $section ][ $prop ] );
  587. }
  588. }
  589. }
  590. }
  591. // Build the schema based on valid block & element names.
  592. $schema = array();
  593. $schema_styles_elements = array();
  594. /*
  595. * Set allowed element pseudo selectors based on per element allow list.
  596. * Target data structure in schema:
  597. * e.g.
  598. * - top level elements: `$schema['styles']['elements']['link'][':hover']`.
  599. * - block level elements: `$schema['styles']['blocks']['core/button']['elements']['link'][':hover']`.
  600. */
  601. foreach ( $valid_element_names as $element ) {
  602. $schema_styles_elements[ $element ] = $styles_non_top_level;
  603. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  604. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  605. if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
  606. foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
  607. $schema_styles_elements[ $element ][ $pseudo_selector ] = $styles_non_top_level;
  608. }
  609. }
  610. }
  611. $schema_styles_blocks = array();
  612. $schema_settings_blocks = array();
  613. foreach ( $valid_block_names as $block ) {
  614. $schema_settings_blocks[ $block ] = static::VALID_SETTINGS;
  615. $schema_styles_blocks[ $block ] = $styles_non_top_level;
  616. $schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
  617. }
  618. $schema['styles'] = static::VALID_STYLES;
  619. $schema['styles']['blocks'] = $schema_styles_blocks;
  620. $schema['styles']['elements'] = $schema_styles_elements;
  621. $schema['settings'] = static::VALID_SETTINGS;
  622. $schema['settings']['blocks'] = $schema_settings_blocks;
  623. // Remove anything that's not present in the schema.
  624. foreach ( array( 'styles', 'settings' ) as $subtree ) {
  625. if ( ! isset( $input[ $subtree ] ) ) {
  626. continue;
  627. }
  628. if ( ! is_array( $input[ $subtree ] ) ) {
  629. unset( $output[ $subtree ] );
  630. continue;
  631. }
  632. $result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
  633. if ( empty( $result ) ) {
  634. unset( $output[ $subtree ] );
  635. } else {
  636. $output[ $subtree ] = $result;
  637. }
  638. }
  639. return $output;
  640. }
  641. /**
  642. * Appends a sub-selector to an existing one.
  643. *
  644. * Given the compounded $selector "h1, h2, h3"
  645. * and the $to_append selector ".some-class" the result will be
  646. * "h1.some-class, h2.some-class, h3.some-class".
  647. *
  648. * @since 5.8.0
  649. * @since 6.1.0 Added append position.
  650. *
  651. * @param string $selector Original selector.
  652. * @param string $to_append Selector to append.
  653. * @param string $position A position sub-selector should be appended. Default 'right'.
  654. * @return string The new selector.
  655. */
  656. protected static function append_to_selector( $selector, $to_append, $position = 'right' ) {
  657. $new_selectors = array();
  658. $selectors = explode( ',', $selector );
  659. foreach ( $selectors as $sel ) {
  660. $new_selectors[] = 'right' === $position ? $sel . $to_append : $to_append . $sel;
  661. }
  662. return implode( ',', $new_selectors );
  663. }
  664. /**
  665. * Returns the metadata for each block.
  666. *
  667. * Example:
  668. *
  669. * {
  670. * 'core/paragraph': {
  671. * 'selector': 'p',
  672. * 'elements': {
  673. * 'link' => 'link selector',
  674. * 'etc' => 'element selector'
  675. * }
  676. * },
  677. * 'core/heading': {
  678. * 'selector': 'h1',
  679. * 'elements': {}
  680. * },
  681. * 'core/image': {
  682. * 'selector': '.wp-block-image',
  683. * 'duotone': 'img',
  684. * 'elements': {}
  685. * }
  686. * }
  687. *
  688. * @since 5.8.0
  689. * @since 5.9.0 Added `duotone` key with CSS selector.
  690. * @since 6.1.0 Added `features` key with block support feature level selectors.
  691. *
  692. * @return array Block metadata.
  693. */
  694. protected static function get_blocks_metadata() {
  695. $registry = WP_Block_Type_Registry::get_instance();
  696. $blocks = $registry->get_all_registered();
  697. // Is there metadata for all currently registered blocks?
  698. $blocks = array_diff_key( $blocks, static::$blocks_metadata );
  699. if ( empty( $blocks ) ) {
  700. return static::$blocks_metadata;
  701. }
  702. foreach ( $blocks as $block_name => $block_type ) {
  703. if (
  704. isset( $block_type->supports['__experimentalSelector'] ) &&
  705. is_string( $block_type->supports['__experimentalSelector'] )
  706. ) {
  707. static::$blocks_metadata[ $block_name ]['selector'] = $block_type->supports['__experimentalSelector'];
  708. } else {
  709. static::$blocks_metadata[ $block_name ]['selector'] = '.wp-block-' . str_replace( '/', '-', str_replace( 'core/', '', $block_name ) );
  710. }
  711. if (
  712. isset( $block_type->supports['color']['__experimentalDuotone'] ) &&
  713. is_string( $block_type->supports['color']['__experimentalDuotone'] )
  714. ) {
  715. static::$blocks_metadata[ $block_name ]['duotone'] = $block_type->supports['color']['__experimentalDuotone'];
  716. }
  717. // Generate block support feature level selectors if opted into
  718. // for the current block.
  719. $features = array();
  720. foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) {
  721. if (
  722. isset( $block_type->supports[ $key ]['__experimentalSelector'] ) &&
  723. $block_type->supports[ $key ]['__experimentalSelector']
  724. ) {
  725. $features[ $feature ] = static::scope_selector(
  726. static::$blocks_metadata[ $block_name ]['selector'],
  727. $block_type->supports[ $key ]['__experimentalSelector']
  728. );
  729. }
  730. }
  731. if ( ! empty( $features ) ) {
  732. static::$blocks_metadata[ $block_name ]['features'] = $features;
  733. }
  734. // Assign defaults, then overwrite those that the block sets by itself.
  735. // If the block selector is compounded, will append the element to each
  736. // individual block selector.
  737. $block_selectors = explode( ',', static::$blocks_metadata[ $block_name ]['selector'] );
  738. foreach ( static::ELEMENTS as $el_name => $el_selector ) {
  739. $element_selector = array();
  740. foreach ( $block_selectors as $selector ) {
  741. if ( $selector === $el_selector ) {
  742. $element_selector = array( $el_selector );
  743. break;
  744. }
  745. $element_selector[] = static::append_to_selector( $el_selector, $selector . ' ', 'left' );
  746. }
  747. static::$blocks_metadata[ $block_name ]['elements'][ $el_name ] = implode( ',', $element_selector );
  748. }
  749. }
  750. return static::$blocks_metadata;
  751. }
  752. /**
  753. * Given a tree, removes the keys that are not present in the schema.
  754. *
  755. * It is recursive and modifies the input in-place.
  756. *
  757. * @since 5.8.0
  758. *
  759. * @param array $tree Input to process.
  760. * @param array $schema Schema to adhere to.
  761. * @return array The modified $tree.
  762. */
  763. protected static function remove_keys_not_in_schema( $tree, $schema ) {
  764. $tree = array_intersect_key( $tree, $schema );
  765. foreach ( $schema as $key => $data ) {
  766. if ( ! isset( $tree[ $key ] ) ) {
  767. continue;
  768. }
  769. if ( is_array( $schema[ $key ] ) && is_array( $tree[ $key ] ) ) {
  770. $tree[ $key ] = static::remove_keys_not_in_schema( $tree[ $key ], $schema[ $key ] );
  771. if ( empty( $tree[ $key ] ) ) {
  772. unset( $tree[ $key ] );
  773. }
  774. } elseif ( is_array( $schema[ $key ] ) && ! is_array( $tree[ $key ] ) ) {
  775. unset( $tree[ $key ] );
  776. }
  777. }
  778. return $tree;
  779. }
  780. /**
  781. * Returns the existing settings for each block.
  782. *
  783. * Example:
  784. *
  785. * {
  786. * 'root': {
  787. * 'color': {
  788. * 'custom': true
  789. * }
  790. * },
  791. * 'core/paragraph': {
  792. * 'spacing': {
  793. * 'customPadding': true
  794. * }
  795. * }
  796. * }
  797. *
  798. * @since 5.8.0
  799. *
  800. * @return array Settings per block.
  801. */
  802. public function get_settings() {
  803. if ( ! isset( $this->theme_json['settings'] ) ) {
  804. return array();
  805. } else {
  806. return $this->theme_json['settings'];
  807. }
  808. }
  809. /**
  810. * Returns the stylesheet that results of processing
  811. * the theme.json structure this object represents.
  812. *
  813. * @since 5.8.0
  814. * @since 5.9.0 Removed the `$type` parameter`, added the `$types` and `$origins` parameters.
  815. *
  816. * @param array $types Types of styles to load. Will load all by default. It accepts:
  817. * - `variables`: only the CSS Custom Properties for presets & custom ones.
  818. * - `styles`: only the styles section in theme.json.
  819. * - `presets`: only the classes for the presets.
  820. * @param array $origins A list of origins to include. By default it includes VALID_ORIGINS.
  821. * @return string The resulting stylesheet.
  822. */
  823. public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null ) {
  824. if ( null === $origins ) {
  825. $origins = static::VALID_ORIGINS;
  826. }
  827. if ( is_string( $types ) ) {
  828. // Dispatch error and map old arguments to new ones.
  829. _deprecated_argument( __FUNCTION__, '5.9.0' );
  830. if ( 'block_styles' === $types ) {
  831. $types = array( 'styles', 'presets' );
  832. } elseif ( 'css_variables' === $types ) {
  833. $types = array( 'variables' );
  834. } else {
  835. $types = array( 'variables', 'styles', 'presets' );
  836. }
  837. }
  838. $blocks_metadata = static::get_blocks_metadata();
  839. $style_nodes = static::get_style_nodes( $this->theme_json, $blocks_metadata );
  840. $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
  841. $stylesheet = '';
  842. if ( in_array( 'variables', $types, true ) ) {
  843. $stylesheet .= $this->get_css_variables( $setting_nodes, $origins );
  844. }
  845. if ( in_array( 'styles', $types, true ) ) {
  846. $root_block_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $style_nodes, 'selector' ), true );
  847. if ( false !== $root_block_key ) {
  848. $stylesheet .= $this->get_root_layout_rules( static::ROOT_BLOCK_SELECTOR, $style_nodes[ $root_block_key ] );
  849. }
  850. $stylesheet .= $this->get_block_classes( $style_nodes );
  851. } elseif ( in_array( 'base-layout-styles', $types, true ) ) {
  852. // Base layout styles are provided as part of `styles`, so only output separately if explicitly requested.
  853. // For backwards compatibility, the Columns block is explicitly included, to support a different default gap value.
  854. $base_styles_nodes = array(
  855. array(
  856. 'path' => array( 'styles' ),
  857. 'selector' => static::ROOT_BLOCK_SELECTOR,
  858. ),
  859. array(
  860. 'path' => array( 'styles', 'blocks', 'core/columns' ),
  861. 'selector' => '.wp-block-columns',
  862. 'name' => 'core/columns',
  863. ),
  864. );
  865. foreach ( $base_styles_nodes as $base_style_node ) {
  866. $stylesheet .= $this->get_layout_styles( $base_style_node );
  867. }
  868. }
  869. if ( in_array( 'presets', $types, true ) ) {
  870. $stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
  871. }
  872. return $stylesheet;
  873. }
  874. /**
  875. * Returns the page templates of the active theme.
  876. *
  877. * @since 5.9.0
  878. *
  879. * @return array
  880. */
  881. public function get_custom_templates() {
  882. $custom_templates = array();
  883. if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) {
  884. return $custom_templates;
  885. }
  886. foreach ( $this->theme_json['customTemplates'] as $item ) {
  887. if ( isset( $item['name'] ) ) {
  888. $custom_templates[ $item['name'] ] = array(
  889. 'title' => isset( $item['title'] ) ? $item['title'] : '',
  890. 'postTypes' => isset( $item['postTypes'] ) ? $item['postTypes'] : array( 'page' ),
  891. );
  892. }
  893. }
  894. return $custom_templates;
  895. }
  896. /**
  897. * Returns the template part data of active theme.
  898. *
  899. * @since 5.9.0
  900. *
  901. * @return array
  902. */
  903. public function get_template_parts() {
  904. $template_parts = array();
  905. if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) {
  906. return $template_parts;
  907. }
  908. foreach ( $this->theme_json['templateParts'] as $item ) {
  909. if ( isset( $item['name'] ) ) {
  910. $template_parts[ $item['name'] ] = array(
  911. 'title' => isset( $item['title'] ) ? $item['title'] : '',
  912. 'area' => isset( $item['area'] ) ? $item['area'] : '',
  913. );
  914. }
  915. }
  916. return $template_parts;
  917. }
  918. /**
  919. * Converts each style section into a list of rulesets
  920. * containing the block styles to be appended to the stylesheet.
  921. *
  922. * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
  923. *
  924. * For each section this creates a new ruleset such as:
  925. *
  926. * block-selector {
  927. * style-property-one: value;
  928. * }
  929. *
  930. * @since 5.8.0 As `get_block_styles()`.
  931. * @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()`
  932. * and no longer returns preset classes.
  933. * Removed the `$setting_nodes` parameter.
  934. * @since 6.1.0 Moved most internal logic to `get_styles_for_block()`.
  935. *
  936. * @param array $style_nodes Nodes with styles.
  937. * @return string The new stylesheet.
  938. */
  939. protected function get_block_classes( $style_nodes ) {
  940. $block_rules = '';
  941. foreach ( $style_nodes as $metadata ) {
  942. if ( null === $metadata['selector'] ) {
  943. continue;
  944. }
  945. $block_rules .= static::get_styles_for_block( $metadata );
  946. }
  947. return $block_rules;
  948. }
  949. /**
  950. * Gets the CSS layout rules for a particular block from theme.json layout definitions.
  951. *
  952. * @since 6.1.0
  953. *
  954. * @param array $block_metadata Metadata about the block to get styles for.
  955. * @return string Layout styles for the block.
  956. */
  957. protected function get_layout_styles( $block_metadata ) {
  958. $block_rules = '';
  959. $block_type = null;
  960. // Skip outputting layout styles if explicitly disabled.
  961. if ( current_theme_supports( 'disable-layout-styles' ) ) {
  962. return $block_rules;
  963. }
  964. if ( isset( $block_metadata['name'] ) ) {
  965. $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] );
  966. if ( ! block_has_support( $block_type, array( '__experimentalLayout' ), false ) ) {
  967. return $block_rules;
  968. }
  969. }
  970. $selector = isset( $block_metadata['selector'] ) ? $block_metadata['selector'] : '';
  971. $has_block_gap_support = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'blockGap' ) ) !== null;
  972. $has_fallback_gap_support = ! $has_block_gap_support; // This setting isn't useful yet: it exists as a placeholder for a future explicit fallback gap styles support.
  973. $node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
  974. $layout_definitions = _wp_array_get( $this->theme_json, array( 'settings', 'layout', 'definitions' ), array() );
  975. $layout_selector_pattern = '/^[a-zA-Z0-9\-\.\ *+>:\(\)]*$/'; // Allow alphanumeric classnames, spaces, wildcard, sibling, child combinator and pseudo class selectors.
  976. // Gap styles will only be output if the theme has block gap support, or supports a fallback gap.
  977. // Default layout gap styles will be skipped for themes that do not explicitly opt-in to blockGap with a `true` or `false` value.
  978. if ( $has_block_gap_support || $has_fallback_gap_support ) {
  979. $block_gap_value = null;
  980. // Use a fallback gap value if block gap support is not available.
  981. if ( ! $has_block_gap_support ) {
  982. $block_gap_value = static::ROOT_BLOCK_SELECTOR === $selector ? '0.5em' : null;
  983. if ( ! empty( $block_type ) ) {
  984. $block_gap_value = _wp_array_get( $block_type->supports, array( 'spacing', 'blockGap', '__experimentalDefault' ), null );
  985. }
  986. } else {
  987. $block_gap_value = static::get_property_value( $node, array( 'spacing', 'blockGap' ) );
  988. }
  989. // Support split row / column values and concatenate to a shorthand value.
  990. if ( is_array( $block_gap_value ) ) {
  991. if ( isset( $block_gap_value['top'] ) && isset( $block_gap_value['left'] ) ) {
  992. $gap_row = static::get_property_value( $node, array( 'spacing', 'blockGap', 'top' ) );
  993. $gap_column = static::get_property_value( $node, array( 'spacing', 'blockGap', 'left' ) );
  994. $block_gap_value = $gap_row === $gap_column ? $gap_row : $gap_row . ' ' . $gap_column;
  995. } else {
  996. // Skip outputting gap value if not all sides are provided.
  997. $block_gap_value = null;
  998. }
  999. }
  1000. // If the block should have custom gap, add the gap styles.
  1001. if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) {
  1002. foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
  1003. // Allow outputting fallback gap styles for flex layout type when block gap support isn't available.
  1004. if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key ) {
  1005. continue;
  1006. }
  1007. $class_name = sanitize_title( _wp_array_get( $layout_definition, array( 'className' ), false ) );
  1008. $spacing_rules = _wp_array_get( $layout_definition, array( 'spacingStyles' ), array() );
  1009. if (
  1010. ! empty( $class_name ) &&
  1011. ! empty( $spacing_rules )
  1012. ) {
  1013. foreach ( $spacing_rules as $spacing_rule ) {
  1014. $declarations = array();
  1015. if (
  1016. isset( $spacing_rule['selector'] ) &&
  1017. preg_match( $layout_selector_pattern, $spacing_rule['selector'] ) &&
  1018. ! empty( $spacing_rule['rules'] )
  1019. ) {
  1020. // Iterate over each of the styling rules and substitute non-string values such as `null` with the real `blockGap` value.
  1021. foreach ( $spacing_rule['rules'] as $css_property => $css_value ) {
  1022. $current_css_value = is_string( $css_value ) ? $css_value : $block_gap_value;
  1023. if ( static::is_safe_css_declaration( $css_property, $current_css_value ) ) {
  1024. $declarations[] = array(
  1025. 'name' => $css_property,
  1026. 'value' => $current_css_value,
  1027. );
  1028. }
  1029. }
  1030. if ( ! $has_block_gap_support ) {
  1031. // For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles.
  1032. $format = static::ROOT_BLOCK_SELECTOR === $selector ? ':where(.%2$s%3$s)' : ':where(%1$s.%2$s%3$s)';
  1033. $layout_selector = sprintf(
  1034. $format,
  1035. $selector,
  1036. $class_name,
  1037. $spacing_rule['selector']
  1038. );
  1039. } else {
  1040. $format = static::ROOT_BLOCK_SELECTOR === $selector ? '%s .%s%s' : '%s.%s%s';
  1041. $layout_selector = sprintf(
  1042. $format,
  1043. $selector,
  1044. $class_name,
  1045. $spacing_rule['selector']
  1046. );
  1047. }
  1048. $block_rules .= static::to_ruleset( $layout_selector, $declarations );
  1049. }
  1050. }
  1051. }
  1052. }
  1053. }
  1054. }
  1055. // Output base styles.
  1056. if (
  1057. static::ROOT_BLOCK_SELECTOR === $selector
  1058. ) {
  1059. $valid_display_modes = array( 'block', 'flex', 'grid' );
  1060. foreach ( $layout_definitions as $layout_definition ) {
  1061. $class_name = sanitize_title( _wp_array_get( $layout_definition, array( 'className' ), false ) );
  1062. $base_style_rules = _wp_array_get( $layout_definition, array( 'baseStyles' ), array() );
  1063. if (
  1064. ! empty( $class_name ) &&
  1065. ! empty( $base_style_rules )
  1066. ) {
  1067. // Output display mode. This requires special handling as `display` is not exposed in `safe_style_css_filter`.
  1068. if (
  1069. ! empty( $layout_definition['displayMode'] ) &&
  1070. is_string( $layout_definition['displayMode'] ) &&
  1071. in_array( $layout_definition['displayMode'], $valid_display_modes, true )
  1072. ) {
  1073. $layout_selector = sprintf(
  1074. '%s .%s',
  1075. $selector,
  1076. $class_name
  1077. );
  1078. $block_rules .= static::to_ruleset(
  1079. $layout_selector,
  1080. array(
  1081. array(
  1082. 'name' => 'display',
  1083. 'value' => $layout_definition['displayMode'],
  1084. ),
  1085. )
  1086. );
  1087. }
  1088. foreach ( $base_style_rules as $base_style_rule ) {
  1089. $declarations = array();
  1090. if (
  1091. isset( $base_style_rule['selector'] ) &&
  1092. preg_match( $layout_selector_pattern, $base_style_rule['selector'] ) &&
  1093. ! empty( $base_style_rule['rules'] )
  1094. ) {
  1095. foreach ( $base_style_rule['rules'] as $css_property => $css_value ) {
  1096. if ( static::is_safe_css_declaration( $css_property, $css_value ) ) {
  1097. $declarations[] = array(
  1098. 'name' => $css_property,
  1099. 'value' => $css_value,
  1100. );
  1101. }
  1102. }
  1103. $layout_selector = sprintf(
  1104. '%s .%s%s',
  1105. $selector,
  1106. $class_name,
  1107. $base_style_rule['selector']
  1108. );
  1109. $block_rules .= static::to_ruleset( $layout_selector, $declarations );
  1110. }
  1111. }
  1112. }
  1113. }
  1114. }
  1115. return $block_rules;
  1116. }
  1117. /**
  1118. * Creates new rulesets as classes for each preset value such as:
  1119. *
  1120. * .has-value-color {
  1121. * color: value;
  1122. * }
  1123. *
  1124. * .has-value-background-color {
  1125. * background-color: value;
  1126. * }
  1127. *
  1128. * .has-value-font-size {
  1129. * font-size: value;
  1130. * }
  1131. *
  1132. * .has-value-gradient-background {
  1133. * background: value;
  1134. * }
  1135. *
  1136. * p.has-value-gradient-background {
  1137. * background: value;
  1138. * }
  1139. *
  1140. * @since 5.9.0
  1141. *
  1142. * @param array $setting_nodes Nodes with settings.
  1143. * @param array $origins List of origins to process presets from.
  1144. * @return string The new stylesheet.
  1145. */
  1146. protected function get_preset_classes( $setting_nodes, $origins ) {
  1147. $preset_rules = '';
  1148. foreach ( $setting_nodes as $metadata ) {
  1149. if ( null === $metadata['selector'] ) {
  1150. continue;
  1151. }
  1152. $selector = $metadata['selector'];
  1153. $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
  1154. $preset_rules .= static::compute_preset_classes( $node, $selector, $origins );
  1155. }
  1156. return $preset_rules;
  1157. }
  1158. /**
  1159. * Converts each styles section into a list of rulesets
  1160. * to be appended to the stylesheet.
  1161. * These rulesets contain all the css variables (custom variables and preset variables).
  1162. *
  1163. * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
  1164. *
  1165. * For each section this creates a new ruleset such as:
  1166. *
  1167. * block-selector {
  1168. * --wp--preset--category--slug: value;
  1169. * --wp--custom--variable: value;
  1170. * }
  1171. *
  1172. * @since 5.8.0
  1173. * @since 5.9.0 Added the `$origins` parameter.
  1174. *
  1175. * @param array $nodes Nodes with settings.
  1176. * @param array $origins List of origins to process.
  1177. * @return string The new stylesheet.
  1178. */
  1179. protected function get_css_variables( $nodes, $origins ) {
  1180. $stylesheet = '';
  1181. foreach ( $nodes as $metadata ) {
  1182. if ( null === $metadata['selector'] ) {
  1183. continue;
  1184. }
  1185. $selector = $metadata['selector'];
  1186. $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
  1187. $declarations = static::compute_preset_vars( $node, $origins );
  1188. $theme_vars_declarations = static::compute_theme_vars( $node );
  1189. foreach ( $theme_vars_declarations as $theme_vars_declaration ) {
  1190. $declarations[] = $theme_vars_declaration;
  1191. }
  1192. $stylesheet .= static::to_ruleset( $selector, $declarations );
  1193. }
  1194. return $stylesheet;
  1195. }
  1196. /**
  1197. * Given a selector and a declaration list,
  1198. * creates the corresponding ruleset.
  1199. *
  1200. * @since 5.8.0
  1201. *
  1202. * @param string $selector CSS selector.
  1203. * @param array $declarations List of declarations.
  1204. * @return string The resulting CSS ruleset.
  1205. */
  1206. protected static function to_ruleset( $selector, $declarations ) {
  1207. if ( empty( $declarations ) ) {
  1208. return '';
  1209. }
  1210. $declaration_block = array_reduce(
  1211. $declarations,
  1212. static function ( $carry, $element ) {
  1213. return $carry .= $element['name'] . ': ' . $element['value'] . ';'; },
  1214. ''
  1215. );
  1216. return $selector . '{' . $declaration_block . '}';
  1217. }
  1218. /**
  1219. * Given a settings array, returns the generated rulesets
  1220. * for the preset classes.
  1221. *
  1222. * @since 5.8.0
  1223. * @since 5.9.0 Added the `$origins` parameter.
  1224. *
  1225. * @param array $settings Settings to process.
  1226. * @param string $selector Selector wrapping the classes.
  1227. * @param array $origins List of origins to process.
  1228. * @return string The result of processing the presets.
  1229. */
  1230. protected static function compute_preset_classes( $settings, $selector, $origins ) {
  1231. if ( static::ROOT_BLOCK_SELECTOR === $selector ) {
  1232. // Classes at the global level do not need any CSS prefixed,
  1233. // and we don't want to increase its specificity.
  1234. $selector = '';
  1235. }
  1236. $stylesheet = '';
  1237. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  1238. $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins );
  1239. foreach ( $preset_metadata['classes'] as $class => $property ) {
  1240. foreach ( $slugs as $slug ) {
  1241. $css_var = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
  1242. $class_name = static::replace_slug_in_string( $class, $slug );
  1243. $stylesheet .= static::to_ruleset(
  1244. static::append_to_selector( $selector, $class_name ),
  1245. array(
  1246. array(
  1247. 'name' => $property,
  1248. 'value' => 'var(' . $css_var . ') !important',
  1249. ),
  1250. )
  1251. );
  1252. }
  1253. }
  1254. }
  1255. return $stylesheet;
  1256. }
  1257. /**
  1258. * Function that scopes a selector with another one. This works a bit like
  1259. * SCSS nesting except the `&` operator isn't supported.
  1260. *
  1261. * <code>
  1262. * $scope = '.a, .b .c';
  1263. * $selector = '> .x, .y';
  1264. * $merged = scope_selector( $scope, $selector );
  1265. * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
  1266. * </code>
  1267. *
  1268. * @since 5.9.0
  1269. *
  1270. * @param string $scope Selector to scope to.
  1271. * @param string $selector Original selector.
  1272. * @return string Scoped selector.
  1273. */
  1274. protected static function scope_selector( $scope, $selector ) {
  1275. $scopes = explode( ',', $scope );
  1276. $selectors = explode( ',', $selector );
  1277. $selectors_scoped = array();
  1278. foreach ( $scopes as $outer ) {
  1279. foreach ( $selectors as $inner ) {
  1280. $selectors_scoped[] = trim( $outer ) . ' ' . trim( $inner );
  1281. }
  1282. }
  1283. return implode( ', ', $selectors_scoped );
  1284. }
  1285. /**
  1286. * Gets preset values keyed by slugs based on settings and metadata.
  1287. *
  1288. * <code>
  1289. * $settings = array(
  1290. * 'typography' => array(
  1291. * 'fontFamilies' => array(
  1292. * array(
  1293. * 'slug' => 'sansSerif',
  1294. * 'fontFamily' => '"Helvetica Neue", sans-serif',
  1295. * ),
  1296. * array(
  1297. * 'slug' => 'serif',
  1298. * 'colors' => 'Georgia, serif',
  1299. * )
  1300. * ),
  1301. * ),
  1302. * );
  1303. * $meta = array(
  1304. * 'path' => array( 'typography', 'fontFamilies' ),
  1305. * 'value_key' => 'fontFamily',
  1306. * );
  1307. * $values_by_slug = get_settings_values_by_slug();
  1308. * // $values_by_slug === array(
  1309. * // 'sans-serif' => '"Helvetica Neue", sans-serif',
  1310. * // 'serif' => 'Georgia, serif',
  1311. * // );
  1312. * </code>
  1313. *
  1314. * @since 5.9.0
  1315. *
  1316. * @param array $settings Settings to process.
  1317. * @param array $preset_metadata One of the PRESETS_METADATA values.
  1318. * @param array $origins List of origins to process.
  1319. * @return array Array of presets where each key is a slug and each value is the preset value.
  1320. */
  1321. protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
  1322. $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
  1323. $result = array();
  1324. foreach ( $origins as $origin ) {
  1325. if ( ! isset( $preset_per_origin[ $origin ] ) ) {
  1326. continue;
  1327. }
  1328. foreach ( $preset_per_origin[ $origin ] as $preset ) {
  1329. $slug = _wp_to_kebab_case( $preset['slug'] );
  1330. $value = '';
  1331. if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
  1332. $value_key = $preset_metadata['value_key'];
  1333. $value = $preset[ $value_key ];
  1334. } elseif (
  1335. isset( $preset_metadata['value_func'] ) &&
  1336. is_callable( $preset_metadata['value_func'] )
  1337. ) {
  1338. $value_func = $preset_metadata['value_func'];
  1339. $value = call_user_func( $value_func, $preset );
  1340. } else {
  1341. // If we don't have a value, then don't add it to the result.
  1342. continue;
  1343. }
  1344. $result[ $slug ] = $value;
  1345. }
  1346. }
  1347. return $result;
  1348. }
  1349. /**
  1350. * Similar to get_settings_values_by_slug, but doesn't compute the value.
  1351. *
  1352. * @since 5.9.0
  1353. *
  1354. * @param array $settings Settings to process.
  1355. * @param array $preset_metadata One of the PRESETS_METADATA values.
  1356. * @param array $origins List of origins to process.
  1357. * @return array Array of presets where the key and value are both the slug.
  1358. */
  1359. protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) {
  1360. if ( null === $origins ) {
  1361. $origins = static::VALID_ORIGINS;
  1362. }
  1363. $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
  1364. $result = array();
  1365. foreach ( $origins as $origin ) {
  1366. if ( ! isset( $preset_per_origin[ $origin ] ) ) {
  1367. continue;
  1368. }
  1369. foreach ( $preset_per_origin[ $origin ] as $preset ) {
  1370. $slug = _wp_to_kebab_case( $preset['slug'] );
  1371. // Use the array as a set so we don't get duplicates.
  1372. $result[ $slug ] = $slug;
  1373. }
  1374. }
  1375. return $result;
  1376. }
  1377. /**
  1378. * Transforms a slug into a CSS Custom Property.
  1379. *
  1380. * @since 5.9.0
  1381. *
  1382. * @param string $input String to replace.
  1383. * @param string $slug The slug value to use to generate the custom property.
  1384. * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`.
  1385. */
  1386. protected static function replace_slug_in_string( $input, $slug ) {
  1387. return strtr( $input, array( '$slug' => $slug ) );
  1388. }
  1389. /**
  1390. * Given the block settings, extracts the CSS Custom Properties
  1391. * for the presets and adds them to the $declarations array
  1392. * following the format:
  1393. *
  1394. * array(
  1395. * 'name' => 'property_name',
  1396. * 'value' => 'property_value,
  1397. * )
  1398. *
  1399. * @since 5.8.0
  1400. * @since 5.9.0 Added the `$origins` parameter.
  1401. *
  1402. * @param array $settings Settings to process.
  1403. * @param array $origins List of origins to process.
  1404. * @return array The modified $declarations.
  1405. */
  1406. protected static function compute_preset_vars( $settings, $origins ) {
  1407. $declarations = array();
  1408. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  1409. $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins );
  1410. foreach ( $values_by_slug as $slug => $value ) {
  1411. $declarations[] = array(
  1412. 'name' => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
  1413. 'value' => $value,
  1414. );
  1415. }
  1416. }
  1417. return $declarations;
  1418. }
  1419. /**
  1420. * Given an array of settings, extracts the CSS Custom Properties
  1421. * for the custom values and adds them to the $declarations
  1422. * array following the format:
  1423. *
  1424. * array(
  1425. * 'name' => 'property_name',
  1426. * 'value' => 'property_value,
  1427. * )
  1428. *
  1429. * @since 5.8.0
  1430. *
  1431. * @param array $settings Settings to process.
  1432. * @return array The modified $declarations.
  1433. */
  1434. protected static function compute_theme_vars( $settings ) {
  1435. $declarations = array();
  1436. $custom_values = _wp_array_get( $settings, array( 'custom' ), array() );
  1437. $css_vars = static::flatten_tree( $custom_values );
  1438. foreach ( $css_vars as $key => $value ) {
  1439. $declarations[] = array(
  1440. 'name' => '--wp--custom--' . $key,
  1441. 'value' => $value,
  1442. );
  1443. }
  1444. return $declarations;
  1445. }
  1446. /**
  1447. * Given a tree, it creates a flattened one
  1448. * by merging the keys and binding the leaf values
  1449. * to the new keys.
  1450. *
  1451. * It also transforms camelCase names into kebab-case
  1452. * and substitutes '/' by '-'.
  1453. *
  1454. * This is thought to be useful to generate
  1455. * CSS Custom Properties from a tree,
  1456. * although there's nothing in the implementation
  1457. * of this function that requires that format.
  1458. *
  1459. * For example, assuming the given prefix is '--wp'
  1460. * and the token is '--', for this input tree:
  1461. *
  1462. * {
  1463. * 'some/property': 'value',
  1464. * 'nestedProperty': {
  1465. * 'sub-property': 'value'
  1466. * }
  1467. * }
  1468. *
  1469. * it'll return this output:
  1470. *
  1471. * {
  1472. * '--wp--some-property': 'value',
  1473. * '--wp--nested-property--sub-property': 'value'
  1474. * }
  1475. *
  1476. * @since 5.8.0
  1477. *
  1478. * @param array $tree Input tree to process.
  1479. * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string.
  1480. * @param string $token Optional. Token to use between levels. Default '--'.
  1481. * @return array The flattened tree.
  1482. */
  1483. protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
  1484. $result = array();
  1485. foreach ( $tree as $property => $value ) {
  1486. $new_key = $prefix . str_replace(
  1487. '/',
  1488. '-',
  1489. strtolower( _wp_to_kebab_case( $property ) )
  1490. );
  1491. if ( is_array( $value ) ) {
  1492. $new_prefix = $new_key . $token;
  1493. $flattened_subtree = static::flatten_tree( $value, $new_prefix, $token );
  1494. foreach ( $flattened_subtree as $subtree_key => $subtree_value ) {
  1495. $result[ $subtree_key ] = $subtree_value;
  1496. }
  1497. } else {
  1498. $result[ $new_key ] = $value;
  1499. }
  1500. }
  1501. return $result;
  1502. }
  1503. /**
  1504. * Given a styles array, it extracts the style properties
  1505. * and adds them to the $declarations array following the format:
  1506. *
  1507. * array(
  1508. * 'name' => 'property_name',
  1509. * 'value' => 'property_value,
  1510. * )
  1511. *
  1512. * @since 5.8.0
  1513. * @since 5.9.0 Added the `$settings` and `$properties` parameters.
  1514. * @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters.
  1515. *
  1516. * @param array $styles Styles to process.
  1517. * @param array $settings Theme settings.
  1518. * @param array $properties Properties metadata.
  1519. * @param array $theme_json Theme JSON array.
  1520. * @param string $selector The style block selector.
  1521. * @param boolean $use_root_padding Whether to add custom properties at root level.
  1522. * @return array Returns the modified $declarations.
  1523. */
  1524. protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) {
  1525. if ( null === $properties ) {
  1526. $properties = static::PROPERTIES_METADATA;
  1527. }
  1528. $declarations = array();
  1529. if ( empty( $styles ) ) {
  1530. return $declarations;
  1531. }
  1532. $root_variable_duplicates = array();
  1533. foreach ( $properties as $css_property => $value_path ) {
  1534. $value = static::get_property_value( $styles, $value_path, $theme_json );
  1535. if ( str_starts_with( $css_property, '--wp--style--root--' ) && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) {
  1536. continue;
  1537. }
  1538. // Root-level padding styles don't currently support strings with CSS shorthand values.
  1539. // This may change: https://github.com/WordPress/gutenberg/issues/40132.
  1540. if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) {
  1541. continue;
  1542. }
  1543. if ( str_starts_with( $css_property, '--wp--style--root--' ) && $use_root_padding ) {
  1544. $root_variable_duplicates[] = substr( $css_property, strlen( '--wp--style--root--' ) );
  1545. }
  1546. // Look up protected properties, keyed by value path.
  1547. // Skip protected properties that are explicitly set to `null`.
  1548. if ( is_array( $value_path ) ) {
  1549. $path_string = implode( '.', $value_path );
  1550. if (
  1551. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  1552. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  1553. array_key_exists( $path_string, static::PROTECTED_PROPERTIES ) &&
  1554. _wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null
  1555. ) {
  1556. continue;
  1557. }
  1558. }
  1559. // Skip if empty and not "0" or value represents array of longhand values.
  1560. $has_missing_value = empty( $value ) && ! is_numeric( $value );
  1561. if ( $has_missing_value || is_array( $value ) ) {
  1562. continue;
  1563. }
  1564. // Calculates fluid typography rules where available.
  1565. if ( 'font-size' === $css_property ) {
  1566. /*
  1567. * wp_get_typography_font_size_value() will check
  1568. * if fluid typography has been activated and also
  1569. * whether the incoming value can be converted to a fluid value.
  1570. * Values that already have a clamp() function will not pass the test,
  1571. * and therefore the original $value will be returned.
  1572. */
  1573. $value = wp_get_typography_font_size_value( array( 'size' => $value ) );
  1574. }
  1575. $declarations[] = array(
  1576. 'name' => $css_property,
  1577. 'value' => $value,
  1578. );
  1579. }
  1580. // If a variable value is added to the root, the corresponding property should be removed.
  1581. foreach ( $root_variable_duplicates as $duplicate ) {
  1582. $discard = array_search( $duplicate, array_column( $declarations, 'name' ), true );
  1583. if ( is_numeric( $discard ) ) {
  1584. array_splice( $declarations, $discard, 1 );
  1585. }
  1586. }
  1587. return $declarations;
  1588. }
  1589. /**
  1590. * Returns the style property for the given path.
  1591. *
  1592. * It also converts CSS Custom Property stored as
  1593. * "var:preset|color|secondary" to the form
  1594. * "--wp--preset--color--secondary".
  1595. *
  1596. * It also converts references to a path to the value
  1597. * stored at that location, e.g.
  1598. * { "ref": "style.color.background" } => "#fff".
  1599. *
  1600. * @since 5.8.0
  1601. * @since 5.9.0 Added support for values of array type, which are returned as is.
  1602. * @since 6.1.0 Added the `$theme_json` parameter.
  1603. *
  1604. * @param array $styles Styles subtree.
  1605. * @param array $path Which property to process.
  1606. * @param array $theme_json Theme JSON array.
  1607. * @return string|array Style property value.
  1608. */
  1609. protected static function get_property_value( $styles, $path, $theme_json = null ) {
  1610. $value = _wp_array_get( $styles, $path, '' );
  1611. if ( '' === $value || null === $value ) {
  1612. // No need to process the value further.
  1613. return '';
  1614. }
  1615. /*
  1616. * This converts references to a path to the value at that path
  1617. * where the values is an array with a "ref" key, pointing to a path.
  1618. * For example: { "ref": "style.color.background" } => "#fff".
  1619. */
  1620. if ( is_array( $value ) && isset( $value['ref'] ) ) {
  1621. $value_path = explode( '.', $value['ref'] );
  1622. $ref_value = _wp_array_get( $theme_json, $value_path );
  1623. // Only use the ref value if we find anything.
  1624. if ( ! empty( $ref_value ) && is_string( $ref_value ) ) {
  1625. $value = $ref_value;
  1626. }
  1627. if ( is_array( $ref_value ) && isset( $ref_value['ref'] ) ) {
  1628. $path_string = json_encode( $path );
  1629. $ref_value_string = json_encode( $ref_value );
  1630. _doing_it_wrong(
  1631. 'get_property_value',
  1632. sprintf(
  1633. /* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */
  1634. __( 'Your %1$s file uses a dynamic value (%2$s) for the path at %3$s. However, the value at %3$s is also a dynamic value (pointing to %4$s) and pointing to another dynamic value is not supported. Please update %3$s to point directly to %4$s.' ),
  1635. 'theme.json',
  1636. $ref_value_string,
  1637. $path_string,
  1638. $ref_value['ref']
  1639. ),
  1640. '6.1.0'
  1641. );
  1642. }
  1643. }
  1644. if ( is_array( $value ) ) {
  1645. return $value;
  1646. }
  1647. // Convert custom CSS properties.
  1648. $prefix = 'var:';
  1649. $prefix_len = strlen( $prefix );
  1650. $token_in = '|';
  1651. $token_out = '--';
  1652. if ( 0 === strncmp( $value, $prefix, $prefix_len ) ) {
  1653. $unwrapped_name = str_replace(
  1654. $token_in,
  1655. $token_out,
  1656. substr( $value, $prefix_len )
  1657. );
  1658. $value = "var(--wp--$unwrapped_name)";
  1659. }
  1660. return $value;
  1661. }
  1662. /**
  1663. * Builds metadata for the setting nodes, which returns in the form of:
  1664. *
  1665. * [
  1666. * [
  1667. * 'path' => ['path', 'to', 'some', 'node' ],
  1668. * 'selector' => 'CSS selector for some node'
  1669. * ],
  1670. * [
  1671. * 'path' => [ 'path', 'to', 'other', 'node' ],
  1672. * 'selector' => 'CSS selector for other node'
  1673. * ],
  1674. * ]
  1675. *
  1676. * @since 5.8.0
  1677. *
  1678. * @param array $theme_json The tree to extract setting nodes from.
  1679. * @param array $selectors List of selectors per block.
  1680. * @return array An array of setting nodes metadata.
  1681. */
  1682. protected static function get_setting_nodes( $theme_json, $selectors = array() ) {
  1683. $nodes = array();
  1684. if ( ! isset( $theme_json['settings'] ) ) {
  1685. return $nodes;
  1686. }
  1687. // Top-level.
  1688. $nodes[] = array(
  1689. 'path' => array( 'settings' ),
  1690. 'selector' => static::ROOT_BLOCK_SELECTOR,
  1691. );
  1692. // Calculate paths for blocks.
  1693. if ( ! isset( $theme_json['settings']['blocks'] ) ) {
  1694. return $nodes;
  1695. }
  1696. foreach ( $theme_json['settings']['blocks'] as $name => $node ) {
  1697. $selector = null;
  1698. if ( isset( $selectors[ $name ]['selector'] ) ) {
  1699. $selector = $selectors[ $name ]['selector'];
  1700. }
  1701. $nodes[] = array(
  1702. 'path' => array( 'settings', 'blocks', $name ),
  1703. 'selector' => $selector,
  1704. );
  1705. }
  1706. return $nodes;
  1707. }
  1708. /**
  1709. * Builds metadata for the style nodes, which returns in the form of:
  1710. *
  1711. * [
  1712. * [
  1713. * 'path' => [ 'path', 'to', 'some', 'node' ],
  1714. * 'selector' => 'CSS selector for some node',
  1715. * 'duotone' => 'CSS selector for duotone for some node'
  1716. * ],
  1717. * [
  1718. * 'path' => ['path', 'to', 'other', 'node' ],
  1719. * 'selector' => 'CSS selector for other node',
  1720. * 'duotone' => null
  1721. * ],
  1722. * ]
  1723. *
  1724. * @since 5.8.0
  1725. *
  1726. * @param array $theme_json The tree to extract style nodes from.
  1727. * @param array $selectors List of selectors per block.
  1728. * @return array An array of style nodes metadata.
  1729. */
  1730. protected static function get_style_nodes( $theme_json, $selectors = array() ) {
  1731. $nodes = array();
  1732. if ( ! isset( $theme_json['styles'] ) ) {
  1733. return $nodes;
  1734. }
  1735. // Top-level.
  1736. $nodes[] = array(
  1737. 'path' => array( 'styles' ),
  1738. 'selector' => static::ROOT_BLOCK_SELECTOR,
  1739. );
  1740. if ( isset( $theme_json['styles']['elements'] ) ) {
  1741. foreach ( self::ELEMENTS as $element => $selector ) {
  1742. if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) {
  1743. continue;
  1744. }
  1745. $nodes[] = array(
  1746. 'path' => array( 'styles', 'elements', $element ),
  1747. 'selector' => static::ELEMENTS[ $element ],
  1748. );
  1749. // Handle any pseudo selectors for the element.
  1750. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  1751. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  1752. if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
  1753. foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
  1754. if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) {
  1755. $nodes[] = array(
  1756. 'path' => array( 'styles', 'elements', $element ),
  1757. 'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ),
  1758. );
  1759. }
  1760. }
  1761. }
  1762. }
  1763. }
  1764. // Blocks.
  1765. if ( ! isset( $theme_json['styles']['blocks'] ) ) {
  1766. return $nodes;
  1767. }
  1768. $block_nodes = static::get_block_nodes( $theme_json );
  1769. foreach ( $block_nodes as $block_node ) {
  1770. $nodes[] = $block_node;
  1771. }
  1772. /**
  1773. * Filters the list of style nodes with metadata.
  1774. *
  1775. * This allows for things like loading block CSS independently.
  1776. *
  1777. * @since 6.1.0
  1778. *
  1779. * @param array $nodes Style nodes with metadata.
  1780. */
  1781. return apply_filters( 'wp_theme_json_get_style_nodes', $nodes );
  1782. }
  1783. /**
  1784. * A public helper to get the block nodes from a theme.json file.
  1785. *
  1786. * @since 6.1.0
  1787. *
  1788. * @return array The block nodes in theme.json.
  1789. */
  1790. public function get_styles_block_nodes() {
  1791. return static::get_block_nodes( $this->theme_json );
  1792. }
  1793. /**
  1794. * Returns a filtered declarations array if there is a separator block with only a background
  1795. * style defined in theme.json by adding a color attribute to reflect the changes in the front.
  1796. *
  1797. * @since 6.1.1
  1798. *
  1799. * @param array $declarations List of declarations.
  1800. * @return array $declarations List of declarations filtered.
  1801. */
  1802. private static function update_separator_declarations( $declarations ) {
  1803. $background_color = '';
  1804. $border_color_matches = false;
  1805. $text_color_matches = false;
  1806. foreach ( $declarations as $declaration ) {
  1807. if ( 'background-color' === $declaration['name'] && ! $background_color && isset( $declaration['value'] ) ) {
  1808. $background_color = $declaration['value'];
  1809. } elseif ( 'border-color' === $declaration['name'] ) {
  1810. $border_color_matches = true;
  1811. } elseif ( 'color' === $declaration['name'] ) {
  1812. $text_color_matches = true;
  1813. }
  1814. if ( $background_color && $border_color_matches && $text_color_matches ) {
  1815. break;
  1816. }
  1817. }
  1818. if ( $background_color && ! $border_color_matches && ! $text_color_matches ) {
  1819. $declarations[] = array(
  1820. 'name' => 'color',
  1821. 'value' => $background_color,
  1822. );
  1823. }
  1824. return $declarations;
  1825. }
  1826. /**
  1827. * An internal method to get the block nodes from a theme.json file.
  1828. *
  1829. * @since 6.1.0
  1830. *
  1831. * @param array $theme_json The theme.json converted to an array.
  1832. * @return array The block nodes in theme.json.
  1833. */
  1834. private static function get_block_nodes( $theme_json ) {
  1835. $selectors = static::get_blocks_metadata();
  1836. $nodes = array();
  1837. if ( ! isset( $theme_json['styles'] ) ) {
  1838. return $nodes;
  1839. }
  1840. // Blocks.
  1841. if ( ! isset( $theme_json['styles']['blocks'] ) ) {
  1842. return $nodes;
  1843. }
  1844. foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
  1845. $selector = null;
  1846. if ( isset( $selectors[ $name ]['selector'] ) ) {
  1847. $selector = $selectors[ $name ]['selector'];
  1848. }
  1849. $duotone_selector = null;
  1850. if ( isset( $selectors[ $name ]['duotone'] ) ) {
  1851. $duotone_selector = $selectors[ $name ]['duotone'];
  1852. }
  1853. $feature_selectors = null;
  1854. if ( isset( $selectors[ $name ]['features'] ) ) {
  1855. $feature_selectors = $selectors[ $name ]['features'];
  1856. }
  1857. $nodes[] = array(
  1858. 'name' => $name,
  1859. 'path' => array( 'styles', 'blocks', $name ),
  1860. 'selector' => $selector,
  1861. 'duotone' => $duotone_selector,
  1862. 'features' => $feature_selectors,
  1863. );
  1864. if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) {
  1865. foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) {
  1866. $nodes[] = array(
  1867. 'path' => array( 'styles', 'blocks', $name, 'elements', $element ),
  1868. 'selector' => $selectors[ $name ]['elements'][ $element ],
  1869. );
  1870. // Handle any pseudo selectors for the element.
  1871. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  1872. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  1873. if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
  1874. foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
  1875. if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) {
  1876. $nodes[] = array(
  1877. 'path' => array( 'styles', 'blocks', $name, 'elements', $element ),
  1878. 'selector' => static::append_to_selector( $selectors[ $name ]['elements'][ $element ], $pseudo_selector ),
  1879. );
  1880. }
  1881. }
  1882. }
  1883. }
  1884. }
  1885. }
  1886. return $nodes;
  1887. }
  1888. /**
  1889. * Gets the CSS rules for a particular block from theme.json.
  1890. *
  1891. * @since 6.1.0
  1892. *
  1893. * @param array $block_metadata Metadata about the block to get styles for.
  1894. *
  1895. * @return string Styles for the block.
  1896. */
  1897. public function get_styles_for_block( $block_metadata ) {
  1898. $node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
  1899. $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
  1900. $selector = $block_metadata['selector'];
  1901. $settings = _wp_array_get( $this->theme_json, array( 'settings' ) );
  1902. /*
  1903. * Process style declarations for block support features the current
  1904. * block contains selectors for. Values for a feature with a custom
  1905. * selector are filtered from the theme.json node before it is
  1906. * processed as normal.
  1907. */
  1908. $feature_declarations = array();
  1909. if ( ! empty( $block_metadata['features'] ) ) {
  1910. foreach ( $block_metadata['features'] as $feature_name => $feature_selector ) {
  1911. if ( ! empty( $node[ $feature_name ] ) ) {
  1912. // Create temporary node containing only the feature data
  1913. // to leverage existing `compute_style_properties` function.
  1914. $feature = array( $feature_name => $node[ $feature_name ] );
  1915. // Generate the feature's declarations only.
  1916. $new_feature_declarations = static::compute_style_properties( $feature, $settings, null, $this->theme_json );
  1917. // Merge new declarations with any that already exist for
  1918. // the feature selector. This may occur when multiple block
  1919. // support features use the same custom selector.
  1920. if ( isset( $feature_declarations[ $feature_selector ] ) ) {
  1921. foreach ( $new_feature_declarations as $new_feature_declaration ) {
  1922. $feature_declarations[ $feature_selector ][] = $feature_declaration;
  1923. }
  1924. } else {
  1925. $feature_declarations[ $feature_selector ] = $new_feature_declarations;
  1926. }
  1927. // Remove the feature from the block's node now the
  1928. // styles will be included under the feature level selector.
  1929. unset( $node[ $feature_name ] );
  1930. }
  1931. }
  1932. }
  1933. /*
  1934. * Get a reference to element name from path.
  1935. * $block_metadata['path'] = array( 'styles','elements','link' );
  1936. * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ].
  1937. * Skip non-element paths like just ['styles'].
  1938. */
  1939. $is_processing_element = in_array( 'elements', $block_metadata['path'], true );
  1940. $current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null;
  1941. $element_pseudo_allowed = array();
  1942. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  1943. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  1944. if ( array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
  1945. $element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ];
  1946. }
  1947. /*
  1948. * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
  1949. * This also resets the array keys.
  1950. */
  1951. $pseudo_matches = array_values(
  1952. array_filter(
  1953. $element_pseudo_allowed,
  1954. function( $pseudo_selector ) use ( $selector ) {
  1955. return str_contains( $selector, $pseudo_selector );
  1956. }
  1957. )
  1958. );
  1959. $pseudo_selector = isset( $pseudo_matches[0] ) ? $pseudo_matches[0] : null;
  1960. /*
  1961. * If the current selector is a pseudo selector that's defined in the allow list for the current
  1962. * element then compute the style properties for it.
  1963. * Otherwise just compute the styles for the default selector as normal.
  1964. */
  1965. if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) &&
  1966. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  1967. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  1968. array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS )
  1969. && in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true )
  1970. ) {
  1971. $declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
  1972. } else {
  1973. $declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
  1974. }
  1975. $block_rules = '';
  1976. /*
  1977. * 1. Separate the declarations that use the general selector
  1978. * from the ones using the duotone selector.
  1979. */
  1980. $declarations_duotone = array();
  1981. foreach ( $declarations as $index => $declaration ) {
  1982. if ( 'filter' === $declaration['name'] ) {
  1983. unset( $declarations[ $index ] );
  1984. $declarations_duotone[] = $declaration;
  1985. }
  1986. }
  1987. // Update declarations if there are separators with only background color defined.
  1988. if ( '.wp-block-separator' === $selector ) {
  1989. $declarations = static::update_separator_declarations( $declarations );
  1990. }
  1991. // 2. Generate and append the rules that use the general selector.
  1992. $block_rules .= static::to_ruleset( $selector, $declarations );
  1993. // 3. Generate and append the rules that use the duotone selector.
  1994. if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
  1995. $selector_duotone = static::scope_selector( $block_metadata['selector'], $block_metadata['duotone'] );
  1996. $block_rules .= static::to_ruleset( $selector_duotone, $declarations_duotone );
  1997. }
  1998. // 4. Generate Layout block gap styles.
  1999. if (
  2000. static::ROOT_BLOCK_SELECTOR !== $selector &&
  2001. ! empty( $block_metadata['name'] )
  2002. ) {
  2003. $block_rules .= $this->get_layout_styles( $block_metadata );
  2004. }
  2005. // 5. Generate and append the feature level rulesets.
  2006. foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
  2007. $block_rules .= static::to_ruleset( $feature_selector, $individual_feature_declarations );
  2008. }
  2009. return $block_rules;
  2010. }
  2011. /**
  2012. * Outputs the CSS for layout rules on the root.
  2013. *
  2014. * @since 6.1.0
  2015. *
  2016. * @param string $selector The root node selector.
  2017. * @param array $block_metadata The metadata for the root block.
  2018. * @return string The additional root rules CSS.
  2019. */
  2020. public function get_root_layout_rules( $selector, $block_metadata ) {
  2021. $css = '';
  2022. $settings = _wp_array_get( $this->theme_json, array( 'settings' ) );
  2023. $use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
  2024. /*
  2025. * Reset default browser margin on the root body element.
  2026. * This is set on the root selector **before** generating the ruleset
  2027. * from the `theme.json`. This is to ensure that if the `theme.json` declares
  2028. * `margin` in its `spacing` declaration for the `body` element then these
  2029. * user-generated values take precedence in the CSS cascade.
  2030. * @link https://github.com/WordPress/gutenberg/issues/36147.
  2031. */
  2032. $css .= 'body { margin: 0;';
  2033. /*
  2034. * If there are content and wide widths in theme.json, output them
  2035. * as custom properties on the body element so all blocks can use them.
  2036. */
  2037. if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) {
  2038. $content_size = isset( $settings['layout']['contentSize'] ) ? $settings['layout']['contentSize'] : $settings['layout']['wideSize'];
  2039. $content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial';
  2040. $wide_size = isset( $settings['layout']['wideSize'] ) ? $settings['layout']['wideSize'] : $settings['layout']['contentSize'];
  2041. $wide_size = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial';
  2042. $css .= '--wp--style--global--content-size: ' . $content_size . ';';
  2043. $css .= '--wp--style--global--wide-size: ' . $wide_size . ';';
  2044. }
  2045. $css .= ' }';
  2046. if ( $use_root_padding ) {
  2047. // Top and bottom padding are applied to the outer block container.
  2048. $css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }';
  2049. // Right and left padding are applied to the first container with `.has-global-padding` class.
  2050. $css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
  2051. // Nested containers with `.has-global-padding` class do not get padding.
  2052. $css .= '.has-global-padding :where(.has-global-padding) { padding-right: 0; padding-left: 0; }';
  2053. // Alignfull children of the container with left and right padding have negative margins so they can still be full width.
  2054. $css .= '.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }';
  2055. // The above rule is negated for alignfull children of nested containers.
  2056. $css .= '.has-global-padding :where(.has-global-padding) > .alignfull { margin-right: 0; margin-left: 0; }';
  2057. // Some of the children of alignfull blocks without content width should also get padding: text blocks and non-alignfull container blocks.
  2058. $css .= '.has-global-padding > .alignfull:where(:not(.has-global-padding)) > :where([class*="wp-block-"]:not(.alignfull):not([class*="__"]),p,h1,h2,h3,h4,h5,h6,ul,ol) { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
  2059. // The above rule also has to be negated for blocks inside nested `.has-global-padding` blocks.
  2060. $css .= '.has-global-padding :where(.has-global-padding) > .alignfull:where(:not(.has-global-padding)) > :where([class*="wp-block-"]:not(.alignfull):not([class*="__"]),p,h1,h2,h3,h4,h5,h6,ul,ol) { padding-right: 0; padding-left: 0; }';
  2061. }
  2062. $css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
  2063. $css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
  2064. $css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
  2065. $block_gap_value = _wp_array_get( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ), '0.5em' );
  2066. $has_block_gap_support = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'blockGap' ) ) !== null;
  2067. if ( $has_block_gap_support ) {
  2068. $block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) );
  2069. $css .= '.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }';
  2070. $css .= ".wp-site-blocks > * + * { margin-block-start: $block_gap_value; }";
  2071. // For backwards compatibility, ensure the legacy block gap CSS variable is still available.
  2072. $css .= "$selector { --wp--style--block-gap: $block_gap_value; }";
  2073. }
  2074. $css .= $this->get_layout_styles( $block_metadata );
  2075. return $css;
  2076. }
  2077. /**
  2078. * For metadata values that can either be booleans or paths to booleans, gets the value.
  2079. *
  2080. * ```php
  2081. * $data = array(
  2082. * 'color' => array(
  2083. * 'defaultPalette' => true
  2084. * )
  2085. * );
  2086. *
  2087. * static::get_metadata_boolean( $data, false );
  2088. * // => false
  2089. *
  2090. * static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) );
  2091. * // => true
  2092. * ```
  2093. *
  2094. * @since 6.0.0
  2095. *
  2096. * @param array $data The data to inspect.
  2097. * @param bool|array $path Boolean or path to a boolean.
  2098. * @param bool $default Default value if the referenced path is missing.
  2099. * Default false.
  2100. * @return bool Value of boolean metadata.
  2101. */
  2102. protected static function get_metadata_boolean( $data, $path, $default = false ) {
  2103. if ( is_bool( $path ) ) {
  2104. return $path;
  2105. }
  2106. if ( is_array( $path ) ) {
  2107. $value = _wp_array_get( $data, $path );
  2108. if ( null !== $value ) {
  2109. return $value;
  2110. }
  2111. }
  2112. return $default;
  2113. }
  2114. /**
  2115. * Merges new incoming data.
  2116. *
  2117. * @since 5.8.0
  2118. * @since 5.9.0 Duotone preset also has origins.
  2119. *
  2120. * @param WP_Theme_JSON $incoming Data to merge.
  2121. */
  2122. public function merge( $incoming ) {
  2123. $incoming_data = $incoming->get_raw_data();
  2124. $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data );
  2125. /*
  2126. * The array_replace_recursive algorithm merges at the leaf level,
  2127. * but we don't want leaf arrays to be merged, so we overwrite it.
  2128. *
  2129. * For leaf values that are sequential arrays it will use the numeric indexes for replacement.
  2130. * We rather replace the existing with the incoming value, if it exists.
  2131. * This is the case of spacing.units.
  2132. *
  2133. * For leaf values that are associative arrays it will merge them as expected.
  2134. * This is also not the behavior we want for the current associative arrays (presets).
  2135. * We rather replace the existing with the incoming value, if it exists.
  2136. * This happens, for example, when we merge data from theme.json upon existing
  2137. * theme supports or when we merge anything coming from the same source twice.
  2138. * This is the case of color.palette, color.gradients, color.duotone,
  2139. * typography.fontSizes, or typography.fontFamilies.
  2140. *
  2141. * Additionally, for some preset types, we also want to make sure the
  2142. * values they introduce don't conflict with default values. We do so
  2143. * by checking the incoming slugs for theme presets and compare them
  2144. * with the equivalent default presets: if a slug is present as a default
  2145. * we remove it from the theme presets.
  2146. */
  2147. $nodes = static::get_setting_nodes( $incoming_data );
  2148. $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) );
  2149. foreach ( $nodes as $node ) {
  2150. // Replace the spacing.units.
  2151. $path = $node['path'];
  2152. $path[] = 'spacing';
  2153. $path[] = 'units';
  2154. $content = _wp_array_get( $incoming_data, $path, null );
  2155. if ( isset( $content ) ) {
  2156. _wp_array_set( $this->theme_json, $path, $content );
  2157. }
  2158. // Replace the presets.
  2159. foreach ( static::PRESETS_METADATA as $preset ) {
  2160. $override_preset = ! static::get_metadata_boolean( $this->theme_json['settings'], $preset['prevent_override'], true );
  2161. foreach ( static::VALID_ORIGINS as $origin ) {
  2162. $base_path = $node['path'];
  2163. foreach ( $preset['path'] as $leaf ) {
  2164. $base_path[] = $leaf;
  2165. }
  2166. $path = $base_path;
  2167. $path[] = $origin;
  2168. $content = _wp_array_get( $incoming_data, $path, null );
  2169. if ( ! isset( $content ) ) {
  2170. continue;
  2171. }
  2172. if ( 'theme' === $origin && $preset['use_default_names'] ) {
  2173. foreach ( $content as $key => $item ) {
  2174. if ( ! isset( $item['name'] ) ) {
  2175. $name = static::get_name_from_defaults( $item['slug'], $base_path );
  2176. if ( null !== $name ) {
  2177. $content[ $key ]['name'] = $name;
  2178. }
  2179. }
  2180. }
  2181. }
  2182. if (
  2183. ( 'theme' !== $origin ) ||
  2184. ( 'theme' === $origin && $override_preset )
  2185. ) {
  2186. _wp_array_set( $this->theme_json, $path, $content );
  2187. } else {
  2188. $slugs_node = static::get_default_slugs( $this->theme_json, $node['path'] );
  2189. $slugs = array_merge_recursive( $slugs_global, $slugs_node );
  2190. $slugs_for_preset = _wp_array_get( $slugs, $preset['path'], array() );
  2191. $content = static::filter_slugs( $content, $slugs_for_preset );
  2192. _wp_array_set( $this->theme_json, $path, $content );
  2193. }
  2194. }
  2195. }
  2196. }
  2197. }
  2198. /**
  2199. * Converts all filter (duotone) presets into SVGs.
  2200. *
  2201. * @since 5.9.1
  2202. *
  2203. * @param array $origins List of origins to process.
  2204. * @return string SVG filters.
  2205. */
  2206. public function get_svg_filters( $origins ) {
  2207. $blocks_metadata = static::get_blocks_metadata();
  2208. $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
  2209. $filters = '';
  2210. foreach ( $setting_nodes as $metadata ) {
  2211. $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
  2212. if ( empty( $node['color']['duotone'] ) ) {
  2213. continue;
  2214. }
  2215. $duotone_presets = $node['color']['duotone'];
  2216. foreach ( $origins as $origin ) {
  2217. if ( ! isset( $duotone_presets[ $origin ] ) ) {
  2218. continue;
  2219. }
  2220. foreach ( $duotone_presets[ $origin ] as $duotone_preset ) {
  2221. $filters .= wp_get_duotone_filter_svg( $duotone_preset );
  2222. }
  2223. }
  2224. }
  2225. return $filters;
  2226. }
  2227. /**
  2228. * Determines whether a presets should be overridden or not.
  2229. *
  2230. * @since 5.9.0
  2231. * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead.
  2232. *
  2233. * @param array $theme_json The theme.json like structure to inspect.
  2234. * @param array $path Path to inspect.
  2235. * @param bool|array $override Data to compute whether to override the preset.
  2236. * @return boolean
  2237. */
  2238. protected static function should_override_preset( $theme_json, $path, $override ) {
  2239. _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' );
  2240. if ( is_bool( $override ) ) {
  2241. return $override;
  2242. }
  2243. /*
  2244. * The relationship between whether to override the defaults
  2245. * and whether the defaults are enabled is inverse:
  2246. *
  2247. * - If defaults are enabled => theme presets should not be overridden
  2248. * - If defaults are disabled => theme presets should be overridden
  2249. *
  2250. * For example, a theme sets defaultPalette to false,
  2251. * making the default palette hidden from the user.
  2252. * In that case, we want all the theme presets to be present,
  2253. * so they should override the defaults.
  2254. */
  2255. if ( is_array( $override ) ) {
  2256. $value = _wp_array_get( $theme_json, array_merge( $path, $override ) );
  2257. if ( isset( $value ) ) {
  2258. return ! $value;
  2259. }
  2260. // Search the top-level key if none was found for this node.
  2261. $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) );
  2262. if ( isset( $value ) ) {
  2263. return ! $value;
  2264. }
  2265. return true;
  2266. }
  2267. }
  2268. /**
  2269. * Returns the default slugs for all the presets in an associative array
  2270. * whose keys are the preset paths and the leafs is the list of slugs.
  2271. *
  2272. * For example:
  2273. *
  2274. * array(
  2275. * 'color' => array(
  2276. * 'palette' => array( 'slug-1', 'slug-2' ),
  2277. * 'gradients' => array( 'slug-3', 'slug-4' ),
  2278. * ),
  2279. * )
  2280. *
  2281. * @since 5.9.0
  2282. *
  2283. * @param array $data A theme.json like structure.
  2284. * @param array $node_path The path to inspect. It's 'settings' by default.
  2285. * @return array
  2286. */
  2287. protected static function get_default_slugs( $data, $node_path ) {
  2288. $slugs = array();
  2289. foreach ( static::PRESETS_METADATA as $metadata ) {
  2290. $path = $node_path;
  2291. foreach ( $metadata['path'] as $leaf ) {
  2292. $path[] = $leaf;
  2293. }
  2294. $path[] = 'default';
  2295. $preset = _wp_array_get( $data, $path, null );
  2296. if ( ! isset( $preset ) ) {
  2297. continue;
  2298. }
  2299. $slugs_for_preset = array();
  2300. foreach ( $preset as $item ) {
  2301. if ( isset( $item['slug'] ) ) {
  2302. $slugs_for_preset[] = $item['slug'];
  2303. }
  2304. }
  2305. _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset );
  2306. }
  2307. return $slugs;
  2308. }
  2309. /**
  2310. * Gets a `default`'s preset name by a provided slug.
  2311. *
  2312. * @since 5.9.0
  2313. *
  2314. * @param string $slug The slug we want to find a match from default presets.
  2315. * @param array $base_path The path to inspect. It's 'settings' by default.
  2316. * @return string|null
  2317. */
  2318. protected function get_name_from_defaults( $slug, $base_path ) {
  2319. $path = $base_path;
  2320. $path[] = 'default';
  2321. $default_content = _wp_array_get( $this->theme_json, $path, null );
  2322. if ( ! $default_content ) {
  2323. return null;
  2324. }
  2325. foreach ( $default_content as $item ) {
  2326. if ( $slug === $item['slug'] ) {
  2327. return $item['name'];
  2328. }
  2329. }
  2330. return null;
  2331. }
  2332. /**
  2333. * Removes the preset values whose slug is equal to any of given slugs.
  2334. *
  2335. * @since 5.9.0
  2336. *
  2337. * @param array $node The node with the presets to validate.
  2338. * @param array $slugs The slugs that should not be overridden.
  2339. * @return array The new node.
  2340. */
  2341. protected static function filter_slugs( $node, $slugs ) {
  2342. if ( empty( $slugs ) ) {
  2343. return $node;
  2344. }
  2345. $new_node = array();
  2346. foreach ( $node as $value ) {
  2347. if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) {
  2348. $new_node[] = $value;
  2349. }
  2350. }
  2351. return $new_node;
  2352. }
  2353. /**
  2354. * Removes insecure data from theme.json.
  2355. *
  2356. * @since 5.9.0
  2357. *
  2358. * @param array $theme_json Structure to sanitize.
  2359. * @return array Sanitized structure.
  2360. */
  2361. public static function remove_insecure_properties( $theme_json ) {
  2362. $sanitized = array();
  2363. $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json );
  2364. $valid_block_names = array_keys( static::get_blocks_metadata() );
  2365. $valid_element_names = array_keys( static::ELEMENTS );
  2366. $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names );
  2367. $blocks_metadata = static::get_blocks_metadata();
  2368. $style_nodes = static::get_style_nodes( $theme_json, $blocks_metadata );
  2369. foreach ( $style_nodes as $metadata ) {
  2370. $input = _wp_array_get( $theme_json, $metadata['path'], array() );
  2371. if ( empty( $input ) ) {
  2372. continue;
  2373. }
  2374. $output = static::remove_insecure_styles( $input );
  2375. /*
  2376. * Get a reference to element name from path.
  2377. * $metadata['path'] = array( 'styles', 'elements', 'link' );
  2378. */
  2379. $current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ];
  2380. /*
  2381. * $output is stripped of pseudo selectors. Re-add and process them
  2382. * or insecure styles here.
  2383. */
  2384. // TODO: Replace array_key_exists() with isset() check once WordPress drops
  2385. // support for PHP 5.6. See https://core.trac.wordpress.org/ticket/57067.
  2386. if ( array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
  2387. foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) {
  2388. if ( isset( $input[ $pseudo_selector ] ) ) {
  2389. $output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] );
  2390. }
  2391. }
  2392. }
  2393. if ( ! empty( $output ) ) {
  2394. _wp_array_set( $sanitized, $metadata['path'], $output );
  2395. }
  2396. }
  2397. $setting_nodes = static::get_setting_nodes( $theme_json );
  2398. foreach ( $setting_nodes as $metadata ) {
  2399. $input = _wp_array_get( $theme_json, $metadata['path'], array() );
  2400. if ( empty( $input ) ) {
  2401. continue;
  2402. }
  2403. $output = static::remove_insecure_settings( $input );
  2404. if ( ! empty( $output ) ) {
  2405. _wp_array_set( $sanitized, $metadata['path'], $output );
  2406. }
  2407. }
  2408. if ( empty( $sanitized['styles'] ) ) {
  2409. unset( $theme_json['styles'] );
  2410. } else {
  2411. $theme_json['styles'] = $sanitized['styles'];
  2412. }
  2413. if ( empty( $sanitized['settings'] ) ) {
  2414. unset( $theme_json['settings'] );
  2415. } else {
  2416. $theme_json['settings'] = $sanitized['settings'];
  2417. }
  2418. return $theme_json;
  2419. }
  2420. /**
  2421. * Processes a setting node and returns the same node
  2422. * without the insecure settings.
  2423. *
  2424. * @since 5.9.0
  2425. *
  2426. * @param array $input Node to process.
  2427. * @return array
  2428. */
  2429. protected static function remove_insecure_settings( $input ) {
  2430. $output = array();
  2431. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  2432. foreach ( static::VALID_ORIGINS as $origin ) {
  2433. $path_with_origin = $preset_metadata['path'];
  2434. $path_with_origin[] = $origin;
  2435. $presets = _wp_array_get( $input, $path_with_origin, null );
  2436. if ( null === $presets ) {
  2437. continue;
  2438. }
  2439. $escaped_preset = array();
  2440. foreach ( $presets as $preset ) {
  2441. if (
  2442. esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] &&
  2443. sanitize_html_class( $preset['slug'] ) === $preset['slug']
  2444. ) {
  2445. $value = null;
  2446. if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
  2447. $value = $preset[ $preset_metadata['value_key'] ];
  2448. } elseif (
  2449. isset( $preset_metadata['value_func'] ) &&
  2450. is_callable( $preset_metadata['value_func'] )
  2451. ) {
  2452. $value = call_user_func( $preset_metadata['value_func'], $preset );
  2453. }
  2454. $preset_is_valid = true;
  2455. foreach ( $preset_metadata['properties'] as $property ) {
  2456. if ( ! static::is_safe_css_declaration( $property, $value ) ) {
  2457. $preset_is_valid = false;
  2458. break;
  2459. }
  2460. }
  2461. if ( $preset_is_valid ) {
  2462. $escaped_preset[] = $preset;
  2463. }
  2464. }
  2465. }
  2466. if ( ! empty( $escaped_preset ) ) {
  2467. _wp_array_set( $output, $path_with_origin, $escaped_preset );
  2468. }
  2469. }
  2470. }
  2471. return $output;
  2472. }
  2473. /**
  2474. * Processes a style node and returns the same node
  2475. * without the insecure styles.
  2476. *
  2477. * @since 5.9.0
  2478. *
  2479. * @param array $input Node to process.
  2480. * @return array
  2481. */
  2482. protected static function remove_insecure_styles( $input ) {
  2483. $output = array();
  2484. $declarations = static::compute_style_properties( $input );
  2485. foreach ( $declarations as $declaration ) {
  2486. if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) {
  2487. $path = static::PROPERTIES_METADATA[ $declaration['name'] ];
  2488. // Check the value isn't an array before adding so as to not
  2489. // double up shorthand and longhand styles.
  2490. $value = _wp_array_get( $input, $path, array() );
  2491. if ( ! is_array( $value ) ) {
  2492. _wp_array_set( $output, $path, $value );
  2493. }
  2494. }
  2495. }
  2496. return $output;
  2497. }
  2498. /**
  2499. * Checks that a declaration provided by the user is safe.
  2500. *
  2501. * @since 5.9.0
  2502. *
  2503. * @param string $property_name Property name in a CSS declaration, i.e. the `color` in `color: red`.
  2504. * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`.
  2505. * @return bool
  2506. */
  2507. protected static function is_safe_css_declaration( $property_name, $property_value ) {
  2508. $style_to_validate = $property_name . ': ' . $property_value;
  2509. $filtered = esc_html( safecss_filter_attr( $style_to_validate ) );
  2510. return ! empty( trim( $filtered ) );
  2511. }
  2512. /**
  2513. * Returns the raw data.
  2514. *
  2515. * @since 5.8.0
  2516. *
  2517. * @return array Raw data.
  2518. */
  2519. public function get_raw_data() {
  2520. return $this->theme_json;
  2521. }
  2522. /**
  2523. * Transforms the given editor settings according the
  2524. * add_theme_support format to the theme.json format.
  2525. *
  2526. * @since 5.8.0
  2527. *
  2528. * @param array $settings Existing editor settings.
  2529. * @return array Config that adheres to the theme.json schema.
  2530. */
  2531. public static function get_from_editor_settings( $settings ) {
  2532. $theme_settings = array(
  2533. 'version' => static::LATEST_SCHEMA,
  2534. 'settings' => array(),
  2535. );
  2536. // Deprecated theme supports.
  2537. if ( isset( $settings['disableCustomColors'] ) ) {
  2538. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  2539. $theme_settings['settings']['color'] = array();
  2540. }
  2541. $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors'];
  2542. }
  2543. if ( isset( $settings['disableCustomGradients'] ) ) {
  2544. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  2545. $theme_settings['settings']['color'] = array();
  2546. }
  2547. $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients'];
  2548. }
  2549. if ( isset( $settings['disableCustomFontSizes'] ) ) {
  2550. if ( ! isset( $theme_settings['settings']['typography'] ) ) {
  2551. $theme_settings['settings']['typography'] = array();
  2552. }
  2553. $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes'];
  2554. }
  2555. if ( isset( $settings['enableCustomLineHeight'] ) ) {
  2556. if ( ! isset( $theme_settings['settings']['typography'] ) ) {
  2557. $theme_settings['settings']['typography'] = array();
  2558. }
  2559. $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight'];
  2560. }
  2561. if ( isset( $settings['enableCustomUnits'] ) ) {
  2562. if ( ! isset( $theme_settings['settings']['spacing'] ) ) {
  2563. $theme_settings['settings']['spacing'] = array();
  2564. }
  2565. $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ?
  2566. array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) :
  2567. $settings['enableCustomUnits'];
  2568. }
  2569. if ( isset( $settings['colors'] ) ) {
  2570. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  2571. $theme_settings['settings']['color'] = array();
  2572. }
  2573. $theme_settings['settings']['color']['palette'] = $settings['colors'];
  2574. }
  2575. if ( isset( $settings['gradients'] ) ) {
  2576. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  2577. $theme_settings['settings']['color'] = array();
  2578. }
  2579. $theme_settings['settings']['color']['gradients'] = $settings['gradients'];
  2580. }
  2581. if ( isset( $settings['fontSizes'] ) ) {
  2582. $font_sizes = $settings['fontSizes'];
  2583. // Back-compatibility for presets without units.
  2584. foreach ( $font_sizes as $key => $font_size ) {
  2585. if ( is_numeric( $font_size['size'] ) ) {
  2586. $font_sizes[ $key ]['size'] = $font_size['size'] . 'px';
  2587. }
  2588. }
  2589. if ( ! isset( $theme_settings['settings']['typography'] ) ) {
  2590. $theme_settings['settings']['typography'] = array();
  2591. }
  2592. $theme_settings['settings']['typography']['fontSizes'] = $font_sizes;
  2593. }
  2594. if ( isset( $settings['enableCustomSpacing'] ) ) {
  2595. if ( ! isset( $theme_settings['settings']['spacing'] ) ) {
  2596. $theme_settings['settings']['spacing'] = array();
  2597. }
  2598. $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing'];
  2599. }
  2600. return $theme_settings;
  2601. }
  2602. /**
  2603. * Returns the current theme's wanted patterns(slugs) to be
  2604. * registered from Pattern Directory.
  2605. *
  2606. * @since 6.0.0
  2607. *
  2608. * @return string[]
  2609. */
  2610. public function get_patterns() {
  2611. if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) {
  2612. return $this->theme_json['patterns'];
  2613. }
  2614. return array();
  2615. }
  2616. /**
  2617. * Returns a valid theme.json as provided by a theme.
  2618. *
  2619. * Unlike get_raw_data() this returns the presets flattened, as provided by a theme.
  2620. * This also uses appearanceTools instead of their opt-ins if all of them are true.
  2621. *
  2622. * @since 6.0.0
  2623. *
  2624. * @return array
  2625. */
  2626. public function get_data() {
  2627. $output = $this->theme_json;
  2628. $nodes = static::get_setting_nodes( $output );
  2629. /**
  2630. * Flatten the theme & custom origins into a single one.
  2631. *
  2632. * For example, the following:
  2633. *
  2634. * {
  2635. * "settings": {
  2636. * "color": {
  2637. * "palette": {
  2638. * "theme": [ {} ],
  2639. * "custom": [ {} ]
  2640. * }
  2641. * }
  2642. * }
  2643. * }
  2644. *
  2645. * will be converted to:
  2646. *
  2647. * {
  2648. * "settings": {
  2649. * "color": {
  2650. * "palette": [ {} ]
  2651. * }
  2652. * }
  2653. * }
  2654. */
  2655. foreach ( $nodes as $node ) {
  2656. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  2657. $path = $node['path'];
  2658. foreach ( $preset_metadata['path'] as $preset_metadata_path ) {
  2659. $path[] = $preset_metadata_path;
  2660. }
  2661. $preset = _wp_array_get( $output, $path, null );
  2662. if ( null === $preset ) {
  2663. continue;
  2664. }
  2665. $items = array();
  2666. if ( isset( $preset['theme'] ) ) {
  2667. foreach ( $preset['theme'] as $item ) {
  2668. $slug = $item['slug'];
  2669. unset( $item['slug'] );
  2670. $items[ $slug ] = $item;
  2671. }
  2672. }
  2673. if ( isset( $preset['custom'] ) ) {
  2674. foreach ( $preset['custom'] as $item ) {
  2675. $slug = $item['slug'];
  2676. unset( $item['slug'] );
  2677. $items[ $slug ] = $item;
  2678. }
  2679. }
  2680. $flattened_preset = array();
  2681. foreach ( $items as $slug => $value ) {
  2682. $flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value );
  2683. }
  2684. _wp_array_set( $output, $path, $flattened_preset );
  2685. }
  2686. }
  2687. // If all of the static::APPEARANCE_TOOLS_OPT_INS are true,
  2688. // this code unsets them and sets 'appearanceTools' instead.
  2689. foreach ( $nodes as $node ) {
  2690. $all_opt_ins_are_set = true;
  2691. foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
  2692. $full_path = $node['path'];
  2693. foreach ( $opt_in_path as $opt_in_path_item ) {
  2694. $full_path[] = $opt_in_path_item;
  2695. }
  2696. // Use "unset prop" as a marker instead of "null" because
  2697. // "null" can be a valid value for some props (e.g. blockGap).
  2698. $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
  2699. if ( 'unset prop' === $opt_in_value ) {
  2700. $all_opt_ins_are_set = false;
  2701. break;
  2702. }
  2703. }
  2704. if ( $all_opt_ins_are_set ) {
  2705. $node_path_with_appearance_tools = $node['path'];
  2706. $node_path_with_appearance_tools[] = 'appearanceTools';
  2707. _wp_array_set( $output, $node_path_with_appearance_tools, true );
  2708. foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
  2709. $full_path = $node['path'];
  2710. foreach ( $opt_in_path as $opt_in_path_item ) {
  2711. $full_path[] = $opt_in_path_item;
  2712. }
  2713. // Use "unset prop" as a marker instead of "null" because
  2714. // "null" can be a valid value for some props (e.g. blockGap).
  2715. $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
  2716. if ( true !== $opt_in_value ) {
  2717. continue;
  2718. }
  2719. // The following could be improved to be path independent.
  2720. // At the moment it relies on a couple of assumptions:
  2721. //
  2722. // - all opt-ins having a path of size 2.
  2723. // - there's two sources of settings: the top-level and the block-level.
  2724. if (
  2725. ( 1 === count( $node['path'] ) ) &&
  2726. ( 'settings' === $node['path'][0] )
  2727. ) {
  2728. // Top-level settings.
  2729. unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] );
  2730. if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) {
  2731. unset( $output['settings'][ $opt_in_path[0] ] );
  2732. }
  2733. } elseif (
  2734. ( 3 === count( $node['path'] ) ) &&
  2735. ( 'settings' === $node['path'][0] ) &&
  2736. ( 'blocks' === $node['path'][1] )
  2737. ) {
  2738. // Block-level settings.
  2739. $block_name = $node['path'][2];
  2740. unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] );
  2741. if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) {
  2742. unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] );
  2743. }
  2744. }
  2745. }
  2746. }
  2747. }
  2748. wp_recursive_ksort( $output );
  2749. return $output;
  2750. }
  2751. /**
  2752. * Sets the spacingSizes array based on the spacingScale values from theme.json.
  2753. *
  2754. * @since 6.1.0
  2755. *
  2756. * @return null|void
  2757. */
  2758. public function set_spacing_sizes() {
  2759. $spacing_scale = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'spacingScale' ), array() );
  2760. if ( ! isset( $spacing_scale['steps'] )
  2761. || ! is_numeric( $spacing_scale['steps'] )
  2762. || ! isset( $spacing_scale['mediumStep'] )
  2763. || ! isset( $spacing_scale['unit'] )
  2764. || ! isset( $spacing_scale['operator'] )
  2765. || ! isset( $spacing_scale['increment'] )
  2766. || ! isset( $spacing_scale['steps'] )
  2767. || ! is_numeric( $spacing_scale['increment'] )
  2768. || ! is_numeric( $spacing_scale['mediumStep'] )
  2769. || ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) {
  2770. if ( ! empty( $spacing_scale ) ) {
  2771. trigger_error( __( 'Some of the theme.json settings.spacing.spacingScale values are invalid' ), E_USER_NOTICE );
  2772. }
  2773. return null;
  2774. }
  2775. // If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0.
  2776. if ( 0 === $spacing_scale['steps'] ) {
  2777. return null;
  2778. }
  2779. $unit = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] );
  2780. $current_step = $spacing_scale['mediumStep'];
  2781. $steps_mid_point = round( $spacing_scale['steps'] / 2, 0 );
  2782. $x_small_count = null;
  2783. $below_sizes = array();
  2784. $slug = 40;
  2785. $remainder = 0;
  2786. for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) {
  2787. if ( '+' === $spacing_scale['operator'] ) {
  2788. $current_step -= $spacing_scale['increment'];
  2789. } elseif ( $spacing_scale['increment'] > 1 ) {
  2790. $current_step /= $spacing_scale['increment'];
  2791. } else {
  2792. $current_step *= $spacing_scale['increment'];
  2793. }
  2794. if ( $current_step <= 0 ) {
  2795. $remainder = $below_midpoint_count;
  2796. break;
  2797. }
  2798. $below_sizes[] = array(
  2799. /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */
  2800. 'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ),
  2801. 'slug' => (string) $slug,
  2802. 'size' => round( $current_step, 2 ) . $unit,
  2803. );
  2804. if ( $below_midpoint_count === $steps_mid_point - 2 ) {
  2805. $x_small_count = 2;
  2806. }
  2807. if ( $below_midpoint_count < $steps_mid_point - 2 ) {
  2808. $x_small_count++;
  2809. }
  2810. $slug -= 10;
  2811. }
  2812. $below_sizes = array_reverse( $below_sizes );
  2813. $below_sizes[] = array(
  2814. 'name' => __( 'Medium' ),
  2815. 'slug' => '50',
  2816. 'size' => $spacing_scale['mediumStep'] . $unit,
  2817. );
  2818. $current_step = $spacing_scale['mediumStep'];
  2819. $x_large_count = null;
  2820. $above_sizes = array();
  2821. $slug = 60;
  2822. $steps_above = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder;
  2823. for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) {
  2824. $current_step = '+' === $spacing_scale['operator']
  2825. ? $current_step + $spacing_scale['increment']
  2826. : ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] );
  2827. $above_sizes[] = array(
  2828. /* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */
  2829. 'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ),
  2830. 'slug' => (string) $slug,
  2831. 'size' => round( $current_step, 2 ) . $unit,
  2832. );
  2833. if ( 1 === $above_midpoint_count ) {
  2834. $x_large_count = 2;
  2835. }
  2836. if ( $above_midpoint_count > 1 ) {
  2837. $x_large_count++;
  2838. }
  2839. $slug += 10;
  2840. }
  2841. $spacing_sizes = $below_sizes;
  2842. foreach ( $above_sizes as $above_sizes_item ) {
  2843. $spacing_sizes[] = $above_sizes_item;
  2844. }
  2845. // If there are 7 or less steps in the scale revert to numbers for labels instead of t-shirt sizes.
  2846. if ( $spacing_scale['steps'] <= 7 ) {
  2847. for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) {
  2848. $spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 );
  2849. }
  2850. }
  2851. _wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes );
  2852. }
  2853. }