create-kywi-app 0.5.0 → 0.6.0

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.
Files changed (2) hide show
  1. package/lib/templates.mjs +174 -12
  2. package/package.json +1 -1
package/lib/templates.mjs CHANGED
@@ -383,12 +383,13 @@ import type {
383
383
  ModuleNode,
384
384
  FeedItemsResolver,
385
385
  ComponentResolver,
386
+ SectionComponentResolver,
386
387
  PersonalizationState,
387
388
  } from '@kywi-software/core/layout'
388
389
  import { isLayoutSection, applyPageVariant } from '@kywi-software/core/layout'
389
390
  import { resolveContentByPath, normalizePath } from '@kywi-software/core/nav'
390
391
  import { getFeedBySlug, getComponentById, resolveLocaleFromRequest } from '@kywi-software/core'
391
- import { resolveComponentDefinition } from '@kywi-software/core/admin/server'
392
+ import { resolveComponentDefinition, resolveSectionComponentDefinition } from '@kywi-software/core/admin/server'
392
393
  import {
393
394
  evaluateActiveAudiences,
394
395
  getSelfIdWidgetConfig,
@@ -590,6 +591,41 @@ export async function buildComponentResolver(
590
591
  return (componentId) => resolveComponentDefinition(map.get(componentId) ?? null)
591
592
  }
592
593
 
594
+ /** Yield every section-level component reference (\`section.componentId\`) in the
595
+ * layout, descending into variantContainer default + variant sections (#69). */
596
+ function* sectionComponentIds(regions: Record<string, RegionNode[]>): Generator<string> {
597
+ for (const nodes of Object.values(regions)) {
598
+ for (const node of nodes) {
599
+ if (isLayoutSection(node)) {
600
+ if (node.componentId) yield node.componentId
601
+ } else {
602
+ for (const s of node.defaultSections) if (s.componentId) yield s.componentId
603
+ for (const v of node.variants) for (const s of v.sections) if (s.componentId) yield s.componentId
604
+ }
605
+ }
606
+ }
607
+ }
608
+
609
+ /**
610
+ * Prefetch every connected *section* component (\`section.componentId\`) referenced
611
+ * by the layout and return a synchronous {@link SectionComponentResolver} over the
612
+ * snapshot — parallel to {@link buildComponentResolver} but for reusable sections
613
+ * (#69). Returns undefined when the layout references none (skip the prop).
614
+ */
615
+ export async function buildSectionComponentResolver(
616
+ layout: LayoutDocument,
617
+ runtime: KywiRuntime,
618
+ ): Promise<SectionComponentResolver | undefined> {
619
+ const ids = new Set<string>(sectionComponentIds(layout.regions))
620
+ if (ids.size === 0) return undefined
621
+ const { db, siteId } = runtime
622
+ const entries = await Promise.all(
623
+ [...ids].map(async (id) => [id, await getComponentById(db, id, siteId)] as const),
624
+ )
625
+ const map = new Map(entries)
626
+ return (componentId) => resolveSectionComponentDefinition(map.get(componentId) ?? null)
627
+ }
628
+
593
629
  // ─── Personalization + experiments (#50) ─────────────────────────────────────
594
630
 
595
631
  /** Server-resolved personalization for one public request. */
@@ -1117,6 +1153,7 @@ import {
1117
1153
  clientRuntimeEnabled,
1118
1154
  buildFeedResolver,
1119
1155
  buildComponentResolver,
1156
+ buildSectionComponentResolver,
1120
1157
  localeAlternates,
1121
1158
  mediaUrl,
1122
1159
  requestBaseUrl,
@@ -1255,6 +1292,7 @@ export default async function PublicPage({ params, searchParams }: Params & Sear
1255
1292
  const personalized = personalizeLayout(layout, perso.audienceId)
1256
1293
  const hydrated = await hydrateLayoutFeeds(personalized, buildFeedResolver(runtime))
1257
1294
  const componentResolver = await buildComponentResolver(hydrated, runtime)
1295
+ const sectionComponentResolver = await buildSectionComponentResolver(hydrated, runtime)
1258
1296
  content = (
1259
1297
  <article className="page page--layout" data-kywi-content-id={contentId}>
1260
1298
  {head}
@@ -1263,6 +1301,7 @@ export default async function PublicPage({ params, searchParams }: Params & Sear
1263
1301
  personalization={perso.personalization}
1264
1302
  moduleComponents={moduleComponents}
1265
1303
  {...(componentResolver ? { componentResolver } : {})}
1304
+ {...(sectionComponentResolver ? { sectionComponentResolver } : {})}
1266
1305
  >
1267
1306
  {Object.keys(hydrated.regions).map((name) => (
1268
1307
  <KywiRegion key={name} name={name} />
@@ -1298,9 +1337,12 @@ export default async function PublicPage({ params, searchParams }: Params & Sear
1298
1337
  canEdit={perms.canEdit}
1299
1338
  canPublish={perms.canPublish}
1300
1339
  contentId={contentId}
1340
+ contentType={contentType}
1301
1341
  pageTitle={title}
1302
1342
  pageStatus={String(node['status'] ?? '')}
1343
+ initialLayout={layout ?? { regions: { main: [] } }}
1303
1344
  adminHref={\`/admin/content/\${contentType}/\${contentId}\`}
1345
+ moduleComponents={moduleComponents}
1304
1346
  >
1305
1347
  {content}
1306
1348
  </KywiFrontEdit>
@@ -1315,56 +1357,167 @@ export default async function PublicPage({ params, searchParams }: Params & Sear
1315
1357
  /**
1316
1358
  * Front-of-site edit overlay (client). Mounted by the public page ONLY for an
1317
1359
  * authenticated admin who opened the page with ?kywi-edit=1 (the page verifies
1318
- * the session cookie server-side first). Surfaces core's KywiEditToolbar and
1319
- * enters edit mode, which outlines the editable regions core already marks with
1320
- * the `data-kywi-*` protocol. Real content edits happen in the full admin editor
1321
- * (the toolbar's Admin link deep-links to this page there); Publish posts to the
1322
- * API for admins with publish permission.
1360
+ * the session cookie server-side first).
1361
+ *
1362
+ * Two modes, same component:
1363
+ * - **Browse** — core's slim `KywiEditToolbar` over the live page, with the
1364
+ * editable regions outlined via the `data-kywi-*` protocol.
1365
+ * - **Edit** (`?kywi-edit=1`, or the toolbar's Edit toggle) — the FULL
1366
+ * `OverlayShell` layout editor, the same one the admin app mounts, rendered
1367
+ * from the same core module registry + custom renderers. Save PUTs the layout
1368
+ * document; Publish PUTs the layout then flips status — exactly the API the
1369
+ * admin editor uses.
1370
+ *
1371
+ * The OverlayShell is lazy-loaded (`next/dynamic`, client-only): its weight
1372
+ * (dnd-kit, canvas, side panels) is only fetched when an editor actually enters
1373
+ * edit mode, so the public browse bundle stays light.
1323
1374
  */
1324
1375
  function frontEditOverlay() {
1325
1376
  return `'use client'
1326
1377
  import React from 'react'
1378
+ import dynamic from 'next/dynamic'
1327
1379
  import { KywiEditToolbar, useKywiEditMode } from '@kywi-software/core/scope-client'
1328
1380
  import { adminFetch } from '@kywi-software/core/host-client'
1381
+ import {
1382
+ createModuleRegistry,
1383
+ createThemeRegistry,
1384
+ BUILT_IN_MODULE_COMPONENTS,
1385
+ type LayoutDocument,
1386
+ type ModuleComponentMap,
1387
+ } from '@kywi-software/core/layout'
1388
+ import type { SaveAction } from '@kywi-software/core/admin'
1389
+
1390
+ // Lazy-load the full layout editor AND its stylesheet: the shell bundle (dnd-kit,
1391
+ // canvas, panels) and the ~4.7k-line admin design system are pulled INSIDE this
1392
+ // factory, so they enter the module graph only when an editor opens the overlay —
1393
+ // never in the public browse bundle a visitor downloads.
1394
+ const OverlayShell = dynamic(
1395
+ async () => {
1396
+ await import('@kywi-software/core/admin/styles.css')
1397
+ const mod = await import('@kywi-software/core/admin')
1398
+ return mod.OverlayShell
1399
+ },
1400
+ { ssr: false },
1401
+ )
1329
1402
 
1330
1403
  export interface KywiFrontEditProps {
1331
1404
  canEdit: boolean
1332
1405
  canPublish: boolean
1333
1406
  contentId: string
1407
+ contentType: string
1334
1408
  pageTitle: string
1335
1409
  pageStatus: string
1410
+ /** The page's saved layout document (empty regions when it has none yet). */
1411
+ initialLayout: LayoutDocument
1336
1412
  /** Deep link to this page in the full admin editor. */
1337
1413
  adminHref: string
1414
+ /** Custom (defineModule) renderers, shared with the public layout + admin (#48). */
1415
+ moduleComponents?: ModuleComponentMap
1338
1416
  children: React.ReactNode
1339
1417
  }
1340
1418
 
1341
1419
  /**
1342
1420
  * Wraps the public page with the front-of-site edit affordance. The page only
1343
1421
  * renders this for a signed-in admin who asked to edit (?kywi-edit=1), so the
1344
- * toolbar's own permission gate (canEdit) is always satisfied here.
1422
+ * permission gate (canEdit) is always satisfied here.
1345
1423
  */
1346
1424
  export function KywiFrontEdit({
1347
1425
  canEdit,
1348
1426
  canPublish,
1349
1427
  contentId,
1428
+ contentType,
1350
1429
  pageTitle,
1351
1430
  pageStatus,
1431
+ initialLayout,
1352
1432
  adminHref,
1433
+ moduleComponents = {},
1353
1434
  children,
1354
1435
  }: KywiFrontEditProps) {
1355
1436
  const edit = useKywiEditMode({ canEdit, canPublish })
1356
1437
 
1357
1438
  // ?kywi-edit=1 means "enter edit mode now" — flip it on once after mount.
1358
- const { startEdit } = edit
1439
+ const { startEdit, endEdit } = edit
1359
1440
  React.useEffect(() => {
1360
1441
  startEdit()
1361
1442
  }, [startEdit])
1362
1443
 
1363
- const handlePublish = React.useCallback(async () => {
1444
+ // Registries + renderers for the editor: built from core (no module list is
1445
+ // re-declared here) and merged with this app's custom module renderers from
1446
+ // lib/modules — the SAME source the admin app and public renderer use (#48).
1447
+ const moduleRegistry = React.useMemo(() => createModuleRegistry([]), [])
1448
+ const themeRegistry = React.useMemo(() => createThemeRegistry(), [])
1449
+ const editorComponents = React.useMemo(
1450
+ () => ({ ...BUILT_IN_MODULE_COMPONENTS, ...moduleComponents }),
1451
+ [moduleComponents],
1452
+ )
1453
+
1454
+ // Persist the edited layout to the same content API the admin editor uses.
1455
+ const persistLayout = React.useCallback(
1456
+ async (next: LayoutDocument) => {
1457
+ const res = await fetch(\`/api/v1/content/\${contentType}/\${contentId}/layout\`, {
1458
+ method: 'PUT',
1459
+ credentials: 'same-origin',
1460
+ headers: { 'Content-Type': 'application/json' },
1461
+ body: JSON.stringify(next),
1462
+ })
1463
+ return res.ok
1464
+ },
1465
+ [contentType, contentId],
1466
+ )
1467
+
1468
+ const handleSave = React.useCallback(
1469
+ async (next: LayoutDocument, _action: SaveAction) => {
1470
+ await persistLayout(next)
1471
+ endEdit()
1472
+ },
1473
+ [persistLayout, endEdit],
1474
+ )
1475
+
1476
+ const handlePublish = React.useCallback(
1477
+ async (next: LayoutDocument, _action: SaveAction) => {
1478
+ const ok = await persistLayout(next)
1479
+ if (ok) {
1480
+ // Best-effort status flip; the layout itself is already persisted above.
1481
+ await fetch(\`/api/v1/content/\${contentType}/\${contentId}\`, {
1482
+ method: 'PUT',
1483
+ credentials: 'same-origin',
1484
+ headers: { 'Content-Type': 'application/json' },
1485
+ body: JSON.stringify({ status: 'published' }),
1486
+ }).catch(() => undefined)
1487
+ }
1488
+ endEdit()
1489
+ },
1490
+ [persistLayout, contentType, contentId, endEdit],
1491
+ )
1492
+
1493
+ // Browse-mode one-click publish from the toolbar (no editor needed).
1494
+ const handleToolbarPublish = React.useCallback(async () => {
1364
1495
  const res = await adminFetch(\`/api/v1/content/by-id/\${contentId}/publish\`, { method: 'POST' })
1365
1496
  if (res.ok) window.location.reload()
1366
1497
  }, [contentId])
1367
1498
 
1499
+ // Edit mode: the full layout editor, in place, over the live page.
1500
+ if (edit.isEditMode && edit.canEdit) {
1501
+ return (
1502
+ <div className="kywi-admin-shell kywi-frontend-edit">
1503
+ <OverlayShell
1504
+ editMode={edit}
1505
+ initialLayout={initialLayout}
1506
+ contentId={contentId}
1507
+ contentType={contentType}
1508
+ pageTitle={pageTitle}
1509
+ themeName="default"
1510
+ themeRegistry={themeRegistry}
1511
+ moduleRegistry={moduleRegistry}
1512
+ moduleComponents={editorComponents}
1513
+ onSave={handleSave}
1514
+ onPublish={handlePublish}
1515
+ />
1516
+ </div>
1517
+ )
1518
+ }
1519
+
1520
+ // Browse mode: slim toolbar + editable-region outlines over the live page.
1368
1521
  return (
1369
1522
  <>
1370
1523
  <KywiEditToolbar
@@ -1372,7 +1525,7 @@ export function KywiFrontEdit({
1372
1525
  canEdit={edit.canEdit}
1373
1526
  canPublish={edit.canPublish}
1374
1527
  onToggleEdit={edit.toggleEdit}
1375
- onPublish={handlePublish}
1528
+ onPublish={handleToolbarPublish}
1376
1529
  pageTitle={pageTitle}
1377
1530
  pageStatus={pageStatus}
1378
1531
  adminHref={adminHref}
@@ -1800,7 +1953,16 @@ their Body rich text. Reach for the Layout tab when a page needs sections,
1800
1953
  columns, or modules; use the Body for simple prose.
1801
1954
 
1802
1955
  **Front-of-site editor.** Signed in as an admin, append \`?kywi-edit=1\` to any
1803
- public page to get an edit toolbar (the \`app/(site)/kywi-front-edit.tsx\` overlay).
1956
+ public page to edit it in place. You get the full **Layout editor** (the same
1957
+ drag-and-drop canvas, module palette and props panel as the admin's Layout tab),
1958
+ mounted right over the live page — add sections and modules, then **Save** (PUTs
1959
+ the layout) or **Publish** (saves + publishes). Exit the editor for the slim
1960
+ browse toolbar with the editable-region outlines. It all lives in
1961
+ \`app/(site)/kywi-front-edit.tsx\`; the editor bundle (and the admin stylesheet) is
1962
+ lazy-loaded, so pages your visitors see never carry its weight. Note: custom
1963
+ \`defineModule\` types still RENDER on the canvas, but they don't appear in the
1964
+ front-of-site editor's insert palette (it uses the built-in module set) — add
1965
+ them from the admin's Layout tab instead.
1804
1966
 
1805
1967
  ## Personalization, A/B testing & self-ID
1806
1968
 
@@ -1919,7 +2081,7 @@ lib/config.ts single import path for kywi.config.ts
1919
2081
  app/api/v1/[...kywi]/route.ts the versioned API (delegates to core)
1920
2082
  app/admin/[[...admin]]/page.tsx mounts the FULL core admin (all surfaces) at /admin
1921
2083
  lib/modules.tsx custom (defineModule) module renderers (admin + public)
1922
- app/{llms,robots,sitemap,…} root AX routes (llms.txt, robots.txt, sitemap.xml, …)${a.mode === 'coupled' ? '\napp/(site)/layout.tsx public shell: theme tokens + your header/footer\napp/(site)/site.css your site chrome styles (edit freely)\napp/(site)/[[...slug]]/page.tsx renders published pages (layout + SEO + JSON-LD + i18n)\nlib/site.ts public-render helpers: path/locale resolution, feeds, personalization\ncomponents/personalization-runtime.tsx optional client runtime (self-ID widget, live re-eval)\napp/(site)/kywi-front-edit.tsx front-of-site edit overlay (?kywi-edit=1)' : '\napp/page.tsx returns 404 (no public rendering in this mode)'}
2084
+ app/{llms,robots,sitemap,…} root AX routes (llms.txt, robots.txt, sitemap.xml, …)${a.mode === 'coupled' ? '\napp/(site)/layout.tsx public shell: theme tokens + your header/footer\napp/(site)/site.css your site chrome styles (edit freely)\napp/(site)/[[...slug]]/page.tsx renders published pages (layout + SEO + JSON-LD + i18n)\nlib/site.ts public-render helpers: path/locale resolution, feeds, personalization\ncomponents/personalization-runtime.tsx optional client runtime (self-ID widget, live re-eval)\napp/(site)/kywi-front-edit.tsx front-of-site editor: browse toolbar + in-place Layout editor (?kywi-edit=1, lazy-loaded)' : '\napp/page.tsx returns 404 (no public rendering in this mode)'}
1923
2085
  \`\`\`
1924
2086
  `
1925
2087
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-kywi-app",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Scaffold a new Kywi CMS project — npx create-kywi-app my-site",
5
5
  "type": "module",
6
6
  "homepage": "https://github.com/Kywi-Software/kywi-cms#readme",