diff --git a/.gitignore b/.gitignore index c5f1ac5..4ee5e6b 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ apps/miniapp/project.private.config.json .worktrees/ apps/taro/src/assets/ +apps/admin/public/template-preview/ apps/taro/test-results/ apps/taro/playwright-report/ diff --git a/.prettierignore b/.prettierignore index a3e7e18..a8c3e1f 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,6 +1,7 @@ node_modules .turbo dist +apps/admin/public/template-preview .next prototype pnpm-lock.yaml diff --git a/apps/admin/.env.example b/apps/admin/.env.example index ffe8b28..b5ccc11 100644 --- a/apps/admin/.env.example +++ b/apps/admin/.env.example @@ -2,4 +2,4 @@ VITE_APP_BASE_PATH=/admin/ VITE_API_BASE_URL=/api VITE_DEV_API_TARGET=http://localhost:3001 ADMIN_PORT=3000 -VITE_TEMPLATE_PREVIEW_URLS={"acheng-campus-food":"http://localhost:3002","linjing-editorial":"http://localhost:3003"} +VITE_TEMPLATE_PREVIEW_URL=http://localhost:3002 diff --git a/apps/admin/src/features/brand/BrandPage.tsx b/apps/admin/src/features/brand/BrandPage.tsx index c366c0f..58cd10a 100644 --- a/apps/admin/src/features/brand/BrandPage.tsx +++ b/apps/admin/src/features/brand/BrandPage.tsx @@ -16,6 +16,10 @@ export function BrandPage() { queryKey: ["admin-workspace"], queryFn: () => client.getAdminWorkspace(), }); + const previewWorkspace = useQuery({ + queryKey: ["admin-preview-workspace"], + queryFn: () => client.getAdminPreviewWorkspace(), + }); const template = useQuery({ queryKey: ["template", brand.data?.templateKey], queryFn: () => client.getPublicTemplate(brand.data!.templateKey), @@ -145,6 +149,7 @@ export function BrandPage() { * { + width: 100%; + max-width: 100%; +} + +:where(.component-template-preview__canvas) button { + display: block; + width: -webkit-fill-available; + margin: 0; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + color: inherit; + font: inherit; + font-size: 4.8cqw; + line-height: 2.55555556; + text-align: center; +} + +:where(.component-template-preview__canvas) input { + display: block; + width: 100%; + min-width: 0; +} + +.component-template-preview__canvas img { + flex-shrink: 0; + display: block; + max-width: 100%; + object-fit: cover; +} + +.component-template-preview [data-editor-target] { + position: relative; + cursor: pointer; + outline: 2px solid transparent; + outline-offset: 3px; + transition: + outline-color 120ms ease, + background-color 120ms ease, + box-shadow 120ms ease; +} + +.component-template-preview [data-editor-target]:hover { + outline-color: #91caff; + background-color: rgba(22, 119, 255, 0.04); +} + +.component-template-preview [data-editor-target].editor-target-selected { + z-index: 2; + outline: 2px solid #1677ff; + outline-offset: 4px; + background-color: rgba(22, 119, 255, 0.1); + box-shadow: 0 0 0 5px rgba(22, 119, 255, 0.14); +} + +.component-template-preview [data-editor-target].editor-target-selected::before { + position: absolute; + top: -10px; + left: -2px; + z-index: 3; + padding: 2px 7px; + border-radius: 4px; + background: #1677ff; + color: #fff; + content: attr(data-editor-target); + font-size: 11px; + line-height: 16px; + pointer-events: none; + white-space: nowrap; +} diff --git a/apps/admin/src/features/brand/ComponentTemplatePreview.tsx b/apps/admin/src/features/brand/ComponentTemplatePreview.tsx new file mode 100644 index 0000000..8a63a42 --- /dev/null +++ b/apps/admin/src/features/brand/ComponentTemplatePreview.tsx @@ -0,0 +1,63 @@ +import { useEffect, useRef } from "react"; +import type { RuntimeWorkspace } from "@personal-brand/api-client"; +import { resolveTemplateRenderer } from "./component-renderers.jsx"; +import "../../../../../packages/template-acheng-campus-food/taro/style.css"; +import "../../../../../packages/template-linjing-editorial/taro/style.css"; +import "./ComponentTemplatePreview.css"; + +type PreviewProps = { + workspace: RuntimeWorkspace; + page: string; + offeringId?: string; + targetKey?: string; + onTargetSelected: (targetKey: string) => void; +}; + +export function ComponentTemplatePreview({ + workspace, + page, + offeringId, + targetKey, + onTargetSelected, +}: PreviewProps) { + const Renderer = resolveTemplateRenderer(workspace); + const root = useRef(null); + useEffect(() => { + root.current?.querySelectorAll("[data-editor-target]").forEach((element) => { + element.classList.toggle( + "editor-target-selected", + element.dataset.editorTarget === targetKey, + ); + }); + const selected = targetKey + ? root.current?.querySelector(`[data-editor-target="${CSS.escape(targetKey)}"]`) + : null; + selected?.scrollIntoView({ block: "nearest", behavior: "smooth" }); + }, [targetKey, workspace, page]); + return ( +
{ + const element = + event.target instanceof Element + ? event.target.closest("[data-editor-target]") + : null; + const key = element?.dataset.editorTarget; + if (!key) return; + event.preventDefault(); + event.stopPropagation(); + onTargetSelected(key); + }} + > +
+ +
+ {targetKey ? ( +
+ ) : null} +
+ ); +} +// @ts-nocheck diff --git a/apps/admin/src/features/brand/PresentationEditor.tsx b/apps/admin/src/features/brand/PresentationEditor.tsx index fd535fe..8ae7c8d 100644 --- a/apps/admin/src/features/brand/PresentationEditor.tsx +++ b/apps/admin/src/features/brand/PresentationEditor.tsx @@ -19,14 +19,21 @@ import { import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useNavigate } from "react-router-dom"; -import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client"; +import type { + AdminTemplateContent, + RuntimeWorkspace, + TemplateAdminField, +} from "@personal-brand/api-client"; import type { BrandProfile } from "@personal-brand/api-client"; +import { projectBrandAliases } from "@personal-brand/api-client"; import { createApiClient } from "../../lib/api.js"; import { ImageUrlField } from "../../components/ImageUrlField.js"; import { TemplateListField } from "../../components/TemplateListField.js"; import { MutationError } from "../../components/QueryState.js"; import { TemplatePreview } from "./TemplatePreview.js"; import { + applyBrandPreviewValues, + applyStandardBrandValues, applyPresentationValues, filterSectionsForPreviewTarget, presentationFieldName, @@ -36,6 +43,7 @@ import { interface PresentationEditorProps { templateContent: AdminTemplateContent | null | undefined; + previewWorkspace?: RuntimeWorkspace | undefined; config: Record | null | undefined; brand: BrandProfile; loading?: boolean; @@ -83,6 +91,7 @@ function renderField(field: TemplateAdminField) { export function PresentationEditor({ templateContent, + previewWorkspace, config, brand, loading, @@ -94,6 +103,8 @@ export function PresentationEditor({ const breakpoints = Grid.useBreakpoint(); const [activePage, setActivePage] = useState(); const [activeTarget, setActiveTarget] = useState(); + const [previewConfig, setPreviewConfig] = useState(config ?? {}); + const [previewBrandValues, setPreviewBrandValues] = useState>({}); const sections = useMemo(() => { const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({ ...field, @@ -113,22 +124,20 @@ export function PresentationEditor({ ] : []), ...(templateContent?.admin.sections ?? []), - ] - .map((section) => ({ - ...section, - fields: section.fields.filter( - (field) => - field.binding.startsWith("brand.config.") || - [ - "brand.avatarUrl", - "brand.description", - "brand.contactPhone", - "brand.contactWechat", - "brand.address", - ].includes(field.binding), - ), - })) - .filter((section) => section.fields.length > 0); + ].map((section) => ({ + ...section, + fields: section.fields.filter( + (field) => + field.binding.startsWith("brand.config.") || + [ + "brand.avatarUrl", + "brand.description", + "brand.contactPhone", + "brand.contactWechat", + "brand.address", + ].includes(field.binding), + ), + })); }, [templateContent]); const pageOptions = useMemo(() => { const pages = new Map(); @@ -144,11 +153,23 @@ export function PresentationEditor({ ? activePage : pageOptions[0]?.value; const visibleSections = sections.filter((section) => section.page === selectedPage); - const visibleTargets = visibleSections.flatMap((section) => - (section.previewTargets ?? []).map((target) => ({ ...target, page: section.page })), - ); + const visibleTargets = (templateContent?.admin.sections ?? []) + .filter((section) => section.page === selectedPage) + .flatMap((section) => + (section.previewTargets ?? []).map((target) => ({ + ...target, + page: section.page, + source: section.target, + })), + ); const selectedTarget = visibleTargets.find((target) => target.key === activeTarget); - const editableSections = filterSectionsForPreviewTarget(visibleSections, selectedTarget?.key); + const selectedSection = (templateContent?.admin.sections ?? []).find((section) => + section.previewTargets?.some((target) => target.key === selectedTarget?.key), + ); + const editableSections = filterSectionsForPreviewTarget( + visibleSections.filter((section) => section.target === "brand"), + selectedTarget?.key, + ); const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []); const relatedTargets = [ ...(templateContent?.admin.sections ?? []) @@ -180,6 +201,12 @@ export function PresentationEditor({ }, ], ); + const relevantPageLinks = selectedSection + ? pageLinks.filter((item) => { + if (item.target.startsWith("trust:")) return selectedSection.target === "trust"; + return item.target === selectedSection.target; + }) + : pageLinks; const initialValues = useMemo(() => { const values: PresentationValues = {}; for (const section of sections) { @@ -188,6 +215,7 @@ export function PresentationEditor({ config, field.binding, field, + brand as unknown as Record, ); } } @@ -197,7 +225,10 @@ export function PresentationEditor({ const save = useMutation({ mutationFn: (values: PresentationValues) => { const nextConfig = applyPresentationValues(config, sections, values); - return createApiClient().updateAdminBrand({ config: nextConfig }); + return createApiClient().updateAdminBrand({ + config: nextConfig, + ...applyStandardBrandValues(brand as unknown as Record, sections, values), + }); }, onSuccess: () => { message.success("页面内容已保存为草稿,发布后小程序才会更新"); @@ -218,6 +249,27 @@ export function PresentationEditor({ setActivePage(pageOptions[0]?.value); }, [activePage, pageOptions]); useEffect(() => setActiveTarget(undefined), [selectedPage]); + useEffect(() => { + setPreviewConfig(config ?? {}); + setPreviewBrandValues({}); + }, [config]); + const previewBrand = useMemo( + () => ({ ...brand, ...previewBrandValues, config: previewConfig }), + [brand, previewBrandValues, previewConfig], + ); + const handleValuesChange = useCallback( + (_changed: PresentationValues, allValues: PresentationValues) => { + const next = applyBrandPreviewValues( + brand as unknown as Record, + config, + sections, + allValues, + ); + setPreviewConfig((next.config as Record) ?? {}); + setPreviewBrandValues(next); + }, + [brand, config, sections], + ); return ( 页面预览 ), + config: previewConfig, + }, + previewConfig, + ), + }, + }, + } + : {})} page={selectedPage ?? "home"} - route={`/pages/${encodeURIComponent(selectedPage ?? "home")}/index`} {...(activeTarget ? { targetKey: activeTarget } : {})} onTargetSelected={handleTargetSelected} /> @@ -287,6 +355,7 @@ export function PresentationEditor({ form={form} layout="vertical" initialValues={initialValues} + onValuesChange={handleValuesChange} onFinish={(values) => save.mutate(values)} style={{ minHeight: 540, display: "flex", flexDirection: "column" }} > @@ -333,7 +402,7 @@ export function PresentationEditor({ ))} - {pageLinks.length ? ( + {relevantPageLinks.length ? ( - {pageLinks.map((item) => ( + {relevantPageLinks.map((item) => (
diff --git a/apps/admin/src/features/brand/TemplatePreview.tsx b/apps/admin/src/features/brand/TemplatePreview.tsx index ba12ffe..a712641 100644 --- a/apps/admin/src/features/brand/TemplatePreview.tsx +++ b/apps/admin/src/features/brand/TemplatePreview.tsx @@ -4,42 +4,42 @@ import type { BrandProfile, EditorPreviewFrameMessage, EditorPreviewHostMessage, + RuntimeWorkspace, } from "@personal-brand/api-client"; import { templatePreviewUrl } from "../../lib/template-preview.js"; +import { ComponentTemplatePreview } from "./ComponentTemplatePreview.js"; import "./TemplatePreview.css"; export function TemplatePreview({ brand, + workspace, page, targetKey, - route, onTargetSelected, }: { brand: BrandProfile; + workspace?: RuntimeWorkspace; page: string; targetKey?: string; - route: string; onTargetSelected: (key: string) => void; }) { const frame = useRef(null); const [ready, setReady] = useState(false); const [error, setError] = useState(""); const [reloadKey, setReloadKey] = useState(0); - const config = brand.config ?? {}; - const templateKey = - typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : brand.templateKey; - const url = useMemo( - () => - templatePreviewUrl( - templateKey, - brand.slug, - page, - import.meta.env.VITE_TEMPLATE_PREVIEW_URLS, - window.location.origin, - route, - ), - [brand.slug, page, reloadKey, route, templateKey], - ); + const url = useMemo(() => { + const value = templatePreviewUrl( + brand.slug, + page, + import.meta.env.VITE_TEMPLATE_PREVIEW_URL || "/template-preview/index.html", + window.location.origin, + `/pages/${encodeURIComponent(page)}/index`, + ); + if (!value) return undefined; + const preview = new URL(value); + preview.searchParams.set("refresh", String(reloadKey)); + return preview.toString(); + }, [brand.slug, page, reloadKey]); const origin = useMemo(() => (url ? new URL(url).origin : ""), [url]); const brandDraft = useMemo( () => ({ @@ -80,12 +80,21 @@ export function TemplatePreview({ if (!ready || !frame.current?.contentWindow || !origin) return; const send = (message: EditorPreviewHostMessage) => frame.current?.contentWindow?.postMessage(message, origin); - send({ - protocol: "personal-brand-editor-preview", - version: 1, - type: "brandDraft", - brand: brandDraft, - }); + if (workspace) { + send({ + protocol: "personal-brand-editor-preview", + version: 1, + type: "workspaceDraft", + workspace, + }); + } else { + send({ + protocol: "personal-brand-editor-preview", + version: 1, + type: "brandDraft", + brand: brandDraft, + }); + } if (targetKey) send({ protocol: "personal-brand-editor-preview", @@ -93,7 +102,7 @@ export function TemplatePreview({ type: "focusTarget", targetKey, }); - }, [brandDraft, origin, ready, targetKey]); + }, [brandDraft, origin, ready, targetKey, workspace]); useEffect(() => { const refresh = () => setReloadKey((value) => value + 1); @@ -106,30 +115,42 @@ export function TemplatePreview({ ); return (
- {!ready && !error ? ( -
- -
+ {workspace ? ( + ) : null} - {error ? ( - + {!workspace ? ( + <> + {!ready && !error ? ( +
+ +
+ ) : null} + {error ? ( + + ) : null} +