soinproduction-gutenberg 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -150,3 +150,11 @@ their own theme tokens and Tailwind utilities. `level` remains supported, and
150
150
  headings without `textStyle` retain their existing section classes. Editor choices
151
151
  are saved separately under `__headings[fieldName]`; the text field stays a string.
152
152
  The portable PHP renderer resolves the same tag, class and defaults as React.
153
+
154
+ ### Isolated section styles
155
+
156
+ Set `"sectionStyles": "isolated"` in `kit.config.json` to compile each section's `styles.css` into a hashed asset. Preparation emits `src/sections/styles.manifest.generated.json` and `public/kit/sections/`. Keep those public assets available alongside a deployed Next build. The shared stylesheet retains theme declarations; selectors and keyframes load per rendered section. Existing projects retain global imports unless they opt in.
157
+
158
+ The existing `Section` root receives `data-site-section="site/slug"`. Compiled selectors are guarded by that owner without increasing specificity; keyframe names are unique to the section. Document state ancestors such as `html[data-motion]` still work. Keep reset rules, fonts and global custom properties in the shared entry. Use unique names for section `@theme` tokens; global directives such as `@font-face`, `@property`, `@utility` and `@apply` are rejected inside isolated section styles.
159
+
160
+ In a custom React block renderer, look up the actual block name in the generated manifest and render `<link rel="stylesheet" href={asset.href} precedence="site-sections" />` beside its View. React hoists and deduplicates the stylesheet and waits for it before revealing the section. For WordPress browser islands use `site.runtime.sectionStyleBase + asset.file` when that base is supplied. Do not import every section stylesheet from a registry. Gutenberg receives all isolated section styles so newly inserted sections work immediately; the WordPress build copies the assets and enqueues only section names found in the current page and its layout slots, including synced blocks.
@@ -1,7 +1,7 @@
1
1
  <?php
2
2
  /** Public compiled assets only; no WordPress bootstrap or source-file access. */
3
3
  $asset = ltrim( $_SERVER['PATH_INFO'] ?? '', '/' );
4
- if ( ! preg_match( '~^(?:runtime\.js|site\.css|chunks/[A-Za-z0-9_-]+\.js|images/[A-Za-z0-9_-]+\.png)$~D', $asset ) ) {
4
+ if ( ! preg_match( '~^(?:runtime\.js|site\.css|chunks/[A-Za-z0-9_-]+\.js|images/[A-Za-z0-9_-]+\.png|sections/[a-z0-9-]+\.css|sections/assets/[a-f0-9]{12}\.(?:png|jpe?g|webp|avif|gif|svg|woff2?))$~D', $asset ) ) {
5
5
  http_response_code( 404 );
6
6
  exit;
7
7
  }
@@ -14,13 +14,14 @@
14
14
  $etag = '"' . filemtime( $file ) . '-' . filesize( $file ) . ( $gzip ? '-gzip' : '' ) . '"';
15
15
  header( 'ETag: ' . $etag );
16
16
  header( 'Vary: Accept-Encoding' );
17
- header( 'Cache-Control: public, max-age=' . ( str_starts_with( $asset, 'chunks/' ) ? '31536000, immutable' : '3600' ) );
17
+ header( 'Cache-Control: public, max-age=' . ( (str_starts_with( $asset, 'chunks/' ) || str_starts_with($asset, 'sections/')) ? '31536000, immutable' : '3600' ) );
18
18
  header( 'X-Content-Type-Options: nosniff' );
19
19
  if ( ( $_SERVER['HTTP_IF_NONE_MATCH'] ?? '' ) === $etag ) {
20
20
  http_response_code( 304 );
21
21
  exit;
22
22
  }
23
- header( 'Content-Type: ' . ( str_ends_with( $asset, '.js' ) ? 'application/javascript; charset=UTF-8' : ( str_ends_with( $asset, '.css' ) ? 'text/css; charset=UTF-8' : 'image/png' ) ) );
23
+ $types = ['js'=>'application/javascript; charset=UTF-8','css'=>'text/css; charset=UTF-8','png'=>'image/png','jpg'=>'image/jpeg','jpeg'=>'image/jpeg','gif'=>'image/gif','svg'=>'image/svg+xml','webp'=>'image/webp','avif'=>'image/avif','woff'=>'font/woff','woff2'=>'font/woff2'];
24
+ header('Content-Type: ' . $types[pathinfo($asset, PATHINFO_EXTENSION)]);
24
25
  if ( $gzip ) {
25
26
  header( 'Content-Encoding: gzip' );
26
27
  $file .= '.gz';
@@ -29,6 +29,7 @@ function describe(node: ReactNode): any[] {
29
29
 
30
30
  export function section(meta: any, View: () => ReactNode) {
31
31
  const template = describe(View());
32
+ const mark=(nodes:any[])=>{for(const node of nodes){if(node.type==='Section')node.props['data-site-section']='site/'+meta.slug;mark(node.children??[]);}};mark(template);
32
33
  const staticTypes = new Set(['#text','Section','Text','Heading','Paragraphs','Image','Icon','Background','Buttons','SocialLinks','Button','Show','Toggle','Choice']);
33
34
  const isStatic = (nodes:any[]):boolean => nodes.every(node => (staticTypes.has(node.type) || /^[a-z]/.test(node.type)) && isStatic(node.children ?? []));
34
35
  return {name: 'site/' + meta.slug, title: meta.title, template, static: isStatic(template)};
@@ -208,7 +208,7 @@ function node(array $node,array $context): string {
208
208
  if(!array_key_exists('icon',$settings))$icon='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 9 6 6 6-6"></path></svg>';
209
209
  elseif($settings['icon'])$icon=node(['type'=>'Icon','props'=>['name'=>'indicator']],array_replace($context,['data'=>['indicator'=>$settings['icon']]]));
210
210
  return tag('summary',['class'=>$class],nodes($children,$context).($icon?tag('span',['data-disclosure-icon'=>true],$icon):''));
211
- case 'Section':if(!empty($p['when'])&&empty($data[$p['when']]))return '';return tag('section',['id'=>$data['sectionId']??null,'class'=>$class],nodes($children,$context));
211
+ case 'Section':if(!empty($p['when'])&&empty($data[$p['when']]))return '';return tag('section',['id'=>$data['sectionId']??null,'class'=>$class,'data-site-section'=>$p['data-site-section']??null],nodes($children,$context));
212
212
  case 'Text':return tag('p',['class'=>$class],wp_kses_post((string)($value??'')));
213
213
  case 'Heading':
214
214
  $valid_tag=static fn($v)=>is_string($v)&&preg_match('/^(?:h[1-6]|p|span)$/D',$v);$valid_style=static fn($v)=>is_string($v)&&preg_match('/^h[1-6]$/D',$v);$settings=$data['__headings'][$p['name']??'']??[];
@@ -10,11 +10,11 @@ import { useClasses } from '../../shared/index.js';
10
10
  export function Section({ when, children, ...classes }: Classes & { when?: string; children: ReactNode }) {
11
11
  const className = useClasses(classes);
12
12
  const values = useValues();
13
- const editor = useFieldScope().edit;
13
+ const {edit:editor,blockName} = useFieldScope();
14
14
  const anchor = useSectionAnchor();
15
15
  if (when && !editor && !(Array.isArray(values[when]) ? values[when].length : values[when])) return null;
16
16
  return (
17
- <section id={anchor} className={className}>
17
+ <section id={anchor} className={className} data-site-section={blockName}>
18
18
  {children}
19
19
  </section>
20
20
  );
@@ -1,7 +1,7 @@
1
1
  <?php
2
2
  /** Public compiled assets only; no WordPress bootstrap or source-file access. */
3
3
  $asset = ltrim( $_SERVER['PATH_INFO'] ?? '', '/' );
4
- if ( ! preg_match( '~^(?:runtime\.js|site\.css|chunks/[A-Za-z0-9_-]+\.js|images/[A-Za-z0-9_-]+\.png)$~D', $asset ) ) {
4
+ if ( ! preg_match( '~^(?:runtime\.js|site\.css|chunks/[A-Za-z0-9_-]+\.js|images/[A-Za-z0-9_-]+\.png|sections/[a-z0-9-]+\.css|sections/assets/[a-f0-9]{12}\.(?:png|jpe?g|webp|avif|gif|svg|woff2?))$~D', $asset ) ) {
5
5
  http_response_code( 404 );
6
6
  exit;
7
7
  }
@@ -14,13 +14,14 @@
14
14
  $etag = '"' . filemtime( $file ) . '-' . filesize( $file ) . ( $gzip ? '-gzip' : '' ) . '"';
15
15
  header( 'ETag: ' . $etag );
16
16
  header( 'Vary: Accept-Encoding' );
17
- header( 'Cache-Control: public, max-age=' . ( str_starts_with( $asset, 'chunks/' ) ? '31536000, immutable' : '3600' ) );
17
+ header( 'Cache-Control: public, max-age=' . ( (str_starts_with( $asset, 'chunks/' ) || str_starts_with($asset, 'sections/')) ? '31536000, immutable' : '3600' ) );
18
18
  header( 'X-Content-Type-Options: nosniff' );
19
19
  if ( ( $_SERVER['HTTP_IF_NONE_MATCH'] ?? '' ) === $etag ) {
20
20
  http_response_code( 304 );
21
21
  exit;
22
22
  }
23
- header( 'Content-Type: ' . ( str_ends_with( $asset, '.js' ) ? 'application/javascript; charset=UTF-8' : ( str_ends_with( $asset, '.css' ) ? 'text/css; charset=UTF-8' : 'image/png' ) ) );
23
+ $types = ['js'=>'application/javascript; charset=UTF-8','css'=>'text/css; charset=UTF-8','png'=>'image/png','jpg'=>'image/jpeg','jpeg'=>'image/jpeg','gif'=>'image/gif','svg'=>'image/svg+xml','webp'=>'image/webp','avif'=>'image/avif','woff'=>'font/woff','woff2'=>'font/woff2'];
24
+ header('Content-Type: ' . $types[pathinfo($asset, PATHINFO_EXTENSION)]);
24
25
  if ( $gzip ) {
25
26
  header( 'Content-Encoding: gzip' );
26
27
  $file .= '.gz';
@@ -16,6 +16,13 @@ function describe(node) {
16
16
  }
17
17
  function section(meta, View) {
18
18
  const template = describe(View());
19
+ const mark = (nodes) => {
20
+ for (const node of nodes) {
21
+ if (node.type === "Section") node.props["data-site-section"] = "site/" + meta.slug;
22
+ mark(node.children ?? []);
23
+ }
24
+ };
25
+ mark(template);
19
26
  const staticTypes = /* @__PURE__ */ new Set(["#text", "Section", "Text", "Heading", "Paragraphs", "Image", "Icon", "Background", "Buttons", "SocialLinks", "Button", "Show", "Toggle", "Choice"]);
20
27
  const isStatic = (nodes) => nodes.every((node) => (staticTypes.has(node.type) || /^[a-z]/.test(node.type)) && isStatic(node.children ?? []));
21
28
  return { name: "site/" + meta.slug, title: meta.title, template, static: isStatic(template) };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../adapters/wordpress/blueprint.ts"],
4
- "sourcesContent": ["import {Children, Fragment, isValidElement, type ReactNode} from 'react';\n\nconst marker = (name: string) => Object.assign((_props: any) => null, {kitName: name});\nexport const Section = marker('Section'), Text = marker('Text'), Heading = marker('Heading'),\n Paragraphs = marker('Paragraphs'), Image = marker('Image'), Icon = marker('Icon'),\n Background = marker('Background'), Buttons = marker('Buttons'), SocialLinks = marker('SocialLinks'), Button = marker('Button'), List = marker('List'),\n PricingPlans = marker('PricingPlans'), ReviewsCarousel = marker('ReviewsCarousel'), Form = marker('Form'), Records = marker('Records'), Categories = marker('Categories'), RecordEdit = marker('RecordEdit'), RecordImage = marker('RecordImage'),\n RecordDate = marker('RecordDate'), RecordTitle = marker('RecordTitle'), RecordExcerpt = marker('RecordExcerpt'), RecordLink = marker('RecordLink'),\n RecordIndex = marker('RecordIndex'), Drag = marker('Drag'), Cols = marker('Cols'), Toggle = marker('Toggle'),\n Choice = marker('Choice'), Show = marker('Show'), Area = marker('Area'), Gallery = marker('Gallery'),\n Accordion = marker('Accordion'), AccordionItem = marker('AccordionItem'), AccordionTrigger = marker('AccordionTrigger'), AccordionContent = marker('AccordionContent'), AccordionProgress = marker('AccordionProgress'),\n Slider = marker('Slider'), SliderButton = marker('SliderButton'), SliderPagination = marker('SliderPagination'), RecordText = marker('RecordText'), RecordContent = marker('RecordContent'), Media = marker('Media');\n\nfunction describe(node: ReactNode): any[] {\n return Children.toArray(node).flatMap(child => {\n if (!isValidElement(child)) return [{type: '#text', value: String(child)}];\n if (child.type === Fragment) return describe((child.props as any).children);\n const props = {...child.props as any};\n delete props.children;\n const type = typeof child.type === 'string' ? child.type : (child.type as any).kitName;\n // Stateful project components mount through the existing browser island.\n // Preserve declarative children as the PHP fallback, without serializing callback props.\n if (!type) return [{type: 'ClientComponent', props: {}, children: describe((child.props as any).children)}];\n if (type === 'Categories' && props.tab !== undefined) props.tab = describe(props.tab);\n for (const [key, value] of Object.entries(props)) if (typeof value === 'function') throw new Error(`WordPress compiler: callback ${key} cannot be serialized`);\n return [{type, props, children: describe((child.props as any).children)}];\n });\n}\n\nexport function section(meta: any, View: () => ReactNode) {\n const template = describe(View());\n const staticTypes = new Set(['#text','Section','Text','Heading','Paragraphs','Image','Icon','Background','Buttons','SocialLinks','Button','Show','Toggle','Choice']);\n const isStatic = (nodes:any[]):boolean => nodes.every(node => (staticTypes.has(node.type) || /^[a-z]/.test(node.type)) && isStatic(node.children ?? []));\n return {name: 'site/' + meta.slug, title: meta.title, template, static: isStatic(template)};\n}\n"],
5
- "mappings": "AAAA,SAAQ,UAAU,UAAU,sBAAqC;AAEjE,MAAM,SAAS,CAAC,SAAiB,OAAO,OAAO,CAAC,WAAgB,MAAM,EAAC,SAAS,KAAI,CAAC;AAC9E,MAAM,UAAU,OAAO,SAAS,GAAG,OAAO,OAAO,MAAM,GAAG,UAAU,OAAO,SAAS,GACvF,aAAa,OAAO,YAAY,GAAG,QAAQ,OAAO,OAAO,GAAG,OAAO,OAAO,MAAM,GAChF,aAAa,OAAO,YAAY,GAAG,UAAU,OAAO,SAAS,GAAG,cAAc,OAAO,aAAa,GAAG,SAAS,OAAO,QAAQ,GAAG,OAAO,OAAO,MAAM,GACpJ,eAAe,OAAO,cAAc,GAAG,kBAAkB,OAAO,iBAAiB,GAAG,OAAO,OAAO,MAAM,GAAG,UAAU,OAAO,SAAS,GAAG,aAAa,OAAO,YAAY,GAAG,aAAa,OAAO,YAAY,GAAG,cAAc,OAAO,aAAa,GAChP,aAAa,OAAO,YAAY,GAAG,cAAc,OAAO,aAAa,GAAG,gBAAgB,OAAO,eAAe,GAAG,aAAa,OAAO,YAAY,GACjJ,cAAc,OAAO,aAAa,GAAG,OAAO,OAAO,MAAM,GAAG,OAAO,OAAO,MAAM,GAAG,SAAS,OAAO,QAAQ,GAC3G,SAAS,OAAO,QAAQ,GAAG,OAAO,OAAO,MAAM,GAAG,OAAO,OAAO,MAAM,GAAG,UAAU,OAAO,SAAS,GACnG,YAAY,OAAO,WAAW,GAAG,gBAAgB,OAAO,eAAe,GAAG,mBAAmB,OAAO,kBAAkB,GAAG,mBAAmB,OAAO,kBAAkB,GAAG,oBAAoB,OAAO,mBAAmB,GACtN,SAAS,OAAO,QAAQ,GAAG,eAAe,OAAO,cAAc,GAAG,mBAAmB,OAAO,kBAAkB,GAAG,aAAa,OAAO,YAAY,GAAG,gBAAgB,OAAO,eAAe,GAAG,QAAQ,OAAO,OAAO;AAEvN,SAAS,SAAS,MAAwB;AACtC,SAAO,SAAS,QAAQ,IAAI,EAAE,QAAQ,WAAS;AAC3C,QAAI,CAAC,eAAe,KAAK,EAAG,QAAO,CAAC,EAAC,MAAM,SAAS,OAAO,OAAO,KAAK,EAAC,CAAC;AACzE,QAAI,MAAM,SAAS,SAAU,QAAO,SAAU,MAAM,MAAc,QAAQ;AAC1E,UAAM,QAAQ,EAAC,GAAG,MAAM,MAAY;AACpC,WAAO,MAAM;AACb,UAAM,OAAO,OAAO,MAAM,SAAS,WAAW,MAAM,OAAQ,MAAM,KAAa;AAG/E,QAAI,CAAC,KAAM,QAAO,CAAC,EAAC,MAAM,mBAAmB,OAAO,CAAC,GAAG,UAAU,SAAU,MAAM,MAAc,QAAQ,EAAC,CAAC;AAC1G,QAAI,SAAS,gBAAgB,MAAM,QAAQ,OAAW,OAAM,MAAM,SAAS,MAAM,GAAG;AACpF,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,EAAG,KAAI,OAAO,UAAU,WAAY,OAAM,IAAI,MAAM,gCAAgC,GAAG,uBAAuB;AAC7J,WAAO,CAAC,EAAC,MAAM,OAAO,UAAU,SAAU,MAAM,MAAc,QAAQ,EAAC,CAAC;AAAA,EAC5E,CAAC;AACL;AAEO,SAAS,QAAQ,MAAW,MAAuB;AACtD,QAAM,WAAW,SAAS,KAAK,CAAC;AAChC,QAAM,cAAc,oBAAI,IAAI,CAAC,SAAQ,WAAU,QAAO,WAAU,cAAa,SAAQ,QAAO,cAAa,WAAU,eAAc,UAAS,QAAO,UAAS,QAAQ,CAAC;AACnK,QAAM,WAAW,CAAC,UAAwB,MAAM,MAAM,WAAS,YAAY,IAAI,KAAK,IAAI,KAAK,SAAS,KAAK,KAAK,IAAI,MAAM,SAAS,KAAK,YAAY,CAAC,CAAC,CAAC;AACvJ,SAAO,EAAC,MAAM,UAAU,KAAK,MAAM,OAAO,KAAK,OAAO,UAAU,QAAQ,SAAS,QAAQ,EAAC;AAC9F;",
4
+ "sourcesContent": ["import {Children, Fragment, isValidElement, type ReactNode} from 'react';\n\nconst marker = (name: string) => Object.assign((_props: any) => null, {kitName: name});\nexport const Section = marker('Section'), Text = marker('Text'), Heading = marker('Heading'),\n Paragraphs = marker('Paragraphs'), Image = marker('Image'), Icon = marker('Icon'),\n Background = marker('Background'), Buttons = marker('Buttons'), SocialLinks = marker('SocialLinks'), Button = marker('Button'), List = marker('List'),\n PricingPlans = marker('PricingPlans'), ReviewsCarousel = marker('ReviewsCarousel'), Form = marker('Form'), Records = marker('Records'), Categories = marker('Categories'), RecordEdit = marker('RecordEdit'), RecordImage = marker('RecordImage'),\n RecordDate = marker('RecordDate'), RecordTitle = marker('RecordTitle'), RecordExcerpt = marker('RecordExcerpt'), RecordLink = marker('RecordLink'),\n RecordIndex = marker('RecordIndex'), Drag = marker('Drag'), Cols = marker('Cols'), Toggle = marker('Toggle'),\n Choice = marker('Choice'), Show = marker('Show'), Area = marker('Area'), Gallery = marker('Gallery'),\n Accordion = marker('Accordion'), AccordionItem = marker('AccordionItem'), AccordionTrigger = marker('AccordionTrigger'), AccordionContent = marker('AccordionContent'), AccordionProgress = marker('AccordionProgress'),\n Slider = marker('Slider'), SliderButton = marker('SliderButton'), SliderPagination = marker('SliderPagination'), RecordText = marker('RecordText'), RecordContent = marker('RecordContent'), Media = marker('Media');\n\nfunction describe(node: ReactNode): any[] {\n return Children.toArray(node).flatMap(child => {\n if (!isValidElement(child)) return [{type: '#text', value: String(child)}];\n if (child.type === Fragment) return describe((child.props as any).children);\n const props = {...child.props as any};\n delete props.children;\n const type = typeof child.type === 'string' ? child.type : (child.type as any).kitName;\n // Stateful project components mount through the existing browser island.\n // Preserve declarative children as the PHP fallback, without serializing callback props.\n if (!type) return [{type: 'ClientComponent', props: {}, children: describe((child.props as any).children)}];\n if (type === 'Categories' && props.tab !== undefined) props.tab = describe(props.tab);\n for (const [key, value] of Object.entries(props)) if (typeof value === 'function') throw new Error(`WordPress compiler: callback ${key} cannot be serialized`);\n return [{type, props, children: describe((child.props as any).children)}];\n });\n}\n\nexport function section(meta: any, View: () => ReactNode) {\n const template = describe(View());\n const mark=(nodes:any[])=>{for(const node of nodes){if(node.type==='Section')node.props['data-site-section']='site/'+meta.slug;mark(node.children??[]);}};mark(template);\n const staticTypes = new Set(['#text','Section','Text','Heading','Paragraphs','Image','Icon','Background','Buttons','SocialLinks','Button','Show','Toggle','Choice']);\n const isStatic = (nodes:any[]):boolean => nodes.every(node => (staticTypes.has(node.type) || /^[a-z]/.test(node.type)) && isStatic(node.children ?? []));\n return {name: 'site/' + meta.slug, title: meta.title, template, static: isStatic(template)};\n}\n"],
5
+ "mappings": "AAAA,SAAQ,UAAU,UAAU,sBAAqC;AAEjE,MAAM,SAAS,CAAC,SAAiB,OAAO,OAAO,CAAC,WAAgB,MAAM,EAAC,SAAS,KAAI,CAAC;AAC9E,MAAM,UAAU,OAAO,SAAS,GAAG,OAAO,OAAO,MAAM,GAAG,UAAU,OAAO,SAAS,GACvF,aAAa,OAAO,YAAY,GAAG,QAAQ,OAAO,OAAO,GAAG,OAAO,OAAO,MAAM,GAChF,aAAa,OAAO,YAAY,GAAG,UAAU,OAAO,SAAS,GAAG,cAAc,OAAO,aAAa,GAAG,SAAS,OAAO,QAAQ,GAAG,OAAO,OAAO,MAAM,GACpJ,eAAe,OAAO,cAAc,GAAG,kBAAkB,OAAO,iBAAiB,GAAG,OAAO,OAAO,MAAM,GAAG,UAAU,OAAO,SAAS,GAAG,aAAa,OAAO,YAAY,GAAG,aAAa,OAAO,YAAY,GAAG,cAAc,OAAO,aAAa,GAChP,aAAa,OAAO,YAAY,GAAG,cAAc,OAAO,aAAa,GAAG,gBAAgB,OAAO,eAAe,GAAG,aAAa,OAAO,YAAY,GACjJ,cAAc,OAAO,aAAa,GAAG,OAAO,OAAO,MAAM,GAAG,OAAO,OAAO,MAAM,GAAG,SAAS,OAAO,QAAQ,GAC3G,SAAS,OAAO,QAAQ,GAAG,OAAO,OAAO,MAAM,GAAG,OAAO,OAAO,MAAM,GAAG,UAAU,OAAO,SAAS,GACnG,YAAY,OAAO,WAAW,GAAG,gBAAgB,OAAO,eAAe,GAAG,mBAAmB,OAAO,kBAAkB,GAAG,mBAAmB,OAAO,kBAAkB,GAAG,oBAAoB,OAAO,mBAAmB,GACtN,SAAS,OAAO,QAAQ,GAAG,eAAe,OAAO,cAAc,GAAG,mBAAmB,OAAO,kBAAkB,GAAG,aAAa,OAAO,YAAY,GAAG,gBAAgB,OAAO,eAAe,GAAG,QAAQ,OAAO,OAAO;AAEvN,SAAS,SAAS,MAAwB;AACtC,SAAO,SAAS,QAAQ,IAAI,EAAE,QAAQ,WAAS;AAC3C,QAAI,CAAC,eAAe,KAAK,EAAG,QAAO,CAAC,EAAC,MAAM,SAAS,OAAO,OAAO,KAAK,EAAC,CAAC;AACzE,QAAI,MAAM,SAAS,SAAU,QAAO,SAAU,MAAM,MAAc,QAAQ;AAC1E,UAAM,QAAQ,EAAC,GAAG,MAAM,MAAY;AACpC,WAAO,MAAM;AACb,UAAM,OAAO,OAAO,MAAM,SAAS,WAAW,MAAM,OAAQ,MAAM,KAAa;AAG/E,QAAI,CAAC,KAAM,QAAO,CAAC,EAAC,MAAM,mBAAmB,OAAO,CAAC,GAAG,UAAU,SAAU,MAAM,MAAc,QAAQ,EAAC,CAAC;AAC1G,QAAI,SAAS,gBAAgB,MAAM,QAAQ,OAAW,OAAM,MAAM,SAAS,MAAM,GAAG;AACpF,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,EAAG,KAAI,OAAO,UAAU,WAAY,OAAM,IAAI,MAAM,gCAAgC,GAAG,uBAAuB;AAC7J,WAAO,CAAC,EAAC,MAAM,OAAO,UAAU,SAAU,MAAM,MAAc,QAAQ,EAAC,CAAC;AAAA,EAC5E,CAAC;AACL;AAEO,SAAS,QAAQ,MAAW,MAAuB;AACtD,QAAM,WAAW,SAAS,KAAK,CAAC;AAChC,QAAM,OAAK,CAAC,UAAc;AAAC,eAAU,QAAQ,OAAM;AAAC,UAAG,KAAK,SAAO,UAAU,MAAK,MAAM,mBAAmB,IAAE,UAAQ,KAAK;AAAK,WAAK,KAAK,YAAU,CAAC,CAAC;AAAA,IAAE;AAAA,EAAC;AAAE,OAAK,QAAQ;AACvK,QAAM,cAAc,oBAAI,IAAI,CAAC,SAAQ,WAAU,QAAO,WAAU,cAAa,SAAQ,QAAO,cAAa,WAAU,eAAc,UAAS,QAAO,UAAS,QAAQ,CAAC;AACnK,QAAM,WAAW,CAAC,UAAwB,MAAM,MAAM,WAAS,YAAY,IAAI,KAAK,IAAI,KAAK,SAAS,KAAK,KAAK,IAAI,MAAM,SAAS,KAAK,YAAY,CAAC,CAAC,CAAC;AACvJ,SAAO,EAAC,MAAM,UAAU,KAAK,MAAM,OAAO,KAAK,OAAO,UAAU,QAAQ,SAAS,QAAQ,EAAC;AAC9F;",
6
6
  "names": []
7
7
  }
@@ -208,7 +208,7 @@ function node(array $node,array $context): string {
208
208
  if(!array_key_exists('icon',$settings))$icon='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 9 6 6 6-6"></path></svg>';
209
209
  elseif($settings['icon'])$icon=node(['type'=>'Icon','props'=>['name'=>'indicator']],array_replace($context,['data'=>['indicator'=>$settings['icon']]]));
210
210
  return tag('summary',['class'=>$class],nodes($children,$context).($icon?tag('span',['data-disclosure-icon'=>true],$icon):''));
211
- case 'Section':if(!empty($p['when'])&&empty($data[$p['when']]))return '';return tag('section',['id'=>$data['sectionId']??null,'class'=>$class],nodes($children,$context));
211
+ case 'Section':if(!empty($p['when'])&&empty($data[$p['when']]))return '';return tag('section',['id'=>$data['sectionId']??null,'class'=>$class,'data-site-section'=>$p['data-site-section']??null],nodes($children,$context));
212
212
  case 'Text':return tag('p',['class'=>$class],wp_kses_post((string)($value??'')));
213
213
  case 'Heading':
214
214
  $valid_tag=static fn($v)=>is_string($v)&&preg_match('/^(?:h[1-6]|p|span)$/D',$v);$valid_style=static fn($v)=>is_string($v)&&preg_match('/^h[1-6]$/D',$v);$settings=$data['__headings'][$p['name']??'']??[];
@@ -7,10 +7,10 @@ import { useClasses } from "../../shared/index.js";
7
7
  function Section({ when, children, ...classes }) {
8
8
  const className = useClasses(classes);
9
9
  const values = useValues();
10
- const editor = useFieldScope().edit;
10
+ const { edit: editor, blockName } = useFieldScope();
11
11
  const anchor = useSectionAnchor();
12
12
  if (when && !editor && !(Array.isArray(values[when]) ? values[when].length : values[when])) return null;
13
- return /* @__PURE__ */ jsx("section", { id: anchor, className, children });
13
+ return /* @__PURE__ */ jsx("section", { id: anchor, className, "data-site-section": blockName, children });
14
14
  }
15
15
  export {
16
16
  Section
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../components/section/index.tsx"],
4
- "sourcesContent": ["'use client';\nimport { useValues } from '../../core/fields/render.js';\nimport { useFieldScope } from '../../core/fields/render.js';\nimport { useSectionAnchor } from '../../core/modules/section.js';\nimport type { ReactNode } from 'react';\nimport { Classes } from '../../shared/index.js';\nimport { useClasses } from '../../shared/index.js';\n\n/** Root of every section: connects the anchor from \"Section settings\". */\nexport function Section({ when, children, ...classes }: Classes & { when?: string; children: ReactNode }) {\n const className = useClasses(classes);\n const values = useValues();\n const editor = useFieldScope().edit;\n const anchor = useSectionAnchor();\n if (when && !editor && !(Array.isArray(values[when]) ? values[when].length : values[when])) return null;\n return (\n <section id={anchor} className={className}>\n {children}\n </section>\n );\n}\n"],
5
- "mappings": ";AAgBI;AAfJ,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AAGjC,SAAS,kBAAkB;AAGpB,SAAS,QAAQ,EAAE,MAAM,UAAU,GAAG,QAAQ,GAAqD;AACxG,QAAM,YAAY,WAAW,OAAO;AACpC,QAAM,SAAS,UAAU;AACzB,QAAM,SAAS,cAAc,EAAE;AAC/B,QAAM,SAAS,iBAAiB;AAChC,MAAI,QAAQ,CAAC,UAAU,EAAE,MAAM,QAAQ,OAAO,IAAI,CAAC,IAAI,OAAO,IAAI,EAAE,SAAS,OAAO,IAAI,GAAI,QAAO;AACnG,SACE,oBAAC,aAAQ,IAAI,QAAQ,WAClB,UACH;AAEJ;",
4
+ "sourcesContent": ["'use client';\nimport { useValues } from '../../core/fields/render.js';\nimport { useFieldScope } from '../../core/fields/render.js';\nimport { useSectionAnchor } from '../../core/modules/section.js';\nimport type { ReactNode } from 'react';\nimport { Classes } from '../../shared/index.js';\nimport { useClasses } from '../../shared/index.js';\n\n/** Root of every section: connects the anchor from \"Section settings\". */\nexport function Section({ when, children, ...classes }: Classes & { when?: string; children: ReactNode }) {\n const className = useClasses(classes);\n const values = useValues();\n const {edit:editor,blockName} = useFieldScope();\n const anchor = useSectionAnchor();\n if (when && !editor && !(Array.isArray(values[when]) ? values[when].length : values[when])) return null;\n return (\n <section id={anchor} className={className} data-site-section={blockName}>\n {children}\n </section>\n );\n}\n"],
5
+ "mappings": ";AAgBI;AAfJ,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AAGjC,SAAS,kBAAkB;AAGpB,SAAS,QAAQ,EAAE,MAAM,UAAU,GAAG,QAAQ,GAAqD;AACxG,QAAM,YAAY,WAAW,OAAO;AACpC,QAAM,SAAS,UAAU;AACzB,QAAM,EAAC,MAAK,QAAO,UAAS,IAAI,cAAc;AAC9C,QAAM,SAAS,iBAAiB;AAChC,MAAI,QAAQ,CAAC,UAAU,EAAE,MAAM,QAAQ,OAAO,IAAI,CAAC,IAAI,OAAO,IAAI,EAAE,SAAS,OAAO,IAAI,GAAI,QAAO;AACnG,SACE,oBAAC,aAAQ,IAAI,QAAQ,WAAsB,qBAAmB,WAC3D,UACH;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,7 @@ import { build } from 'esbuild';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import postcss from 'postcss';
6
+ import {sectionEditorCss} from './section-styles.mjs';
6
7
  import tailwind from '@tailwindcss/postcss';
7
8
  import breakpoints from './breakpoints.cjs';
8
9
  import remDimensions from './rem-css.cjs';
@@ -63,7 +64,7 @@ await build({
63
64
  loader: { '.css': 'empty' },
64
65
  });
65
66
  // Isolate content CSS from the admin controls, including the reset and theme variables.
66
- const css = fs.readFileSync('app/globals.css', 'utf8');
67
+ const css = fs.readFileSync('app/globals.css', 'utf8')+'\n'+sectionEditorCss(process.cwd(),path.resolve(output));
67
68
  const result = await postcss([breakpoints(), tailwind(), remDimensions()]).process(css, { from: path.resolve('app/globals.css') });
68
69
  const tree = postcss.parse(result.css);
69
70
  // WordPress block wrappers use unlayered rules. Keep our scoped utilities at the
@@ -1,5 +1,6 @@
1
1
  import {syncKit} from './sync-kit.mjs';
2
2
  import fs from 'node:fs';
3
+ import {publishSectionStyles} from './section-styles.mjs';
3
4
  import {gzipSync} from 'node:zlib';
4
5
  import path from 'node:path';
5
6
  import {build} from 'esbuild';
@@ -13,6 +14,7 @@ import {syncBlocks} from './sync-blocks.mjs';
13
14
  syncSections();
14
15
  syncKit();syncBlocks();
15
16
  const output=path.resolve('../build/wordpress');fs.rmSync(output,{recursive:true,force:true});fs.mkdirSync(output,{recursive:true});
17
+ publishSectionStyles(process.cwd(),output);
16
18
  const compiled=await build({stdin:{contents:"export {sections} from './src/sections/index.generated';",resolveDir:process.cwd()},bundle:true,platform:'node',format:'cjs',write:false,jsx:'automatic',tsconfig:'tsconfig.json',plugins:[{name:'wordpress-blueprint-entry',setup(builder){builder.onResolve({filter:/^@kit$/},()=>({path:path.resolve('kit/adapters/wordpress/blueprint.ts')}));}}]});
17
19
  const m={exports:{}};new Function('module','exports','require',compiled.outputFiles[0].text)(m,m.exports,createRequire(import.meta.url));
18
20
  fs.writeFileSync(path.join(output,'sections.json'),JSON.stringify({version:1,sections:m.exports.sections},null,2)+'\n');
@@ -0,0 +1,121 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {createHash} from 'node:crypto';
4
+ import postcss from 'postcss';
5
+ import selectors from 'postcss-selector-parser';
6
+ import breakpoints from './breakpoints.cjs';
7
+ import remDimensions from './rem-css.cjs';
8
+
9
+ const hash=value=>createHash('sha256').update(value).digest('hex').slice(0,12);
10
+ const write=(file,value)=>{fs.mkdirSync(path.dirname(file),{recursive:true});if(!fs.existsSync(file)||fs.readFileSync(file,'utf8')!==value)fs.writeFileSync(file,value);};
11
+ export const isolatedSections=root=>{
12
+ const file=path.join(root,'kit.config.json');
13
+ return fs.existsSync(file)&&JSON.parse(fs.readFileSync(file,'utf8')).sectionStyles==='isolated';
14
+ };
15
+ const inKeyframes=rule=>{for(let parent=rule.parent;parent;parent=parent.parent)if(parent.type==='atrule'&&/keyframes$/.test(parent.name))return true;return false;};
16
+
17
+ /** Guard the subject, not its ancestors: html motion states and root selectors keep working. */
18
+ export function isolateSectionCss(css,name){
19
+ const tree=postcss.parse(css),root=`[data-site-section=${JSON.stringify(name)}]`;
20
+ const guard=selectors().astSync(`:where(${root}, ${root} *)`).first.first;
21
+ tree.walkRules(rule=>{
22
+ if(inKeyframes(rule))return;
23
+ rule.selector=selectors(list=>list.each(selector=>{
24
+ const nodes=selector.nodes;
25
+ let start=0;nodes.forEach((node,index)=>{if(node.type==='combinator')start=index+1;});
26
+ const pseudo=nodes.slice(start).find(node=>node.type==='pseudo'&&(/^::/.test(node.value)||/^:(before|after|first-line|first-letter)$/.test(node.value)));
27
+ if(pseudo)selector.insertBefore(pseudo,guard.clone());else selector.append(guard.clone());
28
+ })).processSync(rule.selector);
29
+ });
30
+ return tree;
31
+ }
32
+
33
+ function sourceTree(file,project,seen=new Set()){
34
+ if(seen.has(file))throw new Error('Circular section CSS import: '+file);
35
+ const next=new Set(seen).add(file),tree=postcss.parse(fs.readFileSync(file,'utf8'),{from:file});
36
+ tree.walkAtRules('import',rule=>{
37
+ const match=rule.params.match(/^(['"])([^'"]+)\1$/);
38
+ if(!match||/^(?:https?:|\/\/)/.test(match[2]))throw rule.error('Section CSS imports must be quoted local files; put external styles in the shared entry.');
39
+ const target=path.resolve(path.dirname(file),match[2]);
40
+ if(!target.startsWith(project+path.sep))throw rule.error('Section CSS imports cannot escape the project.');
41
+ rule.replaceWith(...sourceTree(target,project,next).nodes);
42
+ });
43
+ return tree;
44
+ }
45
+
46
+ /** Optional build-time CSS assets. Existing consumers keep their global styles by default. */
47
+ export function syncSectionStyles(project,folders){
48
+ const directory=path.join(project,'src/sections'),manifest={version:1,sections:{}},themes=[];
49
+ if(!isolatedSections(project)){
50
+ write(path.join(directory,'styles.manifest.generated.json'),JSON.stringify(manifest,null,2)+'\n');
51
+ return null;
52
+ }
53
+ const output=path.join(project,'public/kit/sections'),themeOwners=new Map();
54
+ fs.mkdirSync(output,{recursive:true});
55
+ fs.mkdirSync(path.join(project,'src/site/styles'),{recursive:true});
56
+ for(const folder of folders){
57
+ const file=path.join(directory,folder,'styles.css');if(!fs.existsSync(file))continue;
58
+ const metadata=path.join(directory,folder,'section.json');
59
+ const slug=(fs.existsSync(metadata)?JSON.parse(fs.readFileSync(metadata,'utf8')).slug:null)??folder.replace(/^section-/,'');
60
+ if(!/^[a-z0-9][a-z0-9-]*$/.test(slug))throw new Error('Invalid section CSS slug: '+slug);
61
+ const name='site/'+slug,tree=sourceTree(file,project),keyframes=new Map(),assets=new Set();
62
+ tree.walkAtRules(rule=>{
63
+ if(['apply','utility','font-face','property','source'].includes(rule.name))throw rule.error(`@${rule.name} belongs in shared styles; section CSS contains isolated presentation rules.`);
64
+ if(/keyframes$/.test(rule.name))keyframes.set(rule.params,`section-${slug}-${hash(name)}-${rule.params}`);
65
+ });
66
+ tree.walkAtRules(rule=>{if(/keyframes$/.test(rule.name))rule.params=keyframes.get(rule.params);});
67
+ tree.walkDecls(decl=>{
68
+ if(/^(?:-webkit-)?animation(?:-name)?$/.test(decl.prop)||decl.prop.startsWith('--')){
69
+ for(const [original,renamed] of keyframes){
70
+ const escaped=original.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
71
+ decl.value=decl.value.replace(new RegExp(`(^|[^a-zA-Z0-9_-])${escaped}(?=$|[^a-zA-Z0-9_-])`,'g'),(_,prefix)=>prefix+renamed);
72
+ }
73
+ }
74
+ decl.value=decl.value.replace(/url\(\s*(['"]?)([^'"()]+)\1\s*\)/g,(all,_quote,url)=>{
75
+ if(/^(?:[a-z]+:|\/|#)/i.test(url))return all;
76
+ const [pathname]=url.split(/[?#]/),source=path.resolve(path.dirname(decl.source.input.file),decodeURIComponent(pathname));
77
+ if(!source.startsWith(project+path.sep)||!fs.existsSync(source))throw decl.error('Missing or external local section asset: '+url);
78
+ const bytes=fs.readFileSync(source),extension=path.extname(source).toLowerCase();
79
+ if(!/^\.(?:png|jpe?g|webp|avif|gif|svg|woff2?)$/.test(extension))throw decl.error('Unsupported section asset: '+extension);
80
+ const asset='assets/'+hash(bytes)+extension,target=path.join(output,asset);fs.mkdirSync(path.dirname(target),{recursive:true});
81
+ if(!fs.existsSync(target))fs.writeFileSync(target,bytes);assets.add(asset);
82
+ return `url(${JSON.stringify('./'+asset+url.slice(pathname.length))})`;
83
+ });
84
+ });
85
+ tree.walkAtRules('theme',rule=>{
86
+ const theme=rule.clone();theme.removeAll();
87
+ for(const node of rule.nodes??[])if(node.type==='decl'){
88
+ if(themeOwners.has(node.prop)&&themeOwners.get(node.prop)!==name)throw rule.error('Duplicate section theme token '+node.prop+'; use a section-specific name.');
89
+ themeOwners.set(node.prop,name);theme.append(node.clone());
90
+ }
91
+ if(theme.nodes.length)themes.push(theme.toString());
92
+ rule.replaceWith(...(rule.nodes??[]).filter(node=>node.type==='atrule'));
93
+ });
94
+ const compiled=postcss([breakpoints({configPath:path.join(project,'config/breakpoints.json'),outputPath:path.join(project,'src/site/styles/breakpoints.css')}),remDimensions()]).process(tree,{from:file}).css;
95
+ const scoped=isolateSectionCss(compiled,name);
96
+ scoped.walkComments(comment=>comment.remove());
97
+ if(!scoped.nodes.length)continue;
98
+ const css=scoped.toString(),filename=slug+'-'+hash(css)+'.css';
99
+ write(path.join(output,filename),css+'\n');
100
+ manifest.sections[name]={href:'/kit/sections/'+filename,file:filename,assets:[...assets]};
101
+ }
102
+ write(path.join(directory,'styles.manifest.generated.json'),JSON.stringify(manifest,null,2)+'\n');
103
+ return '/* Generated section animation tokens; presentation loads per rendered section. */\n'+themes.join('\n')+'\n';
104
+ }
105
+
106
+ export function sectionEditorCss(project,output){
107
+ if(!isolatedSections(project))return '';
108
+ const manifest=JSON.parse(fs.readFileSync(path.join(project,'src/sections/styles.manifest.generated.json'),'utf8'));
109
+ publishSectionStyles(project,output);
110
+ return Object.values(manifest.sections).map(asset=>fs.readFileSync(path.join(project,'public/kit/sections',asset.file),'utf8').replaceAll('url("./assets/','url("./sections/assets/')).join('\n');
111
+ }
112
+ export function publishSectionStyles(project,output){
113
+ if(!isolatedSections(project))return;
114
+ const manifest=JSON.parse(fs.readFileSync(path.join(project,'src/sections/styles.manifest.generated.json'),'utf8'));
115
+ fs.mkdirSync(path.join(output,'sections'),{recursive:true});
116
+ for(const asset of Object.values(manifest.sections))for(const file of [asset.file,...asset.assets]){
117
+ const target=path.join(output,'sections',file);fs.mkdirSync(path.dirname(target),{recursive:true});
118
+ fs.copyFileSync(path.join(project,'public/kit/sections',file),target);
119
+ }
120
+ write(path.join(output,'section-styles.json'),JSON.stringify(manifest,null,2)+'\n');
121
+ }
@@ -1,4 +1,5 @@
1
1
  import {syncBlocks} from './sync-blocks.mjs';
2
+ import {syncSectionStyles} from './section-styles.mjs';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
 
@@ -34,7 +35,7 @@ export function syncSections(root = process.cwd()) {
34
35
  '',
35
36
  ].join('\n');
36
37
  write(path.join(directory, 'index.generated.ts'), source);
37
- write(path.join(directory, 'styles.generated.css'), styles);
38
+ write(path.join(directory, 'styles.generated.css'), syncSectionStyles(root,folders) ?? styles);
38
39
  syncBlocks(root);
39
40
  return folders;
40
41
  }
@@ -6,6 +6,7 @@
6
6
  if ( file_exists( get_theme_file_path( 'inc/rendering/layouts.php' ) ) ) require_once get_theme_file_path( 'inc/rendering/layouts.php' );
7
7
 
8
8
  require_once __DIR__ . '/performance.php';
9
+ require_once __DIR__ . '/section-styles.php';
9
10
  function render_mode(): string {
10
11
  $file = ( function_exists( 'get_theme_file_path' ) ? get_theme_file_path( 'render.config.json' ) : dirname( __DIR__, 3 ) . '/render.config.json' );
11
12
  $config = is_readable( $file ) ? json_decode( file_get_contents( $file ), true ) : [];
@@ -30,6 +31,7 @@
30
31
  'formsEndpoint' => rest_url( 'site/v1/forms/' )
31
32
  ];
32
33
 
34
+ if (section_style_manifest()) $site['runtime']['sectionStyleBase'] = get_template_directory_uri() . '/build/wordpress/sections/';
33
35
  return $site;
34
36
  }
35
37
 
@@ -62,6 +64,7 @@
62
64
  if ( render_mode() !== 'wordpress' ) {
63
65
  return;
64
66
  }
67
+ enqueue_section_styles();
65
68
  $dir = get_template_directory();
66
69
  $url = get_template_directory_uri();
67
70
  foreach ( [ 'site.css', 'runtime.js' ] as $file ) {
@@ -0,0 +1,50 @@
1
+ <?php
2
+ namespace SiteTheme;
3
+ defined('ABSPATH') || exit;
4
+
5
+ /** Build-time manifest; never parse authored CSS during a request. */
6
+ function section_style_manifest(): array {
7
+ static $manifest;
8
+ if ($manifest === null) {
9
+ $file = get_template_directory() . '/build/wordpress/section-styles.json';
10
+ $manifest = is_readable($file) ? (json_decode(file_get_contents($file), true)['sections'] ?? []) : [];
11
+ }
12
+ return $manifest;
13
+ }
14
+
15
+ /** Both raw Gutenberg blocks and normalized layout blocks are supported. */
16
+ function section_style_names(array $blocks, array &$references = []): array {
17
+ $names = [];
18
+ foreach ($blocks as $block) {
19
+ $name = $block['blockName'] ?? $block['name'] ?? '';
20
+ if ($name) $names[$name] = true;
21
+ if ($name === 'core/block' && !empty($block['attrs']['ref'])) {
22
+ $ref = (int) $block['attrs']['ref'];
23
+ if (!isset($references[$ref])) {
24
+ $references[$ref] = true;
25
+ $post = get_post($ref);
26
+ if ($post) $names += section_style_names(parse_blocks($post->post_content), $references);
27
+ }
28
+ }
29
+ $names += section_style_names($block['innerBlocks'] ?? [], $references);
30
+ }
31
+ return $names;
32
+ }
33
+
34
+ function enqueue_section_styles(): void {
35
+ $manifest = section_style_manifest();
36
+ if (!$manifest) return;
37
+ $references = [];
38
+ $site = wordpress_site();
39
+ $names = section_style_names(array_merge($site['header'] ?? [], $site['footer'] ?? []), $references);
40
+ global $wp_query;
41
+ foreach ($wp_query->posts ?? [] as $post) {
42
+ if ($post instanceof \WP_Post) $names += section_style_names(parse_blocks($post->post_content), $references);
43
+ }
44
+ foreach (array_intersect_key($manifest, $names) as $name => $asset) {
45
+ $file = $asset['file'] ?? '';
46
+ if (!preg_match('/^[a-z0-9-]+\.css$/D', $file)) continue;
47
+ $path = get_template_directory() . '/build/wordpress/sections/' . $file;
48
+ if (is_readable($path)) wp_enqueue_style('site-section-' . substr(hash('sha256', $name), 0, 12), get_template_directory_uri() . '/build/wordpress/sections/' . $file, [], null);
49
+ }
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soinproduction-gutenberg",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -57,6 +57,7 @@
57
57
  "lucide-react": "^0.575.0",
58
58
  "luxon": "3.7.2",
59
59
  "postcss": "^8.5.0",
60
+ "postcss-selector-parser": "7.2.1",
60
61
  "tailwind-merge": "^3.5.0",
61
62
  "tailwindcss": "^4.2.1",
62
63
  "tw-animate-css": "^1.3.4",
@@ -3,6 +3,7 @@ import { build } from 'esbuild';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import postcss from 'postcss';
6
+ import {sectionEditorCss} from './section-styles.mjs';
6
7
  import tailwind from '@tailwindcss/postcss';
7
8
  import breakpoints from './breakpoints.cjs';
8
9
  import remDimensions from './rem-css.cjs';
@@ -63,7 +64,7 @@ await build({
63
64
  loader: { '.css': 'empty' },
64
65
  });
65
66
  // Isolate content CSS from the admin controls, including the reset and theme variables.
66
- const css = fs.readFileSync('app/globals.css', 'utf8');
67
+ const css = fs.readFileSync('app/globals.css', 'utf8')+'\n'+sectionEditorCss(process.cwd(),path.resolve(output));
67
68
  const result = await postcss([breakpoints(), tailwind(), remDimensions()]).process(css, { from: path.resolve('app/globals.css') });
68
69
  const tree = postcss.parse(result.css);
69
70
  // WordPress block wrappers use unlayered rules. Keep our scoped utilities at the
@@ -1,5 +1,6 @@
1
1
  import {syncKit} from './sync-kit.mjs';
2
2
  import fs from 'node:fs';
3
+ import {publishSectionStyles} from './section-styles.mjs';
3
4
  import {gzipSync} from 'node:zlib';
4
5
  import path from 'node:path';
5
6
  import {build} from 'esbuild';
@@ -13,6 +14,7 @@ import {syncBlocks} from './sync-blocks.mjs';
13
14
  syncSections();
14
15
  syncKit();syncBlocks();
15
16
  const output=path.resolve('../build/wordpress');fs.rmSync(output,{recursive:true,force:true});fs.mkdirSync(output,{recursive:true});
17
+ publishSectionStyles(process.cwd(),output);
16
18
  const compiled=await build({stdin:{contents:"export {sections} from './src/sections/index.generated';",resolveDir:process.cwd()},bundle:true,platform:'node',format:'cjs',write:false,jsx:'automatic',tsconfig:'tsconfig.json',plugins:[{name:'wordpress-blueprint-entry',setup(builder){builder.onResolve({filter:/^@kit$/},()=>({path:path.resolve('kit/adapters/wordpress/blueprint.ts')}));}}]});
17
19
  const m={exports:{}};new Function('module','exports','require',compiled.outputFiles[0].text)(m,m.exports,createRequire(import.meta.url));
18
20
  fs.writeFileSync(path.join(output,'sections.json'),JSON.stringify({version:1,sections:m.exports.sections},null,2)+'\n');
@@ -0,0 +1,121 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {createHash} from 'node:crypto';
4
+ import postcss from 'postcss';
5
+ import selectors from 'postcss-selector-parser';
6
+ import breakpoints from './breakpoints.cjs';
7
+ import remDimensions from './rem-css.cjs';
8
+
9
+ const hash=value=>createHash('sha256').update(value).digest('hex').slice(0,12);
10
+ const write=(file,value)=>{fs.mkdirSync(path.dirname(file),{recursive:true});if(!fs.existsSync(file)||fs.readFileSync(file,'utf8')!==value)fs.writeFileSync(file,value);};
11
+ export const isolatedSections=root=>{
12
+ const file=path.join(root,'kit.config.json');
13
+ return fs.existsSync(file)&&JSON.parse(fs.readFileSync(file,'utf8')).sectionStyles==='isolated';
14
+ };
15
+ const inKeyframes=rule=>{for(let parent=rule.parent;parent;parent=parent.parent)if(parent.type==='atrule'&&/keyframes$/.test(parent.name))return true;return false;};
16
+
17
+ /** Guard the subject, not its ancestors: html motion states and root selectors keep working. */
18
+ export function isolateSectionCss(css,name){
19
+ const tree=postcss.parse(css),root=`[data-site-section=${JSON.stringify(name)}]`;
20
+ const guard=selectors().astSync(`:where(${root}, ${root} *)`).first.first;
21
+ tree.walkRules(rule=>{
22
+ if(inKeyframes(rule))return;
23
+ rule.selector=selectors(list=>list.each(selector=>{
24
+ const nodes=selector.nodes;
25
+ let start=0;nodes.forEach((node,index)=>{if(node.type==='combinator')start=index+1;});
26
+ const pseudo=nodes.slice(start).find(node=>node.type==='pseudo'&&(/^::/.test(node.value)||/^:(before|after|first-line|first-letter)$/.test(node.value)));
27
+ if(pseudo)selector.insertBefore(pseudo,guard.clone());else selector.append(guard.clone());
28
+ })).processSync(rule.selector);
29
+ });
30
+ return tree;
31
+ }
32
+
33
+ function sourceTree(file,project,seen=new Set()){
34
+ if(seen.has(file))throw new Error('Circular section CSS import: '+file);
35
+ const next=new Set(seen).add(file),tree=postcss.parse(fs.readFileSync(file,'utf8'),{from:file});
36
+ tree.walkAtRules('import',rule=>{
37
+ const match=rule.params.match(/^(['"])([^'"]+)\1$/);
38
+ if(!match||/^(?:https?:|\/\/)/.test(match[2]))throw rule.error('Section CSS imports must be quoted local files; put external styles in the shared entry.');
39
+ const target=path.resolve(path.dirname(file),match[2]);
40
+ if(!target.startsWith(project+path.sep))throw rule.error('Section CSS imports cannot escape the project.');
41
+ rule.replaceWith(...sourceTree(target,project,next).nodes);
42
+ });
43
+ return tree;
44
+ }
45
+
46
+ /** Optional build-time CSS assets. Existing consumers keep their global styles by default. */
47
+ export function syncSectionStyles(project,folders){
48
+ const directory=path.join(project,'src/sections'),manifest={version:1,sections:{}},themes=[];
49
+ if(!isolatedSections(project)){
50
+ write(path.join(directory,'styles.manifest.generated.json'),JSON.stringify(manifest,null,2)+'\n');
51
+ return null;
52
+ }
53
+ const output=path.join(project,'public/kit/sections'),themeOwners=new Map();
54
+ fs.mkdirSync(output,{recursive:true});
55
+ fs.mkdirSync(path.join(project,'src/site/styles'),{recursive:true});
56
+ for(const folder of folders){
57
+ const file=path.join(directory,folder,'styles.css');if(!fs.existsSync(file))continue;
58
+ const metadata=path.join(directory,folder,'section.json');
59
+ const slug=(fs.existsSync(metadata)?JSON.parse(fs.readFileSync(metadata,'utf8')).slug:null)??folder.replace(/^section-/,'');
60
+ if(!/^[a-z0-9][a-z0-9-]*$/.test(slug))throw new Error('Invalid section CSS slug: '+slug);
61
+ const name='site/'+slug,tree=sourceTree(file,project),keyframes=new Map(),assets=new Set();
62
+ tree.walkAtRules(rule=>{
63
+ if(['apply','utility','font-face','property','source'].includes(rule.name))throw rule.error(`@${rule.name} belongs in shared styles; section CSS contains isolated presentation rules.`);
64
+ if(/keyframes$/.test(rule.name))keyframes.set(rule.params,`section-${slug}-${hash(name)}-${rule.params}`);
65
+ });
66
+ tree.walkAtRules(rule=>{if(/keyframes$/.test(rule.name))rule.params=keyframes.get(rule.params);});
67
+ tree.walkDecls(decl=>{
68
+ if(/^(?:-webkit-)?animation(?:-name)?$/.test(decl.prop)||decl.prop.startsWith('--')){
69
+ for(const [original,renamed] of keyframes){
70
+ const escaped=original.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
71
+ decl.value=decl.value.replace(new RegExp(`(^|[^a-zA-Z0-9_-])${escaped}(?=$|[^a-zA-Z0-9_-])`,'g'),(_,prefix)=>prefix+renamed);
72
+ }
73
+ }
74
+ decl.value=decl.value.replace(/url\(\s*(['"]?)([^'"()]+)\1\s*\)/g,(all,_quote,url)=>{
75
+ if(/^(?:[a-z]+:|\/|#)/i.test(url))return all;
76
+ const [pathname]=url.split(/[?#]/),source=path.resolve(path.dirname(decl.source.input.file),decodeURIComponent(pathname));
77
+ if(!source.startsWith(project+path.sep)||!fs.existsSync(source))throw decl.error('Missing or external local section asset: '+url);
78
+ const bytes=fs.readFileSync(source),extension=path.extname(source).toLowerCase();
79
+ if(!/^\.(?:png|jpe?g|webp|avif|gif|svg|woff2?)$/.test(extension))throw decl.error('Unsupported section asset: '+extension);
80
+ const asset='assets/'+hash(bytes)+extension,target=path.join(output,asset);fs.mkdirSync(path.dirname(target),{recursive:true});
81
+ if(!fs.existsSync(target))fs.writeFileSync(target,bytes);assets.add(asset);
82
+ return `url(${JSON.stringify('./'+asset+url.slice(pathname.length))})`;
83
+ });
84
+ });
85
+ tree.walkAtRules('theme',rule=>{
86
+ const theme=rule.clone();theme.removeAll();
87
+ for(const node of rule.nodes??[])if(node.type==='decl'){
88
+ if(themeOwners.has(node.prop)&&themeOwners.get(node.prop)!==name)throw rule.error('Duplicate section theme token '+node.prop+'; use a section-specific name.');
89
+ themeOwners.set(node.prop,name);theme.append(node.clone());
90
+ }
91
+ if(theme.nodes.length)themes.push(theme.toString());
92
+ rule.replaceWith(...(rule.nodes??[]).filter(node=>node.type==='atrule'));
93
+ });
94
+ const compiled=postcss([breakpoints({configPath:path.join(project,'config/breakpoints.json'),outputPath:path.join(project,'src/site/styles/breakpoints.css')}),remDimensions()]).process(tree,{from:file}).css;
95
+ const scoped=isolateSectionCss(compiled,name);
96
+ scoped.walkComments(comment=>comment.remove());
97
+ if(!scoped.nodes.length)continue;
98
+ const css=scoped.toString(),filename=slug+'-'+hash(css)+'.css';
99
+ write(path.join(output,filename),css+'\n');
100
+ manifest.sections[name]={href:'/kit/sections/'+filename,file:filename,assets:[...assets]};
101
+ }
102
+ write(path.join(directory,'styles.manifest.generated.json'),JSON.stringify(manifest,null,2)+'\n');
103
+ return '/* Generated section animation tokens; presentation loads per rendered section. */\n'+themes.join('\n')+'\n';
104
+ }
105
+
106
+ export function sectionEditorCss(project,output){
107
+ if(!isolatedSections(project))return '';
108
+ const manifest=JSON.parse(fs.readFileSync(path.join(project,'src/sections/styles.manifest.generated.json'),'utf8'));
109
+ publishSectionStyles(project,output);
110
+ return Object.values(manifest.sections).map(asset=>fs.readFileSync(path.join(project,'public/kit/sections',asset.file),'utf8').replaceAll('url("./assets/','url("./sections/assets/')).join('\n');
111
+ }
112
+ export function publishSectionStyles(project,output){
113
+ if(!isolatedSections(project))return;
114
+ const manifest=JSON.parse(fs.readFileSync(path.join(project,'src/sections/styles.manifest.generated.json'),'utf8'));
115
+ fs.mkdirSync(path.join(output,'sections'),{recursive:true});
116
+ for(const asset of Object.values(manifest.sections))for(const file of [asset.file,...asset.assets]){
117
+ const target=path.join(output,'sections',file);fs.mkdirSync(path.dirname(target),{recursive:true});
118
+ fs.copyFileSync(path.join(project,'public/kit/sections',file),target);
119
+ }
120
+ write(path.join(output,'section-styles.json'),JSON.stringify(manifest,null,2)+'\n');
121
+ }
@@ -1,4 +1,5 @@
1
1
  import {syncBlocks} from './sync-blocks.mjs';
2
+ import {syncSectionStyles} from './section-styles.mjs';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
 
@@ -34,7 +35,7 @@ export function syncSections(root = process.cwd()) {
34
35
  '',
35
36
  ].join('\n');
36
37
  write(path.join(directory, 'index.generated.ts'), source);
37
- write(path.join(directory, 'styles.generated.css'), styles);
38
+ write(path.join(directory, 'styles.generated.css'), syncSectionStyles(root,folders) ?? styles);
38
39
  syncBlocks(root);
39
40
  return folders;
40
41
  }
@@ -6,6 +6,7 @@
6
6
  if ( file_exists( get_theme_file_path( 'inc/rendering/layouts.php' ) ) ) require_once get_theme_file_path( 'inc/rendering/layouts.php' );
7
7
 
8
8
  require_once __DIR__ . '/performance.php';
9
+ require_once __DIR__ . '/section-styles.php';
9
10
  function render_mode(): string {
10
11
  $file = ( function_exists( 'get_theme_file_path' ) ? get_theme_file_path( 'render.config.json' ) : dirname( __DIR__, 3 ) . '/render.config.json' );
11
12
  $config = is_readable( $file ) ? json_decode( file_get_contents( $file ), true ) : [];
@@ -30,6 +31,7 @@
30
31
  'formsEndpoint' => rest_url( 'site/v1/forms/' )
31
32
  ];
32
33
 
34
+ if (section_style_manifest()) $site['runtime']['sectionStyleBase'] = get_template_directory_uri() . '/build/wordpress/sections/';
33
35
  return $site;
34
36
  }
35
37
 
@@ -62,6 +64,7 @@
62
64
  if ( render_mode() !== 'wordpress' ) {
63
65
  return;
64
66
  }
67
+ enqueue_section_styles();
65
68
  $dir = get_template_directory();
66
69
  $url = get_template_directory_uri();
67
70
  foreach ( [ 'site.css', 'runtime.js' ] as $file ) {
@@ -0,0 +1,50 @@
1
+ <?php
2
+ namespace SiteTheme;
3
+ defined('ABSPATH') || exit;
4
+
5
+ /** Build-time manifest; never parse authored CSS during a request. */
6
+ function section_style_manifest(): array {
7
+ static $manifest;
8
+ if ($manifest === null) {
9
+ $file = get_template_directory() . '/build/wordpress/section-styles.json';
10
+ $manifest = is_readable($file) ? (json_decode(file_get_contents($file), true)['sections'] ?? []) : [];
11
+ }
12
+ return $manifest;
13
+ }
14
+
15
+ /** Both raw Gutenberg blocks and normalized layout blocks are supported. */
16
+ function section_style_names(array $blocks, array &$references = []): array {
17
+ $names = [];
18
+ foreach ($blocks as $block) {
19
+ $name = $block['blockName'] ?? $block['name'] ?? '';
20
+ if ($name) $names[$name] = true;
21
+ if ($name === 'core/block' && !empty($block['attrs']['ref'])) {
22
+ $ref = (int) $block['attrs']['ref'];
23
+ if (!isset($references[$ref])) {
24
+ $references[$ref] = true;
25
+ $post = get_post($ref);
26
+ if ($post) $names += section_style_names(parse_blocks($post->post_content), $references);
27
+ }
28
+ }
29
+ $names += section_style_names($block['innerBlocks'] ?? [], $references);
30
+ }
31
+ return $names;
32
+ }
33
+
34
+ function enqueue_section_styles(): void {
35
+ $manifest = section_style_manifest();
36
+ if (!$manifest) return;
37
+ $references = [];
38
+ $site = wordpress_site();
39
+ $names = section_style_names(array_merge($site['header'] ?? [], $site['footer'] ?? []), $references);
40
+ global $wp_query;
41
+ foreach ($wp_query->posts ?? [] as $post) {
42
+ if ($post instanceof \WP_Post) $names += section_style_names(parse_blocks($post->post_content), $references);
43
+ }
44
+ foreach (array_intersect_key($manifest, $names) as $name => $asset) {
45
+ $file = $asset['file'] ?? '';
46
+ if (!preg_match('/^[a-z0-9-]+\.css$/D', $file)) continue;
47
+ $path = get_template_directory() . '/build/wordpress/sections/' . $file;
48
+ if (is_readable($path)) wp_enqueue_style('site-section-' . substr(hash('sha256', $name), 0, 12), get_template_directory_uri() . '/build/wordpress/sections/' . $file, [], null);
49
+ }
50
+ }