diff --git a/apps/admin/src/features/brand/ComponentTemplatePreview.css b/apps/admin/src/features/brand/ComponentTemplatePreview.css index 105a70d..d3a41ba 100644 --- a/apps/admin/src/features/brand/ComponentTemplatePreview.css +++ b/apps/admin/src/features/brand/ComponentTemplatePreview.css @@ -1,12 +1,36 @@ +.component-template-preview-shell { + height: 100%; +} + +.component-template-preview__tools { + display: flex; + gap: 8px; + padding: 8px 12px; + border-bottom: 1px solid #e8e8e8; + background: #fff; +} + +.component-template-preview__tools button { + padding: 4px 12px; + border: 1px solid #d9d9d9; + border-radius: 6px; + background: #fff; + cursor: pointer; +} + +.component-template-preview__tools button[aria-pressed="true"] { + border-color: #1677ff; + color: #1677ff; +} + .component-template-preview { position: relative; width: 100%; - height: min(76vh, 820px); - min-height: 620px; + height: calc(100% - 49px); + min-height: 510px; padding: 24px 16px; overflow-x: hidden; overflow-y: auto; - border: 1px solid #e8e8e8; background: #f3f4f6; } @@ -61,42 +85,36 @@ object-fit: cover; } -.component-template-preview [data-editor-target] { - position: relative; +.component-template-preview[data-editor-mode="edit"] [data-editor-target] { 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 { +.component-template-preview__outline { position: absolute; - top: -10px; - left: -2px; - z-index: 3; - padding: 2px 7px; + z-index: 5; + pointer-events: none; + border: 2px solid #91caff; border-radius: 4px; +} + +.component-template-preview__outline.is-selected { + z-index: 6; + border-color: #1677ff; + box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.16); +} + +.component-template-preview__outline span { + position: absolute; + bottom: 100%; + left: 0; + max-width: 100%; + padding: 2px 7px; + overflow: hidden; + border-radius: 4px 4px 0 0; background: #1677ff; color: #fff; - content: attr(data-editor-target); - font-size: 11px; - line-height: 16px; - pointer-events: none; + font-size: 12px; + line-height: 18px; + text-overflow: ellipsis; white-space: nowrap; } diff --git a/apps/admin/src/features/brand/ComponentTemplatePreview.tsx b/apps/admin/src/features/brand/ComponentTemplatePreview.tsx index 8a63a42..745108a 100644 --- a/apps/admin/src/features/brand/ComponentTemplatePreview.tsx +++ b/apps/admin/src/features/brand/ComponentTemplatePreview.tsx @@ -1,6 +1,8 @@ -import { useEffect, useRef } from "react"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import type { RuntimeWorkspace } from "@personal-brand/api-client"; +import { Alert } from "antd"; import { resolveTemplateRenderer } from "./component-renderers.jsx"; +import type { PreviewSelection, PreviewTarget } from "./preview-selection.js"; import "../../../../../packages/template-acheng-campus-food/taro/style.css"; import "../../../../../packages/template-linjing-editorial/taro/style.css"; import "./ComponentTemplatePreview.css"; @@ -9,54 +11,177 @@ type PreviewProps = { workspace: RuntimeWorkspace; page: string; offeringId?: string; - targetKey?: string; - onTargetSelected: (targetKey: string) => void; + selection?: PreviewSelection; + targets: PreviewTarget[]; + onTargetSelected: (selection?: PreviewSelection) => void; }; +type Outline = { top: number; left: number; width: number; height: number; label: string }; + export function ComponentTemplatePreview({ workspace, page, offeringId, - targetKey, + selection, + targets, onTargetSelected, }: PreviewProps) { const Renderer = resolveTemplateRenderer(workspace); const root = useRef(null); + const [mode, setMode] = useState<"edit" | "browse">("edit"); + const [hovered, setHovered] = useState(null); + const [hoverOutline, setHoverOutline] = useState(null); + const [selectedOutline, setSelectedOutline] = useState(null); + const targetFor = useCallback( + (element: Element | null): HTMLElement | null => { + let candidate = element?.closest("[data-editor-target]"); + while (candidate && root.current?.contains(candidate)) { + if (targets.some((target) => target.key === candidate?.dataset.editorTarget)) + return candidate; + candidate = candidate.parentElement?.closest("[data-editor-target]") ?? null; + } + return null; + }, + [targets], + ); + const selectedElement = useCallback(() => { + if (!selection) return null; + return ( + Array.from(root.current?.querySelectorAll("[data-editor-target]") ?? []).find( + (element) => + element.dataset.editorTarget === selection.targetKey && + (element.dataset.editorRecordId || undefined) === selection.recordId, + ) ?? null + ); + }, [selection]); + const measure = useCallback( + (element: HTMLElement | null): Outline | null => { + const viewport = root.current; + if (!element || !viewport || !viewport.contains(element)) return null; + const box = element.getBoundingClientRect(); + const parent = viewport.getBoundingClientRect(); + const target = targets.find((item) => item.key === element.dataset.editorTarget); + if (!target || !box.width || !box.height) return null; + return { + top: box.top - parent.top + viewport.scrollTop, + left: box.left - parent.left + viewport.scrollLeft, + width: box.width, + height: box.height, + label: target.label, + }; + }, + [targets], + ); + useLayoutEffect(() => { + const viewport = root.current; + if (!viewport) return; + let frame = 0; + const update = () => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => { + setSelectedOutline(measure(selectedElement())); + setHoverOutline(measure(hovered)); + }); + }; + update(); + const resize = new ResizeObserver(update); + resize.observe(viewport); + viewport + .querySelectorAll("[data-editor-target]") + .forEach((node) => resize.observe(node)); + window.addEventListener("resize", update); + viewport.addEventListener("scroll", update); + viewport.addEventListener("load", update, true); + return () => { + cancelAnimationFrame(frame); + resize.disconnect(); + window.removeEventListener("resize", update); + viewport.removeEventListener("scroll", update); + viewport.removeEventListener("load", update, true); + }; + }, [hovered, measure, selectedElement, workspace, page]); 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]); + selectedElement()?.scrollIntoView({ block: "nearest", behavior: "smooth" }); + }, [selectedElement]); + useEffect(() => { + const clear = (event: KeyboardEvent) => { + if (event.key === "Escape") onTargetSelected(undefined); + }; + window.addEventListener("keydown", clear); + return () => window.removeEventListener("keydown", clear); + }, [onTargetSelected]); + if (!Renderer) + return ; 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); - }} - > -
- +
+
+ + +
+
{ + if (mode !== "edit") return; + const next = targetFor(event.target instanceof Element ? event.target : null); + if (next !== hovered) setHovered(next); + }} + onPointerLeave={() => setHovered(null)} + onClickCapture={(event) => { + if (mode !== "edit") return; + const element = targetFor(event.target instanceof Element ? event.target : null); + event.preventDefault(); + event.stopPropagation(); + onTargetSelected( + element + ? { + targetKey: element.dataset.editorTarget!, + ...(element.dataset.editorRecordId + ? { recordId: element.dataset.editorRecordId } + : {}), + } + : undefined, + ); + }} + > +
+ +
+ {mode === "edit" && hoverOutline ? ( + - {targetKey ? ( -
- ) : null}
); } diff --git a/apps/admin/src/features/brand/PresentationEditor.tsx b/apps/admin/src/features/brand/PresentationEditor.tsx index 8ae7c8d..b342b39 100644 --- a/apps/admin/src/features/brand/PresentationEditor.tsx +++ b/apps/admin/src/features/brand/PresentationEditor.tsx @@ -16,24 +16,29 @@ import { Typography, message, } from "antd"; -import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useNavigate } from "react-router-dom"; import type { AdminTemplateContent, RuntimeWorkspace, TemplateAdminField, + TemplateAdminSection, + Offering, + TrustContent, } from "@personal-brand/api-client"; import type { BrandProfile } from "@personal-brand/api-client"; -import { projectBrandAliases } from "@personal-brand/api-client"; +import { projectBrandAliases, projectTrustPresentation } 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 { resolvePreviewSelection, type PreviewSelection } from "./preview-selection.js"; import { applyBrandPreviewValues, applyStandardBrandValues, + applyStandardEntityValues, applyPresentationValues, filterSectionsForPreviewTarget, presentationFieldName, @@ -50,6 +55,47 @@ interface PresentationEditorProps { error?: unknown; } +function trustSection( + declaration: NonNullable[number], + page: string, +): TemplateAdminSection { + const key = `trust:${declaration.type}`; + return { + key, + title: declaration.label, + description: declaration.help ?? "编辑当前展示内容。", + page, + target: "trust", + previewTargets: [{ key, label: declaration.label }], + fields: [ + { + key: "title", + binding: "trust.title", + label: declaration.adminFields.title, + input: "text" as const, + required: true, + }, + ...(["summary", "content"] as const) + .filter((field) => !declaration.hideStandardFields?.includes(field)) + .map((field) => ({ + key: field, + binding: `trust.${field}`, + label: declaration.adminFields[field], + input: "textarea" as const, + previewTarget: `trust:${declaration.type}`, + ...(field === "summary" && declaration.adminFields.summaryHelp + ? { help: declaration.adminFields.summaryHelp } + : {}), + ...(field === "content" && declaration.required ? { required: true } : {}), + })), + ...(declaration.configFields ?? []).map((field) => ({ + ...field, + previewTarget: `trust:${declaration.type}`, + })), + ].map((field) => ({ ...field, previewTarget: `trust:${declaration.type}` })), + }; +} + function renderField(field: TemplateAdminField) { if (field.input === "textarea") return ( @@ -102,7 +148,13 @@ export function PresentationEditor({ const navigate = useNavigate(); const breakpoints = Grid.useBreakpoint(); const [activePage, setActivePage] = useState(); - const [activeTarget, setActiveTarget] = useState(); + const [selection, setSelection] = useState(); + const [detailOfferingId, setDetailOfferingId] = useState(); + const [recordDraft, setRecordDraft] = useState<{ + source: "offering" | "trust"; + id: string; + values: PresentationValues; + }>(); const [previewConfig, setPreviewConfig] = useState(config ?? {}); const [previewBrandValues, setPreviewBrandValues] = useState>({}); const sections = useMemo(() => { @@ -153,24 +205,83 @@ export function PresentationEditor({ ? activePage : pageOptions[0]?.value; const visibleSections = sections.filter((section) => section.page === selectedPage); - 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 selectedSection = (templateContent?.admin.sections ?? []).find((section) => - section.previewTargets?.some((target) => target.key === selectedTarget?.key), + const recordSections = useMemo( + () => + (templateContent?.trustContentTypes ?? []) + .filter((item) => item.pages?.includes(selectedPage ?? "")) + .map((item) => trustSection(item, selectedPage ?? "home")), + [templateContent, selectedPage], ); + const visibleTargets = useMemo( + () => + [...(templateContent?.admin.sections ?? []), ...recordSections] + .filter((section) => section.page === selectedPage) + .flatMap((section) => + (section.previewTargets ?? []).map((target) => ({ + ...target, + page: section.page, + source: section.target, + })), + ), + [templateContent, selectedPage, recordSections], + ); + const activeTarget = selection?.targetKey; + const selectedTarget = visibleTargets.find((target) => target.key === activeTarget); + const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find( + (section) => + section.page === selectedPage && + section.previewTargets?.some((target) => target.key === selectedTarget?.key), + ); + const selectedRecordSource = + selectedTarget?.source === "offering" || selectedTarget?.source === "trust" + ? selectedTarget.source + : undefined; + const offeringsQuery = useQuery({ + queryKey: ["admin-offerings"], + queryFn: () => createApiClient().listAdminOfferings(), + enabled: selectedRecordSource === "offering", + }); + const trustQuery = useQuery({ + queryKey: ["trust-content"], + queryFn: () => createApiClient().listAdminTrustContent(), + enabled: selectedRecordSource === "trust", + }); + const selectedRecord = + selectedRecordSource === "offering" + ? offeringsQuery.data?.find((item) => item.id === selection?.recordId) + : selectedRecordSource === "trust" + ? trustQuery.data?.find((item) => item.id === selection?.recordId) + : undefined; const editableSections = filterSectionsForPreviewTarget( visibleSections.filter((section) => section.target === "brand"), selectedTarget?.key, ); - const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []); + const recordSection = useMemo( + () => + selectedSection && selection?.targetKey + ? { + ...selectedSection, + fields: selectedSection.fields.filter( + (field) => field.previewTarget === selection.targetKey, + ), + } + : undefined, + [selectedSection, selection?.targetKey], + ); + const handleTargetSelected = useCallback( + (next?: PreviewSelection) => + setSelection( + next + ? resolvePreviewSelection( + next.targetKey, + next.recordId, + visibleTargets, + selectedPage ?? "home", + ) + : undefined, + ), + [visibleTargets, selectedPage], + ); const relatedTargets = [ ...(templateContent?.admin.sections ?? []) .filter((section) => section.page === selectedPage && section.target !== "brand") @@ -235,6 +346,7 @@ export function PresentationEditor({ window.dispatchEvent(new Event("template-preview-refresh")); void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); + void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] }); }, @@ -248,7 +360,24 @@ export function PresentationEditor({ if (!pageOptions.some((item) => item.value === activePage)) setActivePage(pageOptions[0]?.value); }, [activePage, pageOptions]); - useEffect(() => setActiveTarget(undefined), [selectedPage]); + useEffect(() => setSelection(undefined), [selectedPage, templateContent?.displayName]); + useEffect(() => { + if (!selection?.recordId) return; + const records = + selectedTarget?.source === "trust" + ? previewWorkspace?.trustItems + : previewWorkspace?.offerings; + if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined); + }, [ + previewWorkspace?.offerings, + previewWorkspace?.trustItems, + selectedTarget?.source, + selection, + ]); + useEffect( + () => setRecordDraft(undefined), + [selection?.targetKey, selection?.recordId, selectedPage], + ); useEffect(() => { setPreviewConfig(config ?? {}); setPreviewBrandValues({}); @@ -270,6 +399,96 @@ export function PresentationEditor({ }, [brand, config, sections], ); + const draftWorkspace = useMemo(() => { + if (!previewWorkspace) return undefined; + const next: RuntimeWorkspace = { + ...previewWorkspace, + brand: projectBrandAliases( + { + ...previewWorkspace.brand, + ...(previewBrand as unknown as Record), + config: previewConfig, + }, + previewConfig, + ), + }; + if (!recordDraft || !selectedRecord || !recordSection || recordDraft.id !== selectedRecord.id) + return next; + const values = recordDraft.values; + const config = applyPresentationValues(selectedRecord.config, [recordSection], values); + const standard = applyStandardEntityValues( + selectedRecord as unknown as Record, + recordDraft.source, + [recordSection], + values, + ); + if (recordDraft.source === "trust") { + next.trustItems = next.trustItems.map((item) => + item.id === recordDraft.id + ? { + ...item, + title: typeof standard.title === "string" ? standard.title : item.title, + summary: typeof standard.summary === "string" ? standard.summary : item.summary, + content: typeof standard.content === "string" ? standard.content : item.content, + config, + } + : item, + ); + next.trustPresentation = projectTrustPresentation( + next.trustItems, + templateContent?.trustContentTypes ?? [], + ); + } else { + next.offerings = next.offerings.map((item) => + item.id === recordDraft.id + ? { + ...item, + name: typeof standard.name === "string" ? standard.name : item.name, + summary: + typeof standard.summary === "string" + ? standard.summary + : typeof standard.description === "string" + ? standard.description + : item.summary, + priceText: typeof standard.priceText === "string" ? standard.priceText : null, + coverUrl: typeof standard.coverUrl === "string" ? standard.coverUrl : null, + presentation: { + ...item.presentation, + ...config, + ...(config.presentation && typeof config.presentation === "object" + ? (config.presentation as Record) + : {}), + heroImage: + typeof config.detailHero === "string" + ? config.detailHero + : typeof standard.coverUrl === "string" + ? standard.coverUrl + : null, + details: { + ...item.presentation.details, + ...(config.details && typeof config.details === "object" + ? (config.details as Record) + : {}), + }, + }, + } + : item, + ); + } + return next; + }, [ + previewWorkspace, + previewBrand, + previewConfig, + recordDraft, + selectedRecord, + recordSection, + templateContent, + ]); + const selectedDetailOfferingId = + detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId) + ? detailOfferingId + : draftWorkspace?.offerings[0]?.id; return ( 页面预览 + {selectedPage === "detail" && draftWorkspace?.offerings.length ? ( +