Major refactoring cleanup: - Add new controller architecture (class-controller-*.php) - Add new settings-v2 UI (views/settings-v2/) - Add new CSS architecture (agentic-sidebar.css, tokens) - Add esbuild build pipeline (scripts/build.js, package.json) - Add composer dependencies (vendor/) - Add frontend src directory (assets/js/src/index.jsx) - Add documentation files - Remove old/obsolete files (class-settings.php, old CSS) This commits all pending changes from previous refactoring efforts.
7.3 KiB
7.3 KiB
WP Agentic Writer – Master Migration Blueprint
This document maps the entire 12,364-line sidebar.js monolith to a modular React architecture.
Rule #1 of this migration: Do not guess UI or logic. Every component must be ported 1:1 using the exact SVG paths, class names, state transitions, and DOM interactions found in the legacy file.
1. State Inventory & Context Architecture
The legacy file uses over 50 useState and useRef hooks in a single component. These must be split into specific Context Providers to avoid massive re-renders and prop drilling.
🗂️ SessionContext (Session & Tab Locking)
currentSessionId,availableSessions,isSessionActionLoadingsessionLock,lockHeartbeatRef,tabIdRef(Multi-tab concurrency locks)isHydratingSessionRef,memantoRestore,memantoRestoreFetchedRef- Dependencies: Needs
window.beforeunloadlisteners andsetIntervalfor heartbeat.
💬 ChatContext (Messages & Input)
messages,isLoading,showWelcome,welcomeKeywordInput,welcomeStartModeinput,isTextareaExpanded,inputRef,streamTargetRefmessagesSaveTimeoutRef,lastPersistedMessagesRefinClarification,questions,currentQuestionIndex,answers,detectedLanguage,clarificationModefocusKeywordSuggestions,selectedFocusKeyword,showCustomKeywordInput,customKeywordInput
🤖 AgentContext (Agent Execution & Plans)
agentMode(chat, planning, writing)activeOperation,executionStopped,stopExecutionRefactiveAbortControllerRef,activeReaderReflastGenerationRequestRef,lastExecuteRequestRef,lastRefineRequestRef,lastChatRequestRefwritingState,isWritingStateLoading,currentPlanRefsectionInsertIndexRef,activeSectionIdRef,sectionBlocksRef,blockSectionRef
📝 EditorContext (WP Block Bridge & Locks)
isEditorLocked,isRefinementLocked,refiningBlockIdslockedEditableNodesRef,lockedBlockIdsRef,refinementDecoratedIdsRefworkspaceSnapshot,isWorkspaceCollapsedaiUndoStack(MAX_UNDO_STACK)pendingRefinement,pendingEditPlan,pendingDiffBlockIdsrefineAllConfirm,refineAllConfirmResolverRef,skipRefineAllConfirmRef
⚙️ SettingsContext (Config, Cost, SEO)
postConfig,isConfigLoading,isConfigSaving,configErrorcost,monthlyBudget,providerInfoseoAudit,isSeoAuditing,isGeneratingMeta,activeSeoFixKey
2. WordPress API Bridge
All wp.* calls must be abstracted into dedicated hooks/services so components remain clean.
wp.data.select('core/editor'):getCurrentPostId,getBlocks,getEditedPostAttributewp.data.dispatch('core/editor'):updateBlockAttributes,replaceBlocks,insertBlocks,removeBlocks,editPostwp.data.subscribe: Block mutation listeners (blockMutationEvent).wp.element:createElement,useState,useEffect,useCallback,useRef,useMemowp.components:Panel,TextControl,TextareaControl,CheckboxControl,Button- Custom DOM Manipulation: The legacy code manipulates the DOM directly (e.g., locking
.editor-styles-wrapper [contenteditable="true"]). This needs a safeuseEditorLockhook.
3. UI Component Mapping
Exact mapping of legacy render* functions to new components. Note: Copy exact HTML structures, SVGs, and class names from legacy.
Layout & Shell
AgenticWriterSidebar→src/components/Sidebar.jsxrenderGlobalStatusBar→src/components/shell/StatusBar.jsx(Contains ALL main navigation icons)
Tab: Chat (renderChatTab)
renderWelcomeScreen→src/components/chat/WelcomeScreen.jsxrenderWritingEmptyState→src/components/chat/WritingEmptyState.jsxrenderFocusKeywordBar→src/components/chat/FocusKeywordBar.jsxrenderMessages→src/components/chat/MessageList.jsxrenderMessageContent→src/components/chat/MessageItem.jsxinlineMarkdownToHtml/markdownToHtml→src/utils/markdownRenderer.js
renderAgentWorkspaceCard→src/components/chat/AgentWorkspaceCard.jsxrenderContextIndicator→src/components/chat/ContextIndicator.jsxrenderContextualAction→src/components/chat/ContextualActions.jsxrenderClarification→src/components/chat/ClarificationOverlay.jsx- (Chat Input) →
src/components/chat/ChatInput.jsx
Tab: Config (renderConfigTab)
renderConfigTab→src/components/config/ConfigTab.jsx
Tab: Cost (renderCostTab)
renderCostTab→src/components/cost/CostTab.jsx
Shared / Modals / Overlays
renderRefineAllConfirmModal→src/components/shared/RefineConfirmModal.jsx- Mentions (
showMentionAutocomplete) →src/components/editor/MentionAutocomplete.jsx - Slash Commands (
showSlashAutocomplete) →src/components/editor/SlashCommandMenu.jsx
4. Business Logic & Feature Epics (Migration Phases)
Epic 1: Session & Shell Initialization
- Connect
wp.datato fetch Post ID. - Implement multi-tab session locking (
acquireSessionLock,releaseSessionLock,startLockHeartbeat). - Implement session persistence and hydration (
loadPostSessions,hydrateSessionStateFromMessages,flushOnUnload). - Build the shell:
Sidebar,StatusBar(with exact SVGs for Chat, Config, Cost, Undo, Session List).
Epic 2: Core Chat & UI
- Port
WelcomeScreen(Exact UI: Agentic Writer title, pill buttons, focus keyword). - Port
ChatInput(Auto-expanding textarea, slash/mention triggers). - Port
MessageListand custom Markdown Renderer (MUST support syntax highlighting, links, lists exactly as legacy). - Implement
sendMessagebasic streaming to API.
Epic 3: Mentions & Slash Commands
- Port
extractMentionsFromText,resolveBlockMentions. - Port the visual UI for
@block selection (showing block content previews). - Port
/command definitions (parseInsertCommand,getSlashOptions).
Epic 4: AI Editor Actions & Undo Stack
- Implement Editor Lock hook (
shouldBlockEditorInput, blocking keydown events). - Implement
aiUndoStack(captureEditorSnapshot,pushUndoSnapshot,undoLastAiOperation). - Port Refinement Actions (
handleChatRefinement,handleTitleRefinement). - Port Diff rendering logic (handling insertions/replacements).
Epic 5: The Agentic Planner
- Port
streamGeneratePlanandexecutePlanFromCard. - Port section block management (
loadSectionBlocks,saveSectionBlocks,upsertSectionBlock). - Port workspace logic (
buildWorkspaceSnapshot,toggleAgentWorkspace).
Epic 6: SEO & Utilities
- Port
runSeoAuditandhandleSeoAuditFix. - Port
generateMetaDescription. - Port
savePostConfig,updatePostConfig.
5. Execution Rules for Claude
- Never guess the DOM: When porting a
renderXfunction, grep the legacysidebar.jsfor that function, copy its exact element structure, and translate it to JSX. - Preserve CSS hooks: Do not rename classes. If a legacy element has
.wpaw-status-icon-btn, use exactly that. - Migrate one slice at a time: e.g., Set up Contexts first, then
StatusBar, thenWelcomeScreen. Do not jump around. - Test integrations locally: Verify that WordPress
wp.dataandwp.elementresolve correctly after Webpack compilation.