Skip to content

Commit 699d119

Browse files
committed
Fix insert link flow for new page creation
🔧 Fixed URL generation for new page links: - Updated SlateEditor to generate proper URLs: /new?title=PageName instead of /new:PageName - Added isNew flag to LinkElement type definition - Fixed malformed URLs that were breaking navigation ✨ Added automatic new page creation: - Extract new page references from content during save - Automatically create referenced pages with empty content - Works for both new page creation and existing page updates - Ensures all linked pages exist after save operation 🎯 Improved user experience: - Insert link flow now works correctly for new pages - Proper URL parameters for title pre-filling - Seamless page creation workflow - No more broken links to non-existent pages Technical changes: - Updated insertLink function in SlateEditor.tsx - Added extractNewPageReferences and createNewPagesFromLinks helpers - Enhanced save process in both new/page.tsx and PageView.tsx - Proper URL encoding for page titles with special characters
1 parent bd799fa commit 699d119

File tree

3 files changed

+141
-2
lines changed

3 files changed

+141
-2
lines changed

app/components/editor/SlateEditor.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ type LinkElement = {
5252
isOwned: boolean;
5353
isSuggestion?: boolean; // New flag for link suggestions
5454
suggestionData?: any; // Store original suggestion data for confirmation
55+
isNew?: boolean; // Flag for new pages that need to be created
5556
children: Descendant[];
5657
};
5758

@@ -713,12 +714,13 @@ const SlateEditor: React.FC<SlateEditorProps> = ({
713714
// Insert new link
714715
const link: LinkElement = {
715716
type: 'link',
716-
url: linkData.url,
717+
url: linkData.url || (linkData.isNew ? `/new?title=${encodeURIComponent(linkData.pageTitle)}` : `/${linkData.pageId}`),
717718
pageId: linkData.pageId,
718719
pageTitle: linkData.pageTitle,
719720
isExternal: linkData.type === 'external',
720721
isPublic: true,
721722
isOwned: false,
723+
isNew: linkData.isNew, // Add isNew flag to the link element
722724
children: [{ text: linkData.text || linkData.pageTitle || 'Link' }]
723725
};
724726

@@ -734,12 +736,13 @@ const SlateEditor: React.FC<SlateEditorProps> = ({
734736
editor,
735737
{
736738
type: 'link',
737-
url: linkData.url,
739+
url: linkData.url || (linkData.isNew ? `/new?title=${encodeURIComponent(linkData.pageTitle)}` : `/${linkData.pageId}`),
738740
pageId: linkData.pageId,
739741
pageTitle: linkData.pageTitle,
740742
isExternal: linkData.type === 'external',
741743
isPublic: true,
742744
isOwned: false,
745+
isNew: linkData.isNew, // Add isNew flag to the link element
743746
children: []
744747
},
745748
{ split: true }

app/components/pages/PageView.tsx

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,67 @@ export default function PageView({
800800

801801
// No need for handleSetIsEditing - always in edit mode
802802

803+
// Helper function to extract new page references from content
804+
const extractNewPageReferences = (content: any[]): Array<{pageId: string, title: string}> => {
805+
const newPages: Array<{pageId: string, title: string}> = [];
806+
807+
const processNode = (node: any) => {
808+
if (node.type === 'link' && node.isNew && node.pageId && node.pageTitle) {
809+
newPages.push({
810+
pageId: node.pageId,
811+
title: node.pageTitle
812+
});
813+
}
814+
815+
if (node.children) {
816+
node.children.forEach(processNode);
817+
}
818+
};
819+
820+
content.forEach(processNode);
821+
return newPages;
822+
};
823+
824+
// Helper function to create new pages referenced in links
825+
const createNewPagesFromLinks = async (newPageRefs: Array<{pageId: string, title: string}>): Promise<void> => {
826+
if (!user?.uid || newPageRefs.length === 0) return;
827+
828+
console.log('🔵 PAGE SAVE: Creating new pages from links:', newPageRefs);
829+
830+
for (const pageRef of newPageRefs) {
831+
try {
832+
const pageData = {
833+
title: pageRef.title,
834+
content: JSON.stringify([{ type: 'paragraph', children: [{ text: '' }] }]), // Empty content
835+
userId: user.uid,
836+
username: user.username || user.displayName || 'Anonymous',
837+
lastModified: new Date().toISOString(),
838+
isReply: false,
839+
groupId: null,
840+
customDate: null
841+
};
842+
843+
const response = await fetch('/api/pages', {
844+
method: 'POST',
845+
headers: {
846+
'Content-Type': 'application/json',
847+
},
848+
body: JSON.stringify(pageData),
849+
credentials: 'include'
850+
});
851+
852+
if (response.ok) {
853+
const result = await response.json();
854+
console.log('✅ PAGE SAVE: Created new page from link:', { title: pageRef.title, id: result.id });
855+
} else {
856+
console.error('🔴 PAGE SAVE: Failed to create new page from link:', pageRef.title);
857+
}
858+
} catch (error) {
859+
console.error('🔴 PAGE SAVE: Error creating new page from link:', error);
860+
}
861+
}
862+
};
863+
803864
const handleSave = useCallback(async (passedContent?: any) => {
804865
console.log('🔵 PAGE SAVE: Save initiated', {
805866
pageId,
@@ -857,6 +918,13 @@ export default function PageView({
857918
contentToSaveSample: contentToSave ? JSON.stringify(contentToSave).substring(0, 200) : 'null'
858919
});
859920

921+
// Extract and create new pages referenced in links before saving the main page
922+
const newPageRefs = extractNewPageReferences(contentToSave);
923+
if (newPageRefs.length > 0) {
924+
console.log('🔵 PAGE SAVE: Found new page references, creating them first:', newPageRefs);
925+
await createNewPagesFromLinks(newPageRefs);
926+
}
927+
860928
const updateData = {
861929
id: pageId,
862930
title: title.trim(),

app/new/page.tsx

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,67 @@ function NewPageContent() {
416416
setHasUnsavedChanges(hasContentChanged || hasTitleChanged);
417417
}, [hasContentChanged, hasTitleChanged]);
418418

419+
// Helper function to extract new page references from content
420+
const extractNewPageReferences = (content: EditorNode[]): Array<{pageId: string, title: string}> => {
421+
const newPages: Array<{pageId: string, title: string}> = [];
422+
423+
const processNode = (node: any) => {
424+
if (node.type === 'link' && node.isNew && node.pageId && node.pageTitle) {
425+
newPages.push({
426+
pageId: node.pageId,
427+
title: node.pageTitle
428+
});
429+
}
430+
431+
if (node.children) {
432+
node.children.forEach(processNode);
433+
}
434+
};
435+
436+
content.forEach(processNode);
437+
return newPages;
438+
};
439+
440+
// Helper function to create new pages referenced in links
441+
const createNewPagesFromLinks = async (newPageRefs: Array<{pageId: string, title: string}>): Promise<void> => {
442+
if (!user?.uid || newPageRefs.length === 0) return;
443+
444+
console.log('🔵 DEBUG: Creating new pages from links:', newPageRefs);
445+
446+
for (const pageRef of newPageRefs) {
447+
try {
448+
const pageData = {
449+
title: pageRef.title,
450+
content: JSON.stringify([{ type: 'paragraph', children: [{ text: '' }] }]), // Empty content
451+
userId: user.uid,
452+
username: user.username || user.displayName || 'Anonymous',
453+
lastModified: new Date().toISOString(),
454+
isReply: false,
455+
groupId: null,
456+
customDate: null
457+
};
458+
459+
const response = await fetch('/api/pages', {
460+
method: 'POST',
461+
headers: {
462+
'Content-Type': 'application/json',
463+
},
464+
body: JSON.stringify(pageData),
465+
credentials: 'include'
466+
});
467+
468+
if (response.ok) {
469+
const result = await response.json();
470+
console.log('✅ DEBUG: Created new page from link:', { title: pageRef.title, id: result.id });
471+
} else {
472+
console.error('🔴 DEBUG: Failed to create new page from link:', pageRef.title);
473+
}
474+
} catch (error) {
475+
console.error('🔴 DEBUG: Error creating new page from link:', error);
476+
}
477+
}
478+
};
479+
419480
// Handle save
420481
const handleSave = async (content: EditorNode[], saveMethod: 'keyboard' | 'button' = 'button'): Promise<boolean> => {
421482
console.log('🔵 DEBUG: handleSave called with:', {
@@ -680,6 +741,13 @@ function NewPageContent() {
680741

681742
return true;
682743
} else {
744+
// Extract and create new pages referenced in links before saving the main page
745+
const newPageRefs = extractNewPageReferences(finalContent);
746+
if (newPageRefs.length > 0) {
747+
console.log('🔵 DEBUG: Found new page references, creating them first:', newPageRefs);
748+
await createNewPagesFromLinks(newPageRefs);
749+
}
750+
683751
// Normal page creation for verified users - use API route instead of direct Firestore
684752
console.log('🔵 DEBUG: About to call API route with data:', { ...data, content: '(content omitted)' });
685753

0 commit comments

Comments
 (0)