diff --git a/PlotLine.Tests/Browser/context-calendar-development.cjs b/PlotLine.Tests/Browser/context-calendar-development.cjs new file mode 100644 index 00000000..8b944e7b --- /dev/null +++ b/PlotLine.Tests/Browser/context-calendar-development.cjs @@ -0,0 +1,23 @@ +// Real Development forms, saved chronology, isolated registered project and ordinary writer. +const assert=require('node:assert/strict'),{open}=require('./dev-acceptance.cjs'); +let session,stage='login'; +(async()=>{try{ + session=await open();let p=session.page;const project=await session.project(); + const book=await session.create('Books','?projectId='+project,{BookTitle:'Calendar first',BookNumber:1}),otherBook=await session.create('Books','?projectId='+project,{BookTitle:'Calendar second',BookNumber:2}); + const chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Same chapter',ChapterNumber:1}),otherChapter=await session.create('Chapters','?bookId='+otherBook,{ChapterTitle:'Other book chapter',ChapterNumber:1}),undatedChapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Undated chapter',ChapterNumber:2}); + async function scene(ch,title,date){await session.goto('/Scenes/Create?chapterId='+ch);await p.locator('#SceneTitle').fill(title);if(date){const exact=await p.locator('#TimeModeID option').evaluateAll(ns=>ns.find(n=>/exact/i.test(n.textContent))?.value);assert(exact);await p.locator('#TimeModeID').selectOption(exact);await p.locator('#StartDateTime').fill(date+'T10:00');}await p.getByRole('button',{name:'Create scene',exact:true}).click();await p.waitForURL('**/Scenes/Edit/*');return Number(new URL(p.url()).pathname.split('/').at(-1));} + stage='saved chronology';const first=await scene(chapter,'First dated scene','1983-11-19'),second=await scene(chapter,'Second dated scene','1983-11-19'),other=await scene(otherChapter,'Other book collision','1983-11-19'),undated=await scene(chapter,'Undated with chapter fallback'),empty=await scene(undatedChapter,'Undated without fallback'); + const feature=`/Writing/Context?projectId=${project}&bookId=${book}&chapterId=${chapter}&sceneId=${first}&pinned=true`,ctx=await p.context().newPage();await ctx.setViewportSize({width:1280,height:800});await ctx.goto('https://dev.plotdirector.com'+feature);await ctx.selectOption('[data-context-pane="0"] [data-context-tab]','calendar');const pane=ctx.locator('[data-context-pane="0"]'),day=d=>pane.locator(`[data-calendar-date="${d}"]`); + stage='follow, deduplication and collision';await day('1983-11-19').waitFor();assert.equal(await day('1983-11-19').getAttribute('aria-current'),'date');assert.equal(await day('1983-11-19').locator('.context-calendar-chapter').textContent(),'Ch 1');assert.equal(await day('1983-11-19').locator('small').count(),0);await pane.locator('[data-calendar-books]').selectOption('all');assert.equal(await day('1983-11-19').locator('small').textContent(),' +1');await pane.locator('[data-calendar-details]>details').first().locator('summary').first().click();await pane.getByText('Scene 1 · First dated scene',{exact:true}).click();assert.equal(await pane.getByRole('link',{name:'Open scene in main window'}).count(),1); + await ctx.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');const posts=[];ctx.on('request',r=>{if(r.method()==='POST'&&/NarrativeFocus|NativeCompanion.*Navigate/.test(r.url()))posts.push(new URL(r.url()).pathname);});const focus=await ctx.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position}));const shared=()=>ctx.evaluate(async({project,book})=>(await(await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`)).json()),{project,book});const before=await shared(); + stage='browse empty dates and six-row viewport';await day('1983-11-20').click();await pane.locator('[data-calendar-month]').fill('2020-08');await pane.locator('[data-calendar-month]').dispatchEvent('change');assert.equal(await pane.locator('[data-calendar-grid] button').count(),42);const geometry=await pane.locator('[data-calendar-grid]').evaluate(n=>({bottom:n.getBoundingClientRect().bottom,scroll:n.scrollHeight,height:n.clientHeight,viewport:innerHeight}));assert(geometry.bottom<=geometry.viewport);assert(geometry.scroll<=geometry.height+1);await day('2020-08-15').click();assert.match(await pane.locator('[data-calendar-details]').textContent(),/No dated/);await pane.locator('[data-calendar-from]').fill('2020-08-01');await pane.locator('[data-calendar-from]').dispatchEvent('change');assert.equal(await pane.locator('[data-calendar-elapsed]').textContent(),'14 days to selected date'); + stage='real saved date refresh while held';await session.goto('/Scenes/SceneDetailsEditor?sceneId='+first);const exact=await p.locator('[name=TimeModeID] option').evaluateAll(ns=>ns.find(n=>/exact/i.test(n.textContent))?.value);await p.locator('[name=TimeModeID]').selectOption(exact);await p.locator('[name=StartDateTime]').fill('1984-02-29T10:00');await Promise.all([p.waitForResponse(r=>r.url().includes('/Scenes/SaveSceneDetails')&&r.status()===200),p.getByRole('button',{name:'Save details',exact:true}).click()]);await ctx.waitForFunction(()=>document.querySelector('[data-calendar-status]').textContent.includes('29 February 1984'));assert.equal(await pane.locator('[data-calendar-month]').inputValue(),'2020-08');assert.equal(await day('2020-08-15').getAttribute('aria-pressed'),'true');assert.deepEqual(await ctx.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position})),focus);assert.deepEqual(posts,[]);const after=await shared();assert.equal(after.version,before.version);assert.equal(after.sceneID,before.sceneID); + stage='sibling-book date save refresh';await session.goto('/Scenes/SceneDetailsEditor?sceneId='+other);const otherExact=await p.locator('[name=TimeModeID] option').evaluateAll(ns=>ns.find(n=>/exact/i.test(n.textContent))?.value);await p.locator('[name=TimeModeID]').selectOption(otherExact);await p.locator('[name=StartDateTime]').fill('1984-03-01T10:00');await Promise.all([ctx.waitForResponse(r=>r.url().includes('/Calendar/State')&&r.status()===200),p.getByRole('button',{name:'Save details',exact:true}).click()]);await pane.locator('[data-calendar-month]').fill('1984-03');await pane.locator('[data-calendar-month]').dispatchEvent('change');assert.match(await day('1984-03-01').textContent(),/Book 2/);assert.equal((await shared()).version,before.version);assert.deepEqual(posts,[]); + stage='Return to Scene and leap day';await pane.locator('[data-calendar-return]').click();assert.equal(await pane.locator('[data-calendar-month]').inputValue(),'1984-02');assert.equal(await day('1984-02-29').getAttribute('aria-current'),'date'); + stage='main scene link retains focus';await session.goto('/Locations?projectId='+project);await p.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');await pane.locator('[data-calendar-details]>details summary').first().click();await pane.getByText('Scene 1 · First dated scene',{exact:true}).click();const contextUrl=ctx.url();await pane.getByRole('link',{name:'Open scene in main window'}).click();await p.waitForURL('**/Scenes/Edit/'+first+'?retainNarrativeFocus=true');assert.equal(ctx.url(),contextUrl);assert.equal((await shared()).version,before.version);assert.deepEqual(posts,[]); + stage='chapter fallback and completely undated retention';await ctx.selectOption('[data-context-scene]',String(undated));await ctx.waitForFunction(()=>document.querySelector('[data-calendar-status]').textContent.includes('chapter (first dated scene)'));assert.equal(await pane.locator('[data-calendar-month]').inputValue(),'1984-02');await ctx.selectOption('[data-context-scene]',String(empty));await ctx.waitForFunction(()=>document.querySelector('[data-calendar-status]').textContent.includes('undated; month retained'));assert.equal(await pane.locator('[data-calendar-month]').inputValue(),'1984-02'); + stage='split panes and themes';await ctx.selectOption('[data-context-layout]','columns');await ctx.selectOption('[data-context-pane="1"] [data-context-tab]','calendar');await ctx.locator('[data-context-pane="1"] [data-calendar-grid] button').first().waitFor();await pane.locator('[data-calendar-month]').fill('1983-11');await pane.locator('[data-calendar-month]').dispatchEvent('change');assert.equal(await ctx.locator('[data-context-pane="1"] [data-calendar-month]').inputValue(),new Date().toISOString().slice(0,7));for(const layout of ['columns','rows']){await ctx.selectOption('[data-context-layout]',layout);for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue'])await ctx.evaluate(t=>{localStorage.setItem('plotdirector.applicationTheme',t);window.dispatchEvent(new StorageEvent('storage',{key:'plotdirector.applicationTheme',newValue:t}));},theme);}await ctx.setViewportSize({width:460,height:850});assert.equal(await ctx.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),true); + stage='fresh login persistence';await session.close();session=await open();p=session.page;await session.goto('/Scenes/SceneDetailsEditor?sceneId='+first);assert.match(await p.locator('[name=StartDateTime]').inputValue(),/^1984-02-29T10:00/);await session.goto(feature);await p.selectOption('[data-context-pane="0"] [data-context-tab]','calendar');await p.locator('[data-calendar-date="1984-02-29"]').waitFor();assert.equal(await p.locator('[data-calendar-month]').inputValue(),'1984-02'); + console.log(JSON.stringify({passed:true,checks:['real saved chronology and fresh-login persistence','third Saturday, leap date and six rows','chapter dedup and all-book collisions','empty date and elapsed days','held real save refresh preserves selected month and day','zero focus mutation during browsing refresh and main link','Return to Scene','chapter fallback and undated month retention','independent split panes rows columns seven themes and narrow'],featureUrl:'https://dev.plotdirector.com'+feature,limitation:'No independent chapter date exists; fallback is first dated scene in chapter. No live Word instance; zero focus publication/navigation requests verified.'})); + }catch(error){console.error('Calendar acceptance failed at '+stage+' ('+error.name+'); no credentials logged.');if(error.name==='AssertionError')console.error(error.message);process.exitCode=1;}finally{if(session){try{await session.cleanup();console.log('PASS disposable project cleanup');}catch{console.error('Cleanup incomplete; preserve journal.');process.exitCode=1;}finally{await session.close();}}} +})(); diff --git a/PlotLine.Tests/Browser/context-calendar-model.test.cjs b/PlotLine.Tests/Browser/context-calendar-model.test.cjs new file mode 100644 index 00000000..0f0cd209 --- /dev/null +++ b/PlotLine.Tests/Browser/context-calendar-model.test.cjs @@ -0,0 +1,6 @@ +const {test}=require('node:test'),assert=require('node:assert/strict'),m=require('../../PlotLine/wwwroot/js/context-calendar-model.js'); +test('Monday-first grid places 19 November 1983 on the third Saturday',()=>{const days=m.grid('1983-11');assert.equal(days.indexOf('1983-11-19'),19);assert.equal(days[5],'1983-11-05');assert.equal(days[12],'1983-11-12');}); +test('leap days, six-row months and Gregorian boundaries',()=>{assert(m.grid('2000-02').includes('2000-02-29'));assert(!m.grid('1900-02').includes('1900-02-29'));assert.equal(m.grid('2020-08').length,42);assert.equal(m.shift('1983-12',1),'1984-01');assert.equal(m.shift('1984-01',-1),'1983-12');assert.equal(m.shift('0001-01',-1),null);assert.equal(m.shift('9999-12',1),null);assert(m.grid('9999-12').includes('9999-12-31'));assert.equal(m.date('0000-01-01'),null);}); +test('chapter references deduplicate scenes by book, chapter and date, preserving book collisions',()=>{const scenes=[{bookID:1,chapterID:2,date:'1983-11-19',sceneID:1},{bookID:1,chapterID:2,date:'1983-11-19',sceneID:2},{bookID:2,chapterID:2,date:'1983-11-19',sceneID:3},{bookID:1,chapterID:2,date:'1983-11-20',sceneID:4},{bookID:1,chapterID:2,date:null,sceneID:5}];const groups=m.chapters(scenes,'1983-11-19');assert.equal(groups.length,2);assert.equal(groups[0].scenes.length,2);assert.equal(m.chapters(scenes,'1983-11-21').length,0);assert.equal(m.chapters(scenes,null).length,0);}); +test('scene date takes precedence; undated scenes use first dated chapter scene without inventing dates',()=>{const scenes=[{bookID:1,chapterID:1,sceneID:1,sceneNumber:2,date:'1983-11-19'},{bookID:1,chapterID:1,sceneID:2,sceneNumber:1,date:'1983-11-20'},{bookID:1,chapterID:1,sceneID:3,date:null}];assert.equal(m.manuscript(scenes,{bookId:1,chapterId:1,sceneId:1}).date,'1983-11-19');assert.equal(m.manuscript(scenes,{bookId:1,chapterId:1,sceneId:3}).date,'1983-11-20');assert.equal(m.manuscript(scenes,{bookId:1,chapterId:2}).date,null);}); +test('elapsed days is date-only across DST, leap and year boundaries',()=>{assert.equal(m.elapsed('2024-03-30','2024-04-01'),2);assert.equal(m.elapsed('2024-02-28','2024-03-01'),2);assert.equal(m.elapsed('1984-01-01','1983-12-31'),-1);assert.equal(m.elapsed('',null),null);}); diff --git a/PlotLine.Tests/Browser/context-calendar.cjs b/PlotLine.Tests/Browser/context-calendar.cjs new file mode 100644 index 00000000..ead09f2a --- /dev/null +++ b/PlotLine.Tests/Browser/context-calendar.cjs @@ -0,0 +1,6 @@ +const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict'); +(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage({viewport:{width:1200,height:800}});let date='1983-11-19',reads=0;await page.route('**/Writing/Context/Calendar/State*',r=>{reads++;return r.fulfill({json:{books:[],scenes:[{bookID:1,bookLabel:'Book 1',chapterID:1,chapterNumber:1,chapterTitle:'One',sceneID:1,sceneNumber:1,title:'First',date},{bookID:1,bookLabel:'Book 1',chapterID:1,chapterNumber:1,chapterTitle:'One',sceneID:2,sceneNumber:2,title:'Second',date},{bookID:2,bookLabel:'Book 2',chapterID:2,chapterNumber:1,chapterTitle:'Two',sceneID:3,sceneNumber:1,title:'Other book',date}]}});});await page.route('https://calendar.test/',r=>r.fulfill({body:'',contentType:'text/html'}));await page.goto('https://calendar.test'); +const partial=fs.readFileSync('PlotLine/Views/Writing/_ContextCalendar.cshtml','utf8').split('\n').slice(2).join('\n');await page.setContent('
'+partial+'
');await page.addStyleTag({content:fs.readFileSync('PlotLine/wwwroot/css/context-calendar.css','utf8')});for(const file of ['context-calendar-model.js','context-calendar.js'])await page.addScriptTag({path:'PlotLine/wwwroot/js/'+file});await page.evaluate(()=>{window.node=document.querySelector('[data-context-calendar]');window.life=PlotDirectorContextLifecycles.calendar;life.mount(node,{position:{bookId:1,chapterId:1,sceneId:1}});});await page.locator('[data-calendar-date="1983-11-19"]').waitFor();assert.equal(await page.locator('[data-calendar-date="1983-11-19"] .context-calendar-chapter').textContent(),'Ch 1');assert.equal(await page.locator('[data-calendar-date="1983-11-19"] small').count(),0); +await page.selectOption('[data-calendar-books]','all');assert.equal(await page.locator('[data-calendar-date="1983-11-19"] small').textContent(),' +1');await page.locator('[data-calendar-date="1983-11-20"]').click();await page.evaluate(()=>life.onPosition(node,{bookId:1,chapterId:2,sceneId:99}));assert.equal(await page.locator('[data-calendar-month]').inputValue(),'1983-11');assert.equal(await page.locator('[data-calendar-date="1983-11-20"]').getAttribute('aria-pressed'),'true'); +await page.locator('[data-calendar-month]').fill('2020-08');await page.locator('[data-calendar-month]').dispatchEvent('change');assert.equal(await page.locator('[data-calendar-grid] button').count(),42);assert((await page.locator('[data-calendar-grid]').boundingBox()).height<=400);await page.evaluate(()=>life.onPosition(node,{bookId:1,chapterId:1,sceneId:1}));assert.equal(await page.locator('[data-calendar-month]').inputValue(),'2020-08');date='1984-01-01';await page.evaluate(()=>life.onInvalidation(node));await page.waitForFunction(()=>document.querySelector('[data-calendar-status]').textContent.includes('1984'));assert.equal(await page.locator('[data-calendar-month]').inputValue(),'2020-08');await page.locator('[data-calendar-return]').click();assert.equal(await page.locator('[data-calendar-month]').inputValue(),'1984-01');assert.equal(await page.locator('[data-calendar-date="1984-01-01"]').getAttribute('aria-current'),'date');assert(reads>=2); +await page.evaluate(()=>{life.dispose(node);life.mount(node,{position:{bookId:1,chapterId:1,sceneId:1}});});await page.locator('[data-calendar-date="1984-01-01"]').waitFor();console.log('PASS Calendar lifecycle: deduplication, all-books collision, local hold, undated position, six-row geometry, saved refresh preserves browsing, Return to Scene and remount');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine/Controllers/ContextCalendarController.cs b/PlotLine/Controllers/ContextCalendarController.cs new file mode 100644 index 00000000..7adf3b6a --- /dev/null +++ b/PlotLine/Controllers/ContextCalendarController.cs @@ -0,0 +1,54 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PlotLine.Data; +using PlotLine.Services; + +namespace PlotLine.Controllers; + +[Authorize, Route("Writing/Context/Calendar"), ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] +public sealed class ContextCalendarController(IWordCompanionRepository access, IBookRepository books, + ICurrentUserService user, ITimelineRepository timeline) : Controller +{ + private async Task Project(int bookId) + { + if (!user.UserId.HasValue || await access.GetBookStructureAsync(bookId, user.UserId.Value) == null) return null; + return (await books.GetAsync(bookId))?.ProjectID; + } + + [HttpGet("")] + public async Task Panel(int bookId, int? projectId, int? chapterId, int? sceneId) + { + var project = await Project(bookId); + if (!project.HasValue) return Forbid(); + if (!ModelState.IsValid || projectId.HasValue && project != projectId) return BadRequest(); + var structure = await access.GetBookStructureAsync(bookId, user.UserId!.Value); + var chapter = structure!.Chapters.FirstOrDefault(c => sceneId.HasValue + ? c.Scenes.Any(s => s.SceneId == sceneId) : c.ChapterId == chapterId); + if ((sceneId.HasValue || chapterId.HasValue) && chapter == null || chapterId.HasValue && chapter?.ChapterId != chapterId) return BadRequest(); + return PartialView("~/Views/Writing/_ContextCalendar.cshtml", new ContextCalendarScope(project.Value, bookId, chapter?.ChapterId, sceneId)); + } + + [HttpGet("State")] + public async Task State(int bookId) + { + var project = await Project(bookId); + if (!project.HasValue) return Forbid(); + // Reuse the canonical Story Calendar/Timeline stored-procedure projection. + // Project access was verified before loading cross-book reference data. + var data = await timeline.GetByProjectAsync(project.Value, null, false, [], false); + if (data.Project == null) return NotFound(); + var chapters = data.Chapters.Where(c => !c.IsArchived).ToDictionary(c => c.ChapterID); + var projectBooks = data.Books.Where(b => !b.IsArchived).ToDictionary(b => b.BookID); + return Json(new { scenes = data.Scenes.Where(s => !s.IsArchived && chapters.ContainsKey(s.ChapterID)) + .Where(s => projectBooks.ContainsKey(chapters[s.ChapterID].BookID)).Select(s => { + var chapter = chapters[s.ChapterID]; + var book = projectBooks[chapter.BookID]; + return new { book.BookID, bookLabel = $"Book {book.BookNumber}", bookTitle = book.BookDisplayTitle, + chapter.ChapterID, chapter.ChapterNumber, chapter.ChapterTitle, s.SceneID, s.SceneNumber, + title = string.IsNullOrWhiteSpace(s.SceneTitle) ? $"Scene {s.SceneNumber:g}" : s.SceneTitle, + date = s.StartDateTime?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) }; + }) }); + } +} + +public sealed record ContextCalendarScope(int ProjectID, int BookID, int? ChapterID, int? SceneID); diff --git a/PlotLine/Views/Writing/Context.cshtml b/PlotLine/Views/Writing/Context.cshtml index b3f5dc5d..25982229 100644 --- a/PlotLine/Views/Writing/Context.cshtml +++ b/PlotLine/Views/Writing/Context.cshtml @@ -11,11 +11,13 @@ new { id = "relationships", displayName = "Relationships", endpoint = Url.Action("ContextRelationships", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "relationships", refreshGuard = "defer-while-dirty-or-busy", actions = new[] { "relationship.focus" } }, new { id = "locations", displayName = "Locations", endpoint = Url.Action("ContextLocations", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "spatial", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, new { id = "maps", displayName = "Maps", endpoint = Url.Action("ContextMaps", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "spatial", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, + new { id = "calendar", displayName = "Calendar", endpoint = Url.Action("Panel", "ContextCalendar"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "calendar", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() }, new { id = "floorplans", displayName = "Floor Plans", endpoint = Url.Action("ContextFloorPlans", "Writing"), scope = "Scene", contentRefresh = "relevant-scope", lifecycle = "spatial", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty() } }; } +
+ + diff --git a/PlotLine/Views/Writing/_ContextCalendar.cshtml b/PlotLine/Views/Writing/_ContextCalendar.cshtml new file mode 100644 index 00000000..953bf8a4 --- /dev/null +++ b/PlotLine/Views/Writing/_ContextCalendar.cshtml @@ -0,0 +1,23 @@ +@model PlotLine.Controllers.ContextCalendarScope +@{ Layout = null; } +
+
+ + + + + + +
+

+
+
+ + +
+ ● Manuscript date · outlined date is your selection +
+ +
+
+
diff --git a/PlotLine/wwwroot/css/context-calendar.css b/PlotLine/wwwroot/css/context-calendar.css new file mode 100644 index 00000000..54d9caa8 --- /dev/null +++ b/PlotLine/wwwroot/css/context-calendar.css @@ -0,0 +1,20 @@ +.context-calendar{min-width:0;color:var(--plotline-ink);} +.context-calendar-controls{display:flex;flex-wrap:wrap;align-items:end;gap:.35rem;} +.context-calendar-controls label,.context-calendar-elapsed label{display:flex;gap:.3rem;align-items:center;min-width:0;} +.context-calendar input,.context-calendar select,.context-calendar button{font:inherit;color:var(--plotline-ink);background:var(--plotline-panel);border:1px solid var(--plotline-line);border-radius:.3rem;min-width:0;} +.context-calendar-controls button{padding:.2rem .45rem;}.context-calendar [data-calendar-status]{font-size:.8rem;margin:.4rem 0;} +.context-calendar-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(14rem,.65fr);gap:.75rem;align-items:start;} +.context-calendar-month{min-width:0;}.context-calendar-month>strong{display:block;text-align:center;} +.context-calendar-grid,.context-calendar-weekdays{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:2px;} +.context-calendar-weekdays{text-align:center;font-size:.75rem;} +.context-calendar-grid{height:clamp(15rem,calc(100dvh - 23rem),25rem);grid-template-rows:repeat(var(--calendar-weeks,6),minmax(0,1fr));} +.context-calendar-day{display:flex;flex-direction:column;align-items:stretch;text-align:left;padding:.15rem .2rem;overflow:hidden;font-size:.8rem!important;line-height:1.2;cursor:pointer;} +.context-calendar-day-number{display:flex;justify-content:space-between;font-weight:600;}.context-calendar-day-number small{font-weight:400;} +.context-calendar-chapter{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:.7rem;} +.context-calendar-day.is-overflow{color:var(--plotline-muted);background:var(--plotline-surface);} +.context-calendar-day.is-manuscript{border-bottom:3px solid var(--plotline-accent);font-weight:700;} +.context-calendar-day[aria-pressed=true]{outline:2px solid var(--plotline-accent);outline-offset:-2px;background:var(--pd-selected,var(--plotline-surface));} +.context-calendar button:focus-visible,.context-calendar input:focus-visible,.context-calendar select:focus-visible{outline:3px solid var(--plotline-accent);outline-offset:1px;} +.context-calendar [data-calendar-details]{max-height:26rem;overflow:auto;overflow-wrap:anywhere;}.context-calendar h3{font-size:1rem;}.context-calendar details{margin:.4rem 0;}.context-calendar details details{margin-left:.6rem;}.context-calendar details a{display:block;margin:.3rem .6rem;} +.context-calendar-elapsed{display:flex;flex-wrap:wrap;gap:.5rem;font-size:.8rem;margin-top:.6rem;} +@container(max-width:760px){.context-calendar-layout{grid-template-columns:minmax(0,1fr);}.context-calendar [data-calendar-details]{max-height:16rem;}} diff --git a/PlotLine/wwwroot/js/context-calendar-model.js b/PlotLine/wwwroot/js/context-calendar-model.js new file mode 100644 index 00000000..9b5836e7 --- /dev/null +++ b/PlotLine/wwwroot/js/context-calendar-model.js @@ -0,0 +1,12 @@ +/* Date-only UTC arithmetic avoids DST and the JavaScript 0–99 year constructor trap. */ +(function (host) { + 'use strict'; + const date=value=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(value||'')||value.startsWith('0000'))return null;const d=new Date(value+'T00:00:00Z');return Number.isFinite(+d)&&d.toISOString().slice(0,10)===value?d:null;}; + const iso=d=>d.toISOString().slice(0,10); + function shift(month,step){const d=date(month+'-01');if(!d)return null;d.setUTCMonth(d.getUTCMonth()+step);return d.getUTCFullYear()>=1&&d.getUTCFullYear()<=9999?iso(d).slice(0,7):null;} + function grid(month){const first=date(month+'-01');if(!first)return [];const d=new Date(+first);d.setUTCDate(1-(first.getUTCDay()+6)%7);const next=new Date(+first);next.setUTCMonth(next.getUTCMonth()+1);next.setUTCDate(0);const count=Math.ceil(((first.getUTCDay()+6)%7+next.getUTCDate())/7)*7;return Array.from({length:count},()=>{const value=d.getUTCFullYear()>=1&&d.getUTCFullYear()<=9999?iso(d):null;d.setUTCDate(d.getUTCDate()+1);return value;});} + function chapters(scenes,day){if(!day)return [];const result=new Map();for(const s of scenes){if(s.date!==day)continue;const key=s.bookID+'/'+s.chapterID;if(!result.has(key))result.set(key,{...s,scenes:[]});result.get(key).scenes.push(s);}return [...result.values()];} + function manuscript(scenes,position){const current=scenes.find(s=>s.bookID===position.bookId&&s.sceneID===position.sceneId);if(current?.date)return {date:current.date,source:'scene'};const chapter=position.chapterId??current?.chapterID;const dated=scenes.filter(s=>s.bookID===position.bookId&&s.chapterID===chapter&&s.date).sort((a,b)=>a.sceneNumber-b.sceneNumber);return {date:dated[0]?.date||null,source:dated.length?'chapter (first dated scene)':'undated'};} + const api={date,iso,shift,grid,chapters,manuscript,elapsed:(from,to)=>date(from)&&date(to)?Math.round((date(to)-date(from))/86400000):null}; + if(typeof module!=='undefined'&&module.exports)module.exports=api;else host.PlotDirectorCalendar=api; +})(globalThis); diff --git a/PlotLine/wwwroot/js/context-calendar.js b/PlotLine/wwwroot/js/context-calendar.js new file mode 100644 index 00000000..3ad258e8 --- /dev/null +++ b/PlotLine/wwwroot/js/context-calendar.js @@ -0,0 +1,53 @@ +(() => { + 'use strict'; + const model=window.PlotDirectorCalendar,instances=new WeakMap(),states=new WeakMap(),cache=new Map(); + const element=(tag,text)=>{const n=document.createElement(tag);if(text!=null)n.textContent=text;return n;}; + function load(book,refresh){if(refresh)cache.delete(book);if(!cache.has(book)){if(cache.size>32)cache.delete(cache.keys().next().value);const promise=fetch(`/Writing/Context/Calendar/State?bookId=${book}`,{cache:'no-store',signal:AbortSignal.timeout(20000)}).then(async r=>{if(!r.ok||r.redirected)throw Error('Calendar unavailable. Check access and refresh saved data.');return r.json();}).catch(e=>{if(cache.get(book)===promise)cache.delete(book);throw e;});cache.set(book,promise);}return cache.get(book);} + function mount(node,context){ + if(instances.has(node))return; + const q=s=>node.querySelector(s),pane=node.closest('[data-context-pane]'); + let state=states.get(pane);if(!state){state={month:new Date().toISOString().slice(0,7),selected:null,hold:false,books:'current',from:'',expanded:new Set()};states.set(pane,state);} + let position=context.position,data,epoch=0,disposed=false; + const status=q('[data-calendar-status]'),grid=q('[data-calendar-grid]'),details=q('[data-calendar-details]'); + const label=day=>model.date(day)?.toLocaleDateString('en-GB',{timeZone:'UTC',weekday:'long',day:'numeric',month:'long',year:'numeric'}); + function elapsed(){const n=model.elapsed(state.from,state.selected);q('[data-calendar-elapsed]').textContent=n==null?'':`${n} days to selected date`;} + function drawDetails(){ + details.replaceChildren(element('h3',state.selected?label(state.selected):'Select a date')); + const scenes=data.scenes.filter(s=>state.books==='all'||s.bookID===position.bookId),groups=model.chapters(scenes,state.selected); + if(!groups.length)details.append(element('p','No dated chapters or scenes on this date.')); + for(const group of groups){const key=state.selected+'/'+group.bookID+'/'+group.chapterID,section=element('details');section.open=state.expanded.has(key);section.addEventListener('toggle',()=>{if(section.open)state.expanded.add(key);else state.expanded.delete(key);}); + section.append(element('summary',`${state.books==='all'?group.bookLabel+' · ':''}Ch ${group.chapterNumber} · ${group.chapterTitle} (${group.scenes.length} scenes)`)); + for(const scene of group.scenes){const sceneKey=key+'/'+scene.sceneID,row=element('details');row.open=state.expanded.has(sceneKey);row.addEventListener('toggle',()=>{if(row.open)state.expanded.add(sceneKey);else state.expanded.delete(sceneKey);});row.append(element('summary',`Scene ${scene.sceneNumber} · ${scene.title}`));const link=element('a','Open scene in main window');link.href=`/Scenes/Edit/${scene.sceneID}?retainNarrativeFocus=true`;link.dataset.contextNarrative='author';link.target='_blank';link.rel='noopener';row.append(link);section.append(row);} + details.append(section); + } + elapsed(); + } + function draw(){if(!data)return; + const current=model.manuscript(data.scenes,position); + if(!state.hold&¤t.date){state.month=current.date.slice(0,7);state.selected=current.date;} + q('[data-calendar-month]').value=state.month;q('[data-calendar-books]').value=state.books; + q('[data-calendar-hold]').setAttribute('aria-pressed',String(state.hold)); + status.textContent=`${state.hold?'Browsing / Hold':'Following scene'} · Manuscript: ${current.date?label(current.date)+' · '+current.source:'undated; month retained'}`; + q('[data-calendar-title]').textContent=model.date(state.month+'-01').toLocaleDateString('en-GB',{month:'long',year:'numeric',timeZone:'UTC'}); + q('[data-calendar-previous]').disabled=!model.shift(state.month,-1);q('[data-calendar-next]').disabled=!model.shift(state.month,1); + grid.replaceChildren();const days=model.grid(state.month);grid.style.setProperty('--calendar-weeks',days.length/7); + const scenes=data.scenes.filter(s=>state.books==='all'||s.bookID===position.bookId); + for(const day of days){if(!day){grid.append(element('span'));continue;}const groups=model.chapters(scenes,day),button=element('button');button.type='button';button.dataset.calendarDate=day;button.className='context-calendar-day'; + button.classList.toggle('is-overflow',day.slice(0,7)!==state.month);button.classList.toggle('is-manuscript',day===current.date);button.setAttribute('aria-pressed',String(day===state.selected));if(day===current.date)button.setAttribute('aria-current','date'); + button.setAttribute('aria-label',`${label(day)}${day===current.date?', manuscript date':''}, ${groups.length} chapters${groups.length?', '+groups.map(g=>g.bookLabel+' chapter '+g.chapterNumber).join(', '):''}`); + const head=element('span',`${Number(day.slice(-2))}${day===current.date?' ●':''}`);head.className='context-calendar-day-number';if(groups.length>1)head.append(element('small',` +${groups.length-1}`));button.append(head); + if(groups.length){const text=`${state.books==='all'?groups[0].bookLabel+' · ':''}Ch ${groups[0].chapterNumber}`,chip=element('span',text);chip.title=text;chip.className='context-calendar-chapter';button.append(chip);} + button.onclick=()=>{state.hold=true;state.selected=day;state.month=day.slice(0,7);draw();node.querySelector(`[data-calendar-date="${day}"]`)?.focus({preventScroll:true});};grid.append(button); + } + drawDetails(); + } + async function reload(refresh=false){const ticket=++epoch;try{const result=await load(position.bookId,refresh);if(disposed||ticket!==epoch)return;data=result;draw();}catch(e){if(!disposed&&ticket===epoch)status.textContent=e.message;}} + q('[data-calendar-books]').onchange=e=>{state.books=e.target.value;draw();}; + q('[data-calendar-month]').onchange=e=>{if(model.date(e.target.value+'-01')){state.hold=true;state.month=e.target.value;draw();}}; + for(const [selector,step]of [['[data-calendar-previous]',-1],['[data-calendar-next]',1]])q(selector).onclick=()=>{const month=model.shift(state.month,step);if(month){state.hold=true;state.month=month;draw();}}; + q('[data-calendar-hold]').onclick=()=>{state.hold=true;draw();};q('[data-calendar-return]').onclick=()=>{state.hold=false;draw();}; + q('[data-calendar-from]').value=state.from;q('[data-calendar-from]').onchange=e=>{state.from=e.target.value;elapsed();}; + instances.set(node,{position(next){position=next;draw();},refresh(){void reload(true);},dispose(){disposed=true;epoch++;}});void reload(); + } + window.PlotDirectorContextLifecycles={...(window.PlotDirectorContextLifecycles||{}),calendar:{mount,dispose(node){instances.get(node)?.dispose();instances.delete(node);},onPosition(node,next){const instance=instances.get(node);if(!instance)return false;instance.position(next);return true;},onCacheInvalidation(){cache.clear();},onInvalidation(node){const instance=instances.get(node);if(!instance)return false;instance.refresh();return true;}}}; +})(); diff --git a/PlotLine/wwwroot/js/context-workspace.js b/PlotLine/wwwroot/js/context-workspace.js index 345a659d..78ee05a7 100644 --- a/PlotLine/wwwroot/js/context-workspace.js +++ b/PlotLine/wwwroot/js/context-workspace.js @@ -92,7 +92,7 @@ if(guarded(record)){pane.status.textContent='Updates available · this panel is still editing or busy at its previous position.';return;} if(!record.stale&&record.node){mount(pane,record);pane.status.textContent='';return;} const level=scopes.indexOf(tab.scope); - if(level>=3&&!position.sceneId){ + if(level>=3&&!position.sceneId&&tab.id!=='calendar'){ dispose(pane.host.contextRecord);pane.host.contextRecord=null;pane.host.replaceChildren(); pane.host.removeAttribute('aria-busy');pane.status.textContent='No verified current scene. Choose a saved scene to browse.';return; } @@ -134,9 +134,10 @@ }; function inScope(hint) { return !(hint.projectId&&scope.projectId&&Number(hint.projectId)!==scope.projectId) && - !(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId); + !(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['dates','structure'].includes(hint.kind)); } function affects(tab,hint) { + if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&tab.id!=='calendar')return false; return tab.contentRefresh!=='none' && (!affectedPanels[hint.kind] || affectedPanels[hint.kind].includes(tab.id)); } function invalidate(hint={}) { @@ -149,7 +150,7 @@ function flushInvalidations() { invalidationTimer=null; const hints=pendingHints.splice(0); - if(hints.some(h=>h.kind==='structure'))void refreshStructure(); + if(hints.some(h=>h.kind==='structure'&&(!h.bookId||Number(h.bookId)===scope.bookId)))void refreshStructure(); const affected=new Set([...registry.values()].filter(tab=>hints.some(h=>affects(tab,h))).map(tab=>tab.id)); for(const id of affected)tabVersions.set(id,(tabVersions.get(id)||0)+1); for(const [key,item] of requests)if(affected.has(item.tabId)){item.controller.abort();requests.delete(key);}