Complete Word and Writer toast notification migration
This commit is contained in:
parent
23f3f442d7
commit
65b4910e94
@ -40,3 +40,28 @@ Other feature-specific/admin banners and scripts remain future cleanup opportuni
|
||||
Run `node PlotLine.Tests/Browser/shared-notifications.cjs` from the repository root. It uses production assets in isolated Chromium documents with no application/database writes, testing all categories, plain-text rendering, focus preservation, bounded display, dismissal, duplicate suppression, partial markers and repeated script loading, and native Word interruption/recovery events. Both ordinary and simulated standalone presentation are covered; physical installed-PWA and Word acceptance are separate from this check.
|
||||
|
||||
Implementation validation (2026-11-21): solution build and the full executable regression harness passed; focused browser checks passed. Word transport, debounce, capture, paragraph identity, navigation, and native Windows components were not changed.
|
||||
|
||||
## Completed Word/Writer cleanup (2026-11-21)
|
||||
|
||||
All three web shells (application, embedded writing window, Office Companion) now load the same toast service and Word presentation adapter. `word-notifications.js` consumes existing native/Office presence and Writer status events; it does not fetch, poll, schedule, capture or analyse anything. `requested(lease, requestId)` records only a notification correlation. A manual paragraph success requires the matching request and newer verified positions; a chapter success requires the matching accepted chapter transfer. Unrelated receipts cannot claim success.
|
||||
|
||||
| Previous presentation/message | Result |
|
||||
| --- | --- |
|
||||
| Writer command paragraph, echoed into the ribbon | Command diagnostics moved inside Connection and update options. Ribbon now shows concise persistent manuscript state, with full freshness explanation in its title. |
|
||||
| Live announcements from Writer connection/command/ribbon, native sync feedback, Reader update status | Removed competing routine live regions. Shared toast status/alert regions announce meaningful outcomes. Persistent text remains readable. |
|
||||
| Changes detected / Checking changes / Synchronising chapter / Up to date | Never toast or open a web alert. Incoming chapter progress is confined to persistent state/details. These exact four literals were not hard-coded web transient messages in the checked revision. Native ribbon/tray labels such as Changes found, Checking, Synchronising and Up to date remain persistent and unchanged. |
|
||||
| Office document-message area (reading/resolving/scanning/current-scene updates and diagnostics) | Moved into Manuscript details; routine updates no longer occupy the main notification area. Existing sync indicator remains visible. |
|
||||
| Native paragraph transfer failed/cancelled, chapter Needs review | One shared error/warning per failure state until accepted recovery; a warning can escalate to an error. Persistent freshness/details remain. |
|
||||
| Manual Writer check request failure / accepted check | Error toast on request failure; success toast only for matching accepted completion. Request acknowledgement/checking is silent. |
|
||||
| Native connection dialog sync/repair request errors, timeout, accepted result | Request errors/timeout toast; matching accepted manual completion uses the central adapter. Existing progress and recovery instructions remain beside the controls. |
|
||||
| Word connection lost/restored (native and Office) | Consolidated transition notifications; no initial-offline toast, no repeated reconnect warning. Embedded shell now supports these too. |
|
||||
| Office Sync failed / Synced / Syncing... / waiting for typing | Failure toast once plus visible failed status. Automatic completion clears failure silently. Explicit manual success toasts; in-progress/waiting text stays in the indicator. |
|
||||
| Word confirmed navigation (including paragraph start), failed/expired/mismatched/timed-out navigation | Shared success/error toast for the existing manual outcome; detailed command record stays inside options. Receipt processing, wait/confirmation timing and cancellation are unchanged. |
|
||||
| Manuscript linked / structure imported / Characters created / marker save confirmed or already present | Shared success toast replaces document-message completion. Binding labels, first-run step results/counts and save-required instructions remain where needed. |
|
||||
| Scene links saved successfully / manual chapter-scene linking or ID attachment / manuscript unlinked-cleaned | Shared success toast; redundant link-status completion text removed. |
|
||||
| Manual scene-link save, chapter/scene create-link/ID attachment, first-run link/import/character creation, marker update, diagnostics scan and unlink/cleanup failures | Shared error toast; actionable error details and existing recovery/confirmation workflows retained. |
|
||||
| Reader Chapter updated / automatic checking and pending accepted updates | Background completion stays silent in persistent status. Explicit Apply update success toasts. Update-read failure toasts once until recovery; persistent retry/sign-in text remains. |
|
||||
|
||||
Retained deliberately: Word unsaved/unverified/mapping/selection/capability warnings; persistent connection/freshness/progress; first-run scan/preview/build and marker-save review instructions; detailed cleanup recovery; destructive unlink/cleanup confirmations; Context/Intent follow status and substantial unavailable-content explanations; native import conflict/review/result summaries and validation. `native-companion-review.js` only selects the submitted session; it has no competing notification mechanism. The native workspace connection label remains persistent and feeds the shared connection presentation. No Windows agent, VSTO ribbon, native modal maintenance/troubleshooting dialog, transport, debounce, capture, paragraph identity, navigation processing or analysis was changed.
|
||||
|
||||
Focused checks: `shared-notifications.cjs`, `word-toast-outcomes.cjs`, `word-toast-paths.cjs` (actual Razor Writer/manual check/navigation/native-dialog form paths), `writer-word-notifications.cjs` (existing correlated navigation timing/race regression), `reader-word-freshness.cjs`, and `word-companion-regressions.cjs`. The existing navigation test opens the newly collapsed command diagnostics before checking them; its timing/correlation assertions are retained. Office adapter tests execute the production presentation setter without starting Office. Browser and simulated standalone checks do not physically verify Word, native Windows UI, or a genuinely installed PWA.
|
||||
|
||||
44
PlotLine.Tests/Browser/word-toast-outcomes.cjs
Normal file
44
PlotLine.Tests/Browser/word-toast-outcomes.cjs
Normal file
@ -0,0 +1,44 @@
|
||||
// Production notification event paths. No transport, Word or database work.
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path');
|
||||
const fs=require('node:fs');
|
||||
const assets=path.resolve(__dirname,'../../PlotLine/wwwroot');
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
for(const standalone of [false,true]){
|
||||
const page=await browser.newPage();await page.setContent('<div data-toast-host></div><input id="work">');
|
||||
await page.evaluate(v=>Object.defineProperty(navigator,'standalone',{value:v}),standalone);
|
||||
for(const script of ['notifications','word-notifications','word-notifications'])await page.addScriptTag({path:assets+'/js/'+script+'.js'});
|
||||
await page.locator('#work').focus();
|
||||
const lease={instanceId:'synthetic-instance',sessionId:'synthetic-session',wordAvailable:true,snapshotRevision:2,mappingCurrent:true};
|
||||
const pulse=async value=>page.evaluate(leases=>dispatchEvent(new CustomEvent('writer-word-state',{detail:{leases}})),value);
|
||||
for(const state of ['Changes detected','Checking changes','Synchronising chapter','Up to date','Synchronised']){for(let i=0;i<4;i++)await pulse([{...lease,chapterProgress:{state,message:state}}]);}
|
||||
assert.equal(await page.locator('.pd-toast').count(),0,'routine progress/completion is silent');
|
||||
await pulse([{...lease,paragraphTransfer:{requestId:'failed-1',state:'failed',message:'Synthetic transfer failed'}}]);
|
||||
await pulse([{...lease,paragraphTransfer:{requestId:'failed-1',state:'failed',message:'Synthetic transfer failed'}}]);
|
||||
assert.equal(await page.locator('.pd-toast--error').count(),1);
|
||||
await pulse([{...lease,paragraphTransfer:{state:'accepted'}}]);assert.equal(await page.locator('.pd-toast').count(),0,'background recovery removes persistent error without success toast');
|
||||
await page.evaluate(lease=>PlotDirector.wordNotifications.requested(lease,'manual-1'),lease);
|
||||
await pulse([{...lease,paragraphTransfer:{requestId:'other',state:'accepted',kind:'chapter'}}]);assert.equal(await page.locator('.pd-toast').count(),0,'unrelated request cannot claim manual success');
|
||||
await pulse([{...lease,paragraphTransfer:{requestId:'manual-1',state:'accepted',kind:'paragraph'}}]);assert.equal(await page.locator('.pd-toast').count(),0,'accepted transfer without newer verified positions is not completion');
|
||||
await pulse([{...lease,snapshotRevision:3,paragraphTransfer:{requestId:'manual-1',state:'accepted',kind:'paragraph'}}]);
|
||||
await pulse([{...lease,snapshotRevision:3,paragraphTransfer:{requestId:'manual-1',state:'accepted',kind:'paragraph'}}]);
|
||||
assert.equal(await page.locator('.pd-toast--success').count(),1,'exact manual accepted result reports once');
|
||||
await pulse([{...lease,chapterProgress:{state:'Needs review',message:'Synthetic review required'}}]);
|
||||
await pulse([{...lease,chapterProgress:{state:'Needs review',message:'Synthetic review required'}}]);assert.equal(await page.locator('.pd-toast--warning').count(),1);
|
||||
await pulse([{...lease,paragraphTransfer:{state:'failed',message:'Synthetic escalated failure'}}]);assert.equal(await page.locator('.pd-toast--warning').count(),0);assert.equal(await page.locator('.pd-toast--error').count(),1);
|
||||
await page.evaluate(()=>{PlotDirector.wordNotifications.syncState('office','accepted','Manual Office sync complete',true);PlotDirector.wordNotifications.connection('office',true);PlotDirector.wordNotifications.connection('office',false);PlotDirector.wordNotifications.connection('office',false);});
|
||||
assert.equal(await page.locator('.pd-toast--warning').count(),1,'Office loss is deduplicated');
|
||||
await page.evaluate(()=>PlotDirector.wordNotifications.connection('office',true));assert.equal(await page.locator('.pd-toast--warning').count(),0);
|
||||
assert(await page.locator('#work').evaluate(n=>n===document.activeElement));
|
||||
// Execute the actual Office presentation adapter without starting Office/capture/transport.
|
||||
const office=fs.readFileSync(assets+'/js/word-companion-host.js','utf8');
|
||||
const adapter=office.slice(office.indexOf(' const setSyncStatus ='),office.indexOf(' const setStructurePreviewStatus'));
|
||||
await page.addScriptTag({content:`{const syncStatus=document.createElement('p');document.body.append(syncStatus);const setText=(node,text)=>node.textContent=text;${adapter}window.officeSyncStatus=setSyncStatus;window.officeIndicator=syncStatus;}`});
|
||||
await page.evaluate(()=>document.querySelectorAll('.pd-toast button').forEach(b=>b.click()));
|
||||
await page.evaluate(()=>{officeSyncStatus('Syncing...','automatic');officeSyncStatus('Synced','automatic');});assert.equal(await page.locator('.pd-toast').count(),0);
|
||||
await page.evaluate(()=>{officeSyncStatus('Sync failed','automatic');officeSyncStatus('Sync failed','automatic');});assert.equal(await page.locator('.pd-toast--error').count(),1);
|
||||
assert.equal(await page.evaluate(()=>officeIndicator.textContent),'Sync failed','persistent Office failure remains');
|
||||
await page.evaluate(()=>officeSyncStatus('Synced','automatic'));assert.equal(await page.locator('.pd-toast').count(),0);
|
||||
await page.evaluate(()=>officeSyncStatus('Synced','manual'));assert.equal(await page.locator('.pd-toast--success').count(),1);
|
||||
console.log('PASS Word toast events: silent progress/background completion, failed transfer dedup/escalation, exact manual acceptance, Office outcomes, singleton and focus; standalone='+standalone);await page.close();
|
||||
}
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
42
PlotLine.Tests/Browser/word-toast-paths.cjs
Normal file
42
PlotLine.Tests/Browser/word-toast-paths.cjs
Normal file
@ -0,0 +1,42 @@
|
||||
// Real Razor Writer and production scripts; isolated loopback fixture, no database/Word.
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
const base=process.env.PD_BROWSER_FIXTURE_URL||'http://127.0.0.1:5238';
|
||||
const hub=`window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return{state:'Connected',on:()=>{},onreconnected:()=>{},onreconnecting:()=>{},onclose:()=>{},start:async()=>{},stop:async()=>{},invoke:async()=>({windows:[],isConnected:false})}}}};`;
|
||||
(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){
|
||||
const context=await browser.newContext();if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:hub}));
|
||||
const lease={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',bookId:12,wordAvailable:true,wordSaved:true,canAcknowledgeNavigation:true,canChapterSync:true,canParagraphSync:true,revision:2,snapshotRevision:2,mappingCurrent:true,documentTitle:'Synthetic toast manuscript',expires:new Date(Date.now()+3600000).toISOString()};
|
||||
let packet={leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[]},fail=false,posts=0,requestId='44444444-4444-4444-4444-444444444444';
|
||||
await context.route('**/native-companion/status*',r=>r.fulfill({json:packet}));
|
||||
await context.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null}}));
|
||||
await context.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:true,scene:true,paragraph:true}}));
|
||||
await context.route('**/manuscript/paragraphs/snapshot',r=>{posts++;return r.fulfill({status:fail?409:200,json:fail?{message:'Synthetic request failed'}:{requestId,message:'Synthetic request queued'}})});
|
||||
await context.route('**/WriterWord/Navigate',r=>r.fulfill({status:202,json:{navigationId:new URLSearchParams(r.request().postData()).get('navigationId')}}));
|
||||
await context.route('**/WriterWord/Navigation?*',r=>r.fulfill({json:{...Object.fromEntries(new URL(r.request().url()).searchParams),state:'completed'}}));
|
||||
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.goto(base+'/Writer/Write?projectId=7&bookId=12&objective=true');
|
||||
await page.waitForFunction(()=>window.PlotDirector?.wordNotifications&&document.querySelector('[data-word-sync]')?.disabled===false);
|
||||
await page.locator('[data-word-sync]').evaluate(n=>n.closest('details').open=true);
|
||||
await page.locator('[data-word-check]').click();assert.equal(await page.locator('.pd-toast').count(),0,'check/progress is silent');
|
||||
const response=page.waitForResponse(r=>r.url().endsWith('/manuscript/paragraphs/snapshot'));await page.locator('[data-word-sync]').click();await response;
|
||||
await page.waitForFunction(()=>document.querySelector('[data-word-command]').textContent.includes('requested'));
|
||||
assert.equal(posts,1);assert.equal(await page.locator('.pd-toast').count(),0,'request acknowledgement is not success');
|
||||
packet={...packet,leases:[{...lease,paragraphTransfer:{requestId,state:'accepted',kind:'chapter'}}]};
|
||||
await page.evaluate(v=>dispatchEvent(new CustomEvent('writer-word-state',{detail:v})),packet);
|
||||
await page.locator('.pd-toast--success').filter({hasText:'Saved manuscript check completed.'}).waitFor();
|
||||
fail=true;await page.locator('[data-word-sync]').click();await page.locator('.pd-toast--error').filter({hasText:'Synthetic request failed'}).waitFor();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-word-navigate]').disabled===false);
|
||||
await page.locator('[data-word-navigate]').evaluate(n=>n.click());
|
||||
await page.locator('.pd-toast--success').filter({hasText:'Word confirmed navigation.'}).waitFor();
|
||||
// Exercise the separate native connection dialog's trusted form submission too.
|
||||
fail=false;requestId='55555555-5555-5555-5555-555555555555';
|
||||
await context.route('**/manuscript/paragraphs/snapshot',r=>{posts++;packet={...packet,leases:[{...lease,paragraphTransfer:{requestId,state:'accepted',kind:'chapter',message:'Synthetic native check accepted'}}]};return r.fulfill({json:{requestId,message:'Synthetic native check requested'}})});
|
||||
await page.locator('#native-companion-status').evaluate(n=>n.click()); // fixture deliberately hides the connection launcher
|
||||
await page.waitForFunction(()=>document.querySelector('[data-word-sync-button]').disabled===false);
|
||||
await page.locator('[data-word-sync-button]').click();
|
||||
await page.locator('[data-word-sync-feedback]').filter({hasText:'Synthetic native check accepted'}).waitFor();
|
||||
assert(posts>=3,'native dialog submits its existing form');
|
||||
await page.locator('[data-close-word-details]').click();
|
||||
assert.equal(await page.locator('[data-word-command][aria-live],[data-word-state][role=status],[data-word-ribbon-status][role=status]').count(),0,'no competing routine live regions');
|
||||
assert.deepEqual(errors,[]);console.log('PASS actual Writer notification paths: silent check/request, exact accepted manual success, request failure, correlated navigation result, trusted native dialog sync; standalone='+pwa);await context.close();
|
||||
}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1});
|
||||
@ -12,7 +12,7 @@ const stub=`window.__hubHandlers={};window.signalR={HubConnectionState:{Connecte
|
||||
await c.route('**/WriterWord/Navigate',async r=>{posts++;const body=Object.fromEntries(new URLSearchParams(r.request().postData()));if(beforeAccept){state='completed';await pulse();}return r.fulfill({status:202,json:{navigationId:body.navigationId}})});
|
||||
await c.route('**/WriterWord/Navigation?*',async r=>{reads++;active++;peak=Math.max(peak,active);const result={...Object.fromEntries(new URL(r.request().url()).searchParams),state};if(wrong)result[wrong]='99999999-9999-9999-9999-999999999999';if(hold){hold=false;await new Promise(resolve=>release=resolve);}await r.fulfill({json:result});active--;});
|
||||
p=await c.newPage();const errors=[],diagnostics=[];p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.text().includes('notification-to-receipt'))diagnostics.push(m.text())});
|
||||
await p.goto(base+'/Writer/Write?projectId=7&bookId=12&objective=true');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await p.evaluate(()=>PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:31}));const button=p.locator('[data-ribbon-word=chapter]'),message=p.locator('[data-word-command]');await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);await p.locator('[data-work-note]').evaluate(n=>n.value='Retained synthetic note');
|
||||
await p.goto(base+'/Writer/Write?projectId=7&bookId=12&objective=true');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await p.evaluate(()=>PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:31}));const button=p.locator('[data-ribbon-word=chapter]'),message=p.locator('[data-word-command]');await message.evaluate(n=>{for(let p=n.parentElement;p;p=p.parentElement)if(p.tagName==='DETAILS')p.open=true;});await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);await p.locator('[data-work-note]').evaluate(n=>n.value='Retained synthetic note');
|
||||
const collapse=p.locator('[data-ribbon-collapse]');if(await collapse.count()&&await collapse.getAttribute('aria-expanded')==='false')await collapse.click();const start=Date.now(),firstReceipt=p.waitForResponse(r=>r.url().includes('/WriterWord/Navigation?'));await button.click();await firstReceipt;assert(Date.now()-start<850,'first receipt is immediate, not delayed by the one-second timer');assert.equal(await p.evaluate(()=>__receiptListeners.size),1);assert(!(await message.textContent()).includes('confirmed navigation'));
|
||||
await pulse();await p.waitForTimeout(80);assert(!(await message.textContent()).includes('confirmed navigation'),'a hint without native completion cannot report success');state='completed';const wake=Date.now();await pulse();await message.filter({hasText:'Word confirmed navigation.'}).waitFor();assert(Date.now()-wake<850,'existing SignalR handler wakes exact receipt before fallback timer');assert.equal(await p.evaluate(()=>__receiptListeners.size),0);assert(diagnostics.length>0);
|
||||
state='requested';hold=true;const before=reads;await button.click();await p.waitForFunction(()=>__receiptListeners.size===1);while(!release)await p.waitForTimeout(10);await p.evaluate(()=>{for(let i=0;i<500;i++)__hubHandlers['/hubs/native-companion'].NativePresenceChanged({bookId:12})});state='completed';release();release=null;await message.filter({hasText:'Word confirmed navigation.'}).waitFor();assert.equal(peak,1,'receipt requests remain single-flight');assert(reads-before<=3,'duplicate notifications are coalesced');assert.equal(await p.locator('[data-work-note]').inputValue(),'Retained synthetic note');
|
||||
|
||||
@ -47,7 +47,7 @@
|
||||
<p class="reader-status" role="status" id="reader-loading" hidden>Loading chapter…</p>
|
||||
<div class="reader-status reader-live-controls" hidden>
|
||||
<input type="checkbox" id="reader-pause" hidden /><button type="button" id="reader-pause-toggle" class="btn btn-outline-secondary btn-sm" aria-pressed="false" data-pwa-context="Synchronisation" title="Pause automatic manuscript updates">Pause updates</button>
|
||||
<span role="status" aria-live="polite" id="reader-update-status"></span>
|
||||
<span id="reader-update-status"></span>
|
||||
<button type="button" id="reader-apply-update" data-pwa-context="Synchronisation" data-pwa-keep-visible="true" title="Show the newly accepted chapter" class="btn btn-outline-secondary btn-sm" hidden>Show updated chapter</button>
|
||||
</div>
|
||||
<details class="reader-metadata" open="@(!Model.IntegratedReview)"><summary>Accepted manuscript details</summary><div class="reader-status muted" id="reader-timestamps">
|
||||
|
||||
@ -174,7 +174,7 @@
|
||||
var destination = "word";
|
||||
var tooltip = $"Open current {target.Item1} in Microsoft Word.";
|
||||
<button type="button" class="pd-ribbon-command" data-ribbon-word="@target.Item1" data-command-destination="@destination" data-navigation-title="@tooltip" disabled aria-label="@tooltip" title="@tooltip Select a verified target and connect its Word manuscript."><destination-icon primary-icon="@target.Item3" destination="@destination" /><span>@target.Item2</span></button>
|
||||
}</div><span data-word-ribbon-status role="status" class="writer3-caption"></span><span class="pd-ribbon-group-label">Open in Word</span></div>
|
||||
}</div><span data-word-ribbon-status class="writer3-caption"></span><span class="pd-ribbon-group-label">Open in Word</span></div>
|
||||
}
|
||||
@if (category.Key == selectedCategory)
|
||||
{
|
||||
|
||||
@ -4,5 +4,5 @@
|
||||
var userID=int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var author)?author:0;
|
||||
var appearance=userID>0?await AppearancePreferences.GetAsync(userID):new ApplicationAppearance();
|
||||
}
|
||||
<!DOCTYPE html><html lang="en" data-theme="light" data-bs-theme="light"><head><meta charset="utf-8" /><partial name="_ApplicationThemeBootstrap" model="appearance" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>@ViewData["Title"] · PlotDirector</title><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /><link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/plotline-theme.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/application-shell.css" asp-append-version="true" /></head>
|
||||
<body class="app-layout writing-embedded" data-pd-user-id="@User.FindFirstValue(ClaimTypes.NameIdentifier)"><div class="writing-window-bar"><a href="/Writer" target="_blank" rel="noopener">PlotDirector</a><button type="button" id="native-companion-status" class="pd-presence" aria-haspopup="dialog" aria-controls="writing-connection-details" data-word-companion-presence><span class="word-companion-presence-dot"></span><span id="native-companion-status-text">Checking Word…</span></button></div><partial name="_WritingConnectionDetails" />@RenderBody()<script src="https://cdn.jsdelivr.net/npm/@@microsoft/signalr@8.0.7/dist/browser/signalr.min.js"></script><script src="~/js/application-theme-sync.js" asp-append-version="true"></script><script src="~/js/story-position.js" asp-append-version="true"></script><script src="~/js/native-companion-status.js" asp-append-version="true" defer></script>@await RenderSectionAsync("Scripts",required:false)</body></html>
|
||||
<!DOCTYPE html><html lang="en" data-theme="light" data-bs-theme="light"><head><meta charset="utf-8" /><partial name="_ApplicationThemeBootstrap" model="appearance" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>@ViewData["Title"] · PlotDirector</title><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /><link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/plotline-theme.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/application-shell.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/notifications.css" asp-append-version="true" /></head>
|
||||
<body class="app-layout writing-embedded" data-pd-user-id="@User.FindFirstValue(ClaimTypes.NameIdentifier)"><div class="writing-window-bar"><a href="/Writer" target="_blank" rel="noopener">PlotDirector</a><button type="button" id="native-companion-status" class="pd-presence" aria-haspopup="dialog" aria-controls="writing-connection-details" data-word-companion-presence><span class="word-companion-presence-dot"></span><span id="native-companion-status-text">Checking Word…</span></button></div><partial name="_WritingConnectionDetails" />@RenderBody()<div class="pd-toast-host" data-toast-host aria-label="Notifications"></div><script src="~/js/notifications.js" asp-append-version="true"></script><script src="~/js/word-notifications.js" asp-append-version="true"></script><script src="https://cdn.jsdelivr.net/npm/@@microsoft/signalr@8.0.7/dist/browser/signalr.min.js"></script><script src="~/js/application-theme-sync.js" asp-append-version="true"></script><script src="~/js/story-position.js" asp-append-version="true"></script><script src="~/js/native-companion-status.js" asp-append-version="true" defer></script>@await RenderSectionAsync("Scripts",required:false)</body></html>
|
||||
|
||||
@ -12,7 +12,7 @@
|
||||
<input type="hidden" name="bookId" data-word-sync-book />
|
||||
<button type="submit" class="btn btn-primary" data-word-sync-button disabled>Synchronise from Word</button>
|
||||
<button type="submit" class="btn btn-outline-primary mt-2" data-word-repair-button formaction="/manuscript/paragraphs/repair" disabled>Repair Manuscript Synchronisation</button>
|
||||
<p class="small mt-2 mb-0" data-word-sync-feedback role="status">Select a connected, saved manuscript to refresh its paragraph positions. Word prose is never rewritten and AI analysis is not started.</p>
|
||||
<p class="small mt-2 mb-0" data-word-sync-feedback>Select a connected, saved manuscript to refresh its paragraph positions. Word prose is never rewritten and AI analysis is not started.</p>
|
||||
</form>
|
||||
<p data-word-connection-diagnostics class="small text-muted"></p>
|
||||
<nav class="d-flex flex-wrap gap-3 mb-3" data-word-book-links hidden><a data-word-book-link target="_blank" rel="noopener">Open book workspace</a><a data-word-structure-link target="_blank" rel="noopener">Manuscript structure and evidence</a></nav>
|
||||
|
||||
@ -157,7 +157,7 @@
|
||||
<button type="button" class="word-companion-primary-action" data-sync-scene-progress disabled>Sync Current Scene</button>
|
||||
<button type="button" data-refresh-current-scene>Refresh Current Scene</button>
|
||||
</div>
|
||||
<p class="word-companion-message" data-document-message></p>
|
||||
<details><summary>Manuscript details</summary><p class="word-companion-message" data-document-message></p></details>
|
||||
<p class="word-companion-message" data-sync-status>No resolved PlotDirector scene.</p>
|
||||
|
||||
<div class="word-companion-scene-card word-companion-scene-summary">
|
||||
@ -620,6 +620,7 @@
|
||||
}
|
||||
<div class="pd-toast-host" data-toast-host aria-label="Notifications"></div>
|
||||
<script src="~/js/notifications.js" asp-append-version="true"></script>
|
||||
<script src="~/js/word-notifications.js" asp-append-version="true"></script>
|
||||
<script src="~/js/word-companion-host.js" asp-append-version="true"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@ -2,15 +2,14 @@
|
||||
@{var focus=Model.NarrativeFocus;var reviewing=Model.WordNavigationContext=="review";var chapter=reviewing?Model.ReviewReader?.Chapter?.ChapterID:focus?.ChapterID;var scene=reviewing?(int?)null:focus?.SceneID;}
|
||||
<section class="writer3-word writer3-inset" data-writer-word data-word-context="@Model.WordNavigationContext" data-book-id="@Model.BookID" data-chapter-id="@chapter" data-scene-id="@scene" data-status-url="/native-companion/status?writerBookId=@Model.BookID&writerChapterId=@chapter" aria-label="Word Companion">
|
||||
<div class="writer3-authoring-heading"><h3>Your manuscript in Word</h3><help-icon key="writer3.word" /></div>
|
||||
<p data-word-state role="status">Checking Word Companion…</p>
|
||||
<p data-word-state>Checking Word Companion…</p>
|
||||
<label data-word-choose hidden>Choose the manuscript in Word<select class="form-select" data-word-document><option value="">Choose a document</option></select></label>
|
||||
<p class="writer3-caption" data-word-position>Word position has not been verified.</p>
|
||||
<p class="writer3-caption" data-word-freshness>Your latest changes have not yet been confirmed in PlotDirector.</p>
|
||||
<div class="button-row" data-word-legacy-navigation hidden>
|
||||
<button type="button" data-word-paragraph disabled>Paragraph in Word</button><button type="button" data-word-navigate disabled>Chapter in Word</button><button type="button" data-word-scene disabled>Scene in Word</button>
|
||||
</div>
|
||||
<details><summary>Connection and update options</summary><p class="writer3-caption">@(reviewing?"Review selection":"Working focus") and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.</p><div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-word-sync disabled>Check saved manuscript</button><button type="button" class="btn btn-sm btn-outline-secondary" data-word-check>Check connection & updates</button></div></details>
|
||||
<p data-word-command role="status" aria-live="polite"></p>
|
||||
<details><summary>Connection and update options</summary><p class="writer3-caption">@(reviewing?"Review selection":"Working focus") and Word position can differ. Navigation does not save Word or change your session. Reader shows accepted content.</p><div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-word-sync disabled>Check saved manuscript</button><button type="button" class="btn btn-sm btn-outline-secondary" data-word-check>Check connection & updates</button></div><p data-word-command class="writer3-caption"></p></details>
|
||||
<form method="post" asp-action="Set" asp-controller="NarrativeFocus" data-word-adopt hidden>
|
||||
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID"/><input type="hidden" name="SceneID"/><input type="hidden" name="projectId" value="@Model.ProjectID"/><input type="hidden" name="version" value="@focus?.Version"/>
|
||||
<p data-word-origin></p><button type="submit" class="btn btn-sm btn-outline-secondary">Use verified Word chapter as Current Focus</button>
|
||||
|
||||
@ -7,6 +7,12 @@ function initialiseManuscriptReader() {
|
||||
const focus = root.querySelector('#reader-focus');
|
||||
const content = root.querySelector('#reader-content');
|
||||
const message = root.querySelector('#reader-update-status');
|
||||
let dismissUpdateError, updateError = false;
|
||||
const notifyUpdateError = () => {
|
||||
if (!updateError) { updateError = true; dismissUpdateError = window.PlotDirector?.toast?.error(message.textContent); }
|
||||
};
|
||||
const clearUpdateError = () => { updateError = false; dismissUpdateError?.(); };
|
||||
|
||||
const apply = root.querySelector('#reader-apply-update');
|
||||
const pause = root.querySelector('#reader-pause');
|
||||
const loading = root.querySelector('#reader-loading');
|
||||
@ -202,6 +208,8 @@ function initialiseManuscriptReader() {
|
||||
root.dispatchEvent(new CustomEvent('reader:updated',{bubbles:true,detail:{revision,version:displayedVersion}}));
|
||||
apply.hidden = true;
|
||||
message.textContent = 'Chapter updated.';
|
||||
clearUpdateError();
|
||||
if (force) window.PlotDirector?.toast?.success('Chapter updated.');
|
||||
};
|
||||
const schedule = () => {
|
||||
clearTimeout(timer);
|
||||
@ -224,17 +232,18 @@ function initialiseManuscriptReader() {
|
||||
if (!pending()) {root.dataset.revision=revision;root.dispatchEvent(new CustomEvent('reader:metadata',{bubbles:true}));if(data.lastSuccessfulSyncUtc || data.snapshotCapturedUtc)timestamps(data);}
|
||||
indicate();
|
||||
await update();
|
||||
clearUpdateError();
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError' && !stopped) message.textContent = blocked
|
||||
if (error.name !== 'AbortError' && !stopped) { message.textContent = blocked
|
||||
? 'Updates stopped. Sign in again or reopen this chapter to check access.'
|
||||
: 'Updates temporarily unavailable. Your chapter is retained; retrying automatically.';
|
||||
: 'Updates temporarily unavailable. Your chapter is retained; retrying automatically.'; notifyUpdateError(); }
|
||||
} finally { finish(); }
|
||||
};
|
||||
const tryUpdate = async (force = false) => {
|
||||
if (busy || stopped || blocked || document.hidden) return;
|
||||
clearTimeout(timer); busy = true;
|
||||
try { await update(force); }
|
||||
catch (error) { if (error.name !== 'AbortError') message.textContent = 'Update could not be loaded. Retrying automatically.'; }
|
||||
catch (error) { if (error.name !== 'AbortError') { message.textContent = 'Update could not be loaded. Retrying automatically.'; notifyUpdateError(); } }
|
||||
finally { finish(); }
|
||||
};
|
||||
const stop = () => { stopped = true; clearTimeout(timer); request?.abort(); };
|
||||
|
||||
@ -14,7 +14,7 @@
|
||||
const body=new URLSearchParams(new FormData(syncForm));body.set('instanceId',selected.instanceId);body.set('sessionId',selected.sessionId);
|
||||
try{const response=await fetch((event.submitter?.hasAttribute('formaction')?event.submitter.formAction:syncForm.action),{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});
|
||||
if(response.redirected||!response.headers.get('content-type')?.includes('application/json'))throw Error('Sign in to PlotDirector again before requesting synchronisation.');
|
||||
const result=await response.json();if(!response.ok)throw Error(result.message||'Synchronisation could not be requested.');syncFeedback.textContent=result.message;if(syncPending)syncPending.requestId=result.requestId&&result.requestId!=='00000000-0000-0000-0000-000000000000'?result.requestId:null;if(!syncPending?.requestId){syncPending=null;syncButton.disabled=false;}void update();
|
||||
const result=await response.json();if(!response.ok)throw Error(result.message||'Synchronisation could not be requested.');syncFeedback.textContent=result.message;window.PlotDirector?.wordNotifications?.requested(selected,result.requestId);if(syncPending)syncPending.requestId=result.requestId&&result.requestId!=='00000000-0000-0000-0000-000000000000'?result.requestId:null;if(!syncPending?.requestId){syncPending=null;syncButton.disabled=false;}void update();
|
||||
}catch(error){syncPending=null;syncButton.disabled=false;syncFeedback.textContent=error.message||'Could not contact PlotDirector. Your saved manuscript is unchanged.';window.PlotDirector?.toast?.error(syncFeedback.textContent);}
|
||||
});
|
||||
root.addEventListener('click',()=>details?.showModal());
|
||||
@ -41,7 +41,7 @@
|
||||
else if(observed?.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.kind==='chapter'){syncFeedback.textContent=observed.paragraphTransfer.message;if(observed.paragraphTransfer.state==='needs-review'){syncPending=null;syncButton.disabled=false;}}
|
||||
else if(syncPending.requestId&&(!observed||observed.paragraphTransfer?.requestId!==syncPending.requestId||observed.paragraphTransfer.state==='failed')){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word transfer ended without an accepted snapshot. Saved paragraphs are unchanged. Check Companion Troubleshooting, then retry.';}
|
||||
else if(observed?.captureRequestId)syncFeedback.textContent='Reading Word: '+Math.max(0,Math.min(100,Number(observed.captureProgress)||0))+'%. Keep Word open until PlotDirector acknowledges the snapshot.';
|
||||
else if(Date.now()-syncPending.started>120000){syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';}
|
||||
else if(Date.now()-syncPending.started>120000){window.PlotDirector?.wordNotifications?.forget(syncPending.key);syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';window.PlotDirector?.toast?.error(syncFeedback.textContent);}
|
||||
}else if(selection?.chapterProgress){const progress=selection.chapterProgress;syncFeedback.textContent=progress.state+' · '+progress.matching+'/'+progress.total+' chapter mappings accepted. '+progress.message;}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.';
|
||||
else if(selection.wordSaved!==true)syncFeedback.textContent='Save the manuscript in Word before requesting synchronisation.';
|
||||
else if(selection.canParagraphSync!==true)syncFeedback.textContent='The connected add-in has not advertised paragraph synchronisation. Check the installed Companion and Word connection.';
|
||||
|
||||
@ -16,6 +16,7 @@
|
||||
if(sessions&&sessions.dataset.signature!==signature){sessions.dataset.signature=signature;sessions.replaceChildren(new Option('Active Word manuscript',''));for(const l of words)sessions.add(new Option(l.documentTitle,l.instanceId+'/'+l.sessionId));sessions.value=selected;}
|
||||
const candidates=selected?words.filter(l=>l.instanceId+'/'+l.sessionId===selected):active.length===1?active:words;
|
||||
const lease=candidates.length===1?candidates[0]:null;
|
||||
window.PlotDirector?.wordNotifications?.connection('native',words.length>0);
|
||||
status.textContent=lease?'Word connected · '+lease.documentTitle:words.length>1?'Choose a Word document':leases.length?'Companion connected · Word unavailable':'Companion disconnected or stale';
|
||||
scene.textContent=lease?.sceneId?[lease.chapterTitle,lease.sceneTitle].filter(Boolean).join(' · '):'No trustworthy current Word scene · saved workspaces remain available';
|
||||
}catch{status.textContent='Connection status unavailable · saved workspaces remain available';}finally{pending=false;}
|
||||
|
||||
@ -379,6 +379,7 @@
|
||||
};
|
||||
|
||||
const setConnectionStatus = (message) => {
|
||||
window.PlotDirector?.wordNotifications?.connection("office", message === "Connected");
|
||||
if (connectionStatus) {
|
||||
connectionStatus.textContent = message;
|
||||
}
|
||||
@ -612,18 +613,10 @@
|
||||
});
|
||||
};
|
||||
|
||||
let syncFailureNotified = false;
|
||||
let dismissSyncWarning;
|
||||
const setSyncStatus = (message) => {
|
||||
const setSyncStatus = (message, source = "automatic") => {
|
||||
setText(syncStatus, message);
|
||||
if (message === "Sync failed" && !syncFailureNotified) {
|
||||
syncFailureNotified = true;
|
||||
dismissSyncWarning = window.PlotDirector?.toast?.error("Word synchronisation failed. Check Companion diagnostics before retrying.");
|
||||
} else if (message === "Synced" && syncFailureNotified) {
|
||||
syncFailureNotified = false;
|
||||
dismissSyncWarning?.();
|
||||
window.PlotDirector?.toast?.info("Word synchronisation restored.");
|
||||
}
|
||||
if (message === "Sync failed") window.PlotDirector?.wordNotifications?.syncState('office-sync', 'failed', 'Word synchronisation failed. Check Companion diagnostics before retrying.');
|
||||
else if (message === "Synced") window.PlotDirector?.wordNotifications?.syncState('office-sync', 'accepted', 'Word synchronisation completed.', source === 'manual');
|
||||
};
|
||||
|
||||
const setStructurePreviewStatus = (message) => {
|
||||
@ -1915,7 +1908,7 @@
|
||||
}
|
||||
|
||||
clearOnboardingManualSavePrompt();
|
||||
setDocumentMessage("Scene markers added and save confirmed. Word may now be closed.");
|
||||
window.PlotDirector?.toast?.success("Scene markers added and save confirmed. Word may now be closed.");
|
||||
setDiagnostics({ lastError: "-" });
|
||||
};
|
||||
|
||||
@ -2796,7 +2789,7 @@
|
||||
"SaveNotRequired",
|
||||
"Scene markers already existed. No Word save was required.",
|
||||
diagnostics);
|
||||
setDocumentMessage("Scene markers already existed. Word may now be closed.");
|
||||
window.PlotDirector?.toast?.success("Scene markers already existed. Word may now be closed.");
|
||||
setDiagnostics({ lastError: "-" });
|
||||
return;
|
||||
}
|
||||
@ -2819,6 +2812,7 @@
|
||||
} catch (error) {
|
||||
console.error("Unable to update onboarding Word markers.", error);
|
||||
setDocumentMessage("Unable to update PlotDirector scene markers.");
|
||||
window.PlotDirector?.toast?.error("Unable to update PlotDirector scene markers.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
await invokeMarkerSyncFailure(buildId, errorText(error), {
|
||||
markersChanged: null,
|
||||
@ -3898,6 +3892,7 @@
|
||||
const message = errorText(error);
|
||||
setDiagnostics({ lastScan: "Failure", lastError: message });
|
||||
setDocumentMessage(`Unable to scan the Word document: ${message}`);
|
||||
window.PlotDirector?.toast?.error(`Unable to scan the Word document: ${message}`);
|
||||
} finally {
|
||||
if (runDiagnosticsButton) {
|
||||
runDiagnosticsButton.disabled = false;
|
||||
@ -4129,12 +4124,13 @@
|
||||
});
|
||||
setFirstRunMode(false);
|
||||
setConnectionStatus("Connected");
|
||||
setBookMessage(response.message || "Manuscript linked.");
|
||||
setDocumentMessage(response.message || "Manuscript linked.");
|
||||
setBookMessage("Manuscript linked.");
|
||||
window.PlotDirector?.toast?.success(response.message || "Manuscript linked.");
|
||||
await loadRuntimeDocumentAwareness();
|
||||
} catch (error) {
|
||||
console.error("Unable to link Word document.", error);
|
||||
setFirstRunStatus(`Unable to link manuscript: ${errorText(error)}`);
|
||||
window.PlotDirector?.toast?.error(`Unable to link manuscript: ${errorText(error)}`);
|
||||
} finally {
|
||||
isFirstRunImporting = false;
|
||||
updateFirstRunButtons();
|
||||
@ -4217,7 +4213,7 @@
|
||||
setHidden(firstRunImportActions, true);
|
||||
setHidden(firstRunCharacterActions, false);
|
||||
setFirstRunStatus(response.message || "Manuscript structure imported.");
|
||||
setDocumentMessage(response.message || "Manuscript structure imported.");
|
||||
window.PlotDirector?.toast?.success(response.message || "Manuscript structure imported.");
|
||||
window.setTimeout(updateFirstRunButtons, 750);
|
||||
} else {
|
||||
await finishFirstRunOnboarding(response.message || "Manuscript structure imported.");
|
||||
@ -4225,6 +4221,7 @@
|
||||
} catch (error) {
|
||||
console.error("Unable to import manuscript structure.", error);
|
||||
setFirstRunStatus(`Unable to import manuscript: ${errorText(error)}`);
|
||||
window.PlotDirector?.toast?.error(`Unable to import manuscript: ${errorText(error)}`);
|
||||
} finally {
|
||||
isFirstRunImporting = false;
|
||||
updateFirstRunButtons();
|
||||
@ -4268,12 +4265,13 @@
|
||||
projectId: project.projectId,
|
||||
candidateNames
|
||||
});
|
||||
setDocumentMessage(response.message || "Characters created.");
|
||||
window.PlotDirector?.toast?.success(response.message || "Characters created.");
|
||||
setText(firstRunCharacterStatus, `${response.createdCount || 0} created, ${response.skippedCount || 0} already existed.`);
|
||||
await finishFirstRunOnboarding(response.message || "Characters created.");
|
||||
} catch (error) {
|
||||
console.error("Unable to create discovered characters.", error);
|
||||
setText(firstRunCharacterStatus, `Unable to create characters: ${errorText(error)}`);
|
||||
window.PlotDirector?.toast?.error(`Unable to create characters: ${errorText(error)}`);
|
||||
} finally {
|
||||
isCreatingFirstRunCharacters = false;
|
||||
updateFirstRunButtons();
|
||||
@ -4429,7 +4427,7 @@
|
||||
}
|
||||
resetSelect(firstRunBookSelect, "Select a project first");
|
||||
resetFirstRunPreview(message || "Select a Project and Book to begin.");
|
||||
setDocumentMessage(message || "Manuscript unlinked.");
|
||||
window.PlotDirector?.toast?.success(message || "Manuscript unlinked.");
|
||||
setSyncStatus("No resolved PlotDirector scene.");
|
||||
setFirstRunMode(true);
|
||||
updateUnlinkWordDocumentButton();
|
||||
@ -4477,6 +4475,7 @@
|
||||
} catch (error) {
|
||||
console.error("Unable to unlink manuscript binding.", error);
|
||||
setDocumentMessage("Unable to unlink from PlotDirector.");
|
||||
window.PlotDirector?.toast?.error("Unable to unlink from PlotDirector.");
|
||||
const removeLocalOnly = window.confirm("PlotDirector could not be updated, but you can still remove the binding from this Word document.\n\nYou may need to unlink the Book manually in PlotDirector later.\n\nRemove binding from this Word document only?");
|
||||
if (removeLocalOnly) {
|
||||
try {
|
||||
@ -4486,9 +4485,11 @@
|
||||
} catch (metadataError) {
|
||||
console.error("Unable to remove Word document metadata.", metadataError);
|
||||
setDocumentMessage(`Unable to remove Word metadata: ${errorText(metadataError)}`);
|
||||
window.PlotDirector?.toast?.error(`Unable to remove Word metadata: ${errorText(metadataError)}`);
|
||||
}
|
||||
} else {
|
||||
setDocumentMessage(`Unable to unlink manuscript: ${errorText(error)}`);
|
||||
window.PlotDirector?.toast?.error(`Unable to unlink manuscript: ${errorText(error)}`);
|
||||
}
|
||||
} finally {
|
||||
if (unlinkWordDocumentButton) {
|
||||
@ -4513,6 +4514,7 @@
|
||||
await inspectPlotDirectorMarkers();
|
||||
} catch (error) {
|
||||
setDocumentMessage(`Unable to inspect markers: ${errorText(error)}`);
|
||||
window.PlotDirector?.toast?.error(`Unable to inspect markers: ${errorText(error)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -4539,11 +4541,13 @@
|
||||
} catch (verificationError) {
|
||||
console.error("Unable to verify PlotDirector marker cleanup.", verificationError);
|
||||
setDocumentMessage(`PlotDirector markers were removed, but cleanup verification failed: ${errorText(verificationError)}`);
|
||||
window.PlotDirector?.toast?.error(`PlotDirector markers were removed, but cleanup verification failed: ${errorText(verificationError)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (latestMarkerState.available && latestMarkerState.totalCount > 0) {
|
||||
setDocumentMessage(`Cleanup stopped: ${latestMarkerState.totalCount} PlotDirector marker${latestMarkerState.totalCount === 1 ? "" : "s"} remain.`);
|
||||
window.PlotDirector?.toast?.error(`Cleanup stopped: ${latestMarkerState.totalCount} PlotDirector marker${latestMarkerState.totalCount === 1 ? "" : "s"} remain.`);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -4553,6 +4557,7 @@
|
||||
} catch (metadataError) {
|
||||
console.error("Unable to remove Word document metadata after marker cleanup.", metadataError);
|
||||
setDocumentMessage(`PlotDirector markers were removed, but Word binding metadata remains: ${errorText(metadataError)}`);
|
||||
window.PlotDirector?.toast?.error(`PlotDirector markers were removed, but Word binding metadata remains: ${errorText(metadataError)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -4574,6 +4579,7 @@
|
||||
} catch (error) {
|
||||
console.error("Unable to clean PlotDirector markers.", error);
|
||||
setDocumentMessage(`Cleanup failed before unlinking: ${errorText(error)}`);
|
||||
window.PlotDirector?.toast?.error(`Cleanup failed before unlinking: ${errorText(error)}`);
|
||||
} finally {
|
||||
if (cleanUnlinkWordDocumentButton) {
|
||||
cleanUnlinkWordDocumentButton.disabled = false;
|
||||
@ -4691,10 +4697,12 @@
|
||||
primaryLocationId: selectedPrimaryLocationId()
|
||||
});
|
||||
updateCurrentSceneLinkState();
|
||||
setSceneLinksStatus("Scene links saved successfully.");
|
||||
window.PlotDirector?.toast?.success("Scene links saved successfully.");
|
||||
setSceneLinksStatus("");
|
||||
setDiagnostics({ lastError: "-" });
|
||||
} catch (error) {
|
||||
setSceneLinksStatus("Unable to save scene links.");
|
||||
window.PlotDirector?.toast?.error("Unable to save scene links.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
} finally {
|
||||
if (saveSceneLinksButton) {
|
||||
@ -4819,13 +4827,14 @@
|
||||
storedAnchorInvalid = false;
|
||||
currentResolutionAnchorType = "SceneID Anchor";
|
||||
currentResolutionMethod = "Anchor";
|
||||
setDocumentMessage(successMessage);
|
||||
window.PlotDirector?.toast?.success(successMessage);
|
||||
setDiagnostics({ lastError: "-" });
|
||||
updateAnchorDisplay();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Unable to attach PlotDirector IDs.", error);
|
||||
setDocumentMessage("Unable to attach PlotDirector IDs.");
|
||||
window.PlotDirector?.toast?.error("Unable to attach PlotDirector IDs.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
updateAnchorDisplay();
|
||||
return false;
|
||||
@ -4871,14 +4880,15 @@
|
||||
storedAnchorInvalid = false;
|
||||
currentResolutionAnchorType = "ChapterID Anchor";
|
||||
currentResolutionMethod = "Chapter anchor";
|
||||
setChapterCreateLinkStatus(successMessage);
|
||||
setDocumentMessage(successMessage);
|
||||
setChapterCreateLinkStatus("");
|
||||
window.PlotDirector?.toast?.success(successMessage);
|
||||
setDiagnostics({ lastError: "-" });
|
||||
updateAnchorDisplay();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Unable to attach PlotDirector chapter ID.", error);
|
||||
setChapterCreateLinkStatus("Unable to attach PlotDirector chapter ID.");
|
||||
window.PlotDirector?.toast?.error("Unable to attach PlotDirector chapter ID.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
updateAnchorDisplay();
|
||||
return false;
|
||||
@ -4892,8 +4902,8 @@
|
||||
const refreshAfterChapterLink = async (message) => {
|
||||
hideChapterCreateLink();
|
||||
await refreshPlotDirectorScene();
|
||||
setDocumentMessage(message);
|
||||
setChapterCreateLinkStatus(message);
|
||||
window.PlotDirector?.toast?.success(message);
|
||||
setChapterCreateLinkStatus("");
|
||||
};
|
||||
|
||||
const closeCreateChapterDialog = (confirmed) => {
|
||||
@ -4968,6 +4978,7 @@
|
||||
await refreshAfterChapterLink("Chapter created and linked successfully.");
|
||||
} catch (error) {
|
||||
setChapterCreateLinkStatus("Unable to create chapter.");
|
||||
window.PlotDirector?.toast?.error("Unable to create chapter.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
} finally {
|
||||
if (createPlotDirectorChapterButton) {
|
||||
@ -5095,6 +5106,7 @@
|
||||
} catch (error) {
|
||||
setText(linkChapterDialogStatus, "Unable to link chapter.");
|
||||
setChapterCreateLinkStatus("Unable to link chapter.");
|
||||
window.PlotDirector?.toast?.error("Unable to link chapter.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
} finally {
|
||||
if (linkSelectedChapterButton) {
|
||||
@ -5117,7 +5129,7 @@
|
||||
return false;
|
||||
}
|
||||
|
||||
setCreateLinkStatus(successMessage);
|
||||
setCreateLinkStatus("");
|
||||
hideSceneCreateLink();
|
||||
return true;
|
||||
};
|
||||
@ -5191,6 +5203,7 @@
|
||||
await resolveCreatedOrLinkedScene(response.sceneId, response.chapterId, "Scene created and linked successfully.");
|
||||
} catch (error) {
|
||||
setCreateLinkStatus("Unable to create scene.");
|
||||
window.PlotDirector?.toast?.error("Unable to create scene.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
} finally {
|
||||
if (createPlotDirectorSceneButton) {
|
||||
@ -5325,6 +5338,7 @@
|
||||
} catch (error) {
|
||||
setText(linkDialogStatus, "Unable to link scene.");
|
||||
setCreateLinkStatus("Unable to link scene.");
|
||||
window.PlotDirector?.toast?.error("Unable to link scene.");
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
} finally {
|
||||
if (linkSelectedSceneButton) {
|
||||
@ -5347,24 +5361,24 @@
|
||||
const source = options.source || "manual";
|
||||
const totalStartedAt = runtimePerformanceNow();
|
||||
if (!resolvedSceneId) {
|
||||
setSyncStatus("No resolved PlotDirector scene.");
|
||||
setSyncStatus("No resolved PlotDirector scene.", source);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!resolvedChapterId) {
|
||||
setSyncStatus("No resolved PlotDirector chapter.");
|
||||
setSyncStatus("No resolved PlotDirector chapter.", source);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sceneContextStale) {
|
||||
setSyncStatus("Refresh Current Scene before syncing.");
|
||||
setSyncStatus("Refresh Current Scene before syncing.", source);
|
||||
return;
|
||||
}
|
||||
|
||||
const book = selectedBook();
|
||||
const documentGuid = currentDocumentGuid();
|
||||
if (!book || !documentGuid) {
|
||||
setSyncStatus("Bound manuscript metadata is unavailable.");
|
||||
setSyncStatus("Bound manuscript metadata is unavailable.", source);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -5382,7 +5396,7 @@
|
||||
try {
|
||||
snapshot = isSnapshotFresh(snapshot) ? snapshot : await getFreshCurrentSceneSnapshot();
|
||||
} catch (error) {
|
||||
setSyncStatus("Sync failed");
|
||||
setSyncStatus("Sync failed", source);
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
runtimeDebug("Scene sync failed.");
|
||||
finishSceneWordCountSync();
|
||||
@ -5390,7 +5404,7 @@
|
||||
}
|
||||
|
||||
if (!isSnapshotFresh(snapshot)) {
|
||||
setSyncStatus("Waiting for typing to pause");
|
||||
setSyncStatus("Waiting for typing to pause", source);
|
||||
runtimeDebug("Scene sync skipped (stale snapshot).");
|
||||
finishSceneWordCountSync();
|
||||
return;
|
||||
@ -5398,14 +5412,14 @@
|
||||
|
||||
const wordCount = snapshot.wordCount;
|
||||
if (!Number.isInteger(wordCount) || wordCount < 0) {
|
||||
setSyncStatus("Sync failed");
|
||||
setSyncStatus("Sync failed", source);
|
||||
runtimeDebug("Scene sync failed.");
|
||||
finishSceneWordCountSync();
|
||||
return;
|
||||
}
|
||||
|
||||
if (lastSyncedSceneId === snapshot.sceneId && lastSyncedWordCount === wordCount) {
|
||||
setSyncStatus("Synced");
|
||||
setSyncStatus("Synced", source);
|
||||
runtimeDebug("Sync skipped (count unchanged).");
|
||||
finishSceneWordCountSync();
|
||||
return;
|
||||
@ -5418,7 +5432,7 @@
|
||||
syncSceneProgressButton.textContent = "Syncing...";
|
||||
}
|
||||
|
||||
setSyncStatus("Syncing...");
|
||||
setSyncStatus("Syncing...", source);
|
||||
runtimeDebug(`Scene sync started (${source}).`);
|
||||
try {
|
||||
const apiStartedAt = runtimePerformanceNow();
|
||||
@ -5442,11 +5456,11 @@
|
||||
setText(plotDirectorActualWords, displayValue(actualWords));
|
||||
setText(syncLastSynced, formatLastSynced(syncedAt));
|
||||
setText(runtimeLastSync, formatLastSynced(syncedAt));
|
||||
setSyncStatus("Synced");
|
||||
setSyncStatus("Synced", source);
|
||||
runtimeDebug("Scene sync succeeded.");
|
||||
runtimeTiming(`Total word count sync: ${Math.round(runtimePerformanceNow() - totalStartedAt)}ms`);
|
||||
} catch (error) {
|
||||
setSyncStatus("Sync failed");
|
||||
setSyncStatus("Sync failed", source);
|
||||
setDiagnostics({ lastError: errorText(error) });
|
||||
runtimeDebug("Scene sync failed.");
|
||||
} finally {
|
||||
|
||||
@ -39,6 +39,7 @@
|
||||
});
|
||||
const applyStatus = (status) => {
|
||||
lastOfficeStatus=status;
|
||||
window.dispatchEvent(new CustomEvent('plotdirector:office-presence', {detail:{connected:!!field(status, 'isConnected', 'IsConnected')}}));
|
||||
for(const root of roots)root.dataset.officeConnected=String(!!field(status,"isConnected","IsConnected"));
|
||||
const nativeMode=nativeState?.known&&(nativeState.ready||!field(status,"isConnected","IsConnected"));
|
||||
if(nativeMode)status={isConnected:nativeState.connected,documentOpen:nativeState.ready,currentDocumentName:nativeDocument?.documentTitle,companionVersion:'Native',lastHeartbeatUtc:nativeDocument?.updated};
|
||||
|
||||
@ -1,20 +1,58 @@
|
||||
// Presentation only. Observe existing presence events; never request or schedule Word work.
|
||||
// Presentation only: consume existing status events; never request or schedule Word work.
|
||||
(() => {
|
||||
if (window.PlotDirector.wordNotifications) return;
|
||||
window.PlotDirector.wordNotifications = true;
|
||||
const pd = window.PlotDirector ||= {};
|
||||
if (pd.wordNotifications) return;
|
||||
const connections = new Map(), failures = new Map(), manual = new Map();
|
||||
let connected = false, interrupted = false, dismissWarning;
|
||||
window.addEventListener('native-companion-presence', event => {
|
||||
const leases = event.detail;
|
||||
if (!Array.isArray(leases)) return;
|
||||
const available = leases.some(lease => lease.wordAvailable);
|
||||
if (connected && !available && !interrupted) {
|
||||
const key = lease => lease.instanceId + '/' + lease.sessionId;
|
||||
function connection(source, available) {
|
||||
connections.set(source, available);
|
||||
const next = [...connections.values()].some(Boolean);
|
||||
if (connected && !next && !interrupted) {
|
||||
interrupted = true;
|
||||
dismissWarning = window.PlotDirector.toast.warning('Word connection interrupted. Saved scenes remain available; check the Word connection indicator.');
|
||||
} else if (interrupted && available) {
|
||||
dismissWarning = pd.toast.warning('Word connection interrupted. Saved scenes remain available; check the Word connection indicator.');
|
||||
} else if (interrupted && next) {
|
||||
interrupted = false;
|
||||
dismissWarning?.();
|
||||
window.PlotDirector.toast.info('Word connection restored.');
|
||||
pd.toast.info('Word connection restored.');
|
||||
}
|
||||
connected = next;
|
||||
}
|
||||
function syncState(id, state, message, userRequested = false) {
|
||||
if (['failed', 'cancelled', 'needs-review'].includes(state)) {
|
||||
if (failures.get(id)?.state !== state) {
|
||||
failures.get(id)?.dismiss?.();
|
||||
failures.set(id, {state, dismiss: pd.toast[state === 'needs-review' ? 'warning' : 'error'](message)});
|
||||
}
|
||||
} else if (state === 'accepted') {
|
||||
failures.get(id)?.dismiss?.(); failures.delete(id);
|
||||
if (userRequested) pd.toast.success(message);
|
||||
}
|
||||
}
|
||||
pd.wordNotifications = {
|
||||
connection, syncState,
|
||||
forget(id) { manual.delete(id); },
|
||||
requested(lease, requestId) { if (requestId && !/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(requestId)) manual.set(key(lease), {requestId, revision:Number(lease.snapshotRevision)||0}); }
|
||||
};
|
||||
window.addEventListener('native-companion-presence', event => {
|
||||
if (Array.isArray(event.detail)) connection('native', event.detail.some(lease => lease.wordAvailable));
|
||||
});
|
||||
window.addEventListener('plotdirector:office-presence', event => connection('office', event.detail.connected));
|
||||
window.addEventListener('writer-word-state', event => {
|
||||
for (const lease of event.detail?.leases || []) {
|
||||
const id = key(lease), transfer = lease.paragraphTransfer, progress = lease.chapterProgress;
|
||||
const operation = manual.get(id);
|
||||
const requested = operation && operation.requestId === transfer?.requestId;
|
||||
const accepted = transfer?.kind === 'chapter' || lease.mappingCurrent && Number(lease.snapshotRevision) > operation?.revision;
|
||||
const state = transfer?.state;
|
||||
if (['failed', 'cancelled', 'needs-review'].includes(state)) {
|
||||
syncState(id, state, transfer.message || 'Word synchronisation did not complete. Check Companion details; accepted content is retained.');
|
||||
} else if (progress?.state === 'Needs review' || lease.chapterIssue === 'needs_review') {
|
||||
syncState(id, 'needs-review', progress?.message || 'Manuscript checking needs attention in Companion. Accepted content is retained.');
|
||||
} else if (state === 'accepted' || progress?.state === 'Synchronised') {
|
||||
syncState(id, 'accepted', 'Saved manuscript check completed.', requested && state === 'accepted' && accepted);
|
||||
}
|
||||
if (requested && (state === 'accepted' && accepted || ['failed', 'cancelled', 'needs-review'].includes(state))) manual.delete(id);
|
||||
}
|
||||
connected = available;
|
||||
});
|
||||
})();
|
||||
|
||||
@ -6,17 +6,19 @@ const reviewing=root.dataset.wordContext==='review',paragraphButton=root.querySe
|
||||
let availabilityKey='',availability={},availabilityEpoch=0,availabilityChecked=0;let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
|
||||
const selectionKey='plotdirector.writer.word-selection.'+(document.body.dataset.pdUserId||'')+'.'+book;
|
||||
let explicitSelection=null;try{const saved=JSON.parse(sessionStorage.getItem(selectionKey)||'null');if(typeof saved?.key==='string'&&/^[0-9a-f-]{36}\/[0-9a-f-]{36}$/i.test(saved.key)&&typeof saved.title==='string'&&saved.title.length<=260)explicitSelection=saved;}catch{}
|
||||
const key=l=>l.instanceId+'/'+l.sessionId;new MutationObserver(()=>{for(const status of document.querySelectorAll('[data-word-ribbon-status]'))status.textContent=message.textContent;}).observe(message,{childList:true,subtree:true,characterData:true});
|
||||
const key=l=>l.instanceId+'/'+l.sessionId;
|
||||
|
||||
const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l));
|
||||
const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status'));
|
||||
function render(data){chapter=Number(root.dataset.chapterId);scene=Number(root.dataset.sceneId);packet=data;const old=current;const leases=(data.leases||[]).filter(l=>l.wordAvailable&&l.bookId===book&&Date.parse(l.expires)>Date.now());const originParams=new URLSearchParams(location.search);const originKey=originParams.get('wordInstanceId')+'/'+originParams.get('wordSessionId');const selected=explicitSelection?.key||select.value||originKey;select.replaceChildren(new Option('Choose a document',''),...leases.map(l=>new Option(l.documentTitle,key(l))));const missingSelection=!!explicitSelection&&!leases.some(l=>key(l)===explicitSelection.key);if(missingSelection){const missing=new Option(explicitSelection.title+' · disconnected',explicitSelection.key);missing.disabled=true;select.add(missing);select.value=explicitSelection.key;}else if(leases.some(l=>key(l)===selected))select.value=selected;else if(leases.length===1)select.value=key(leases[0]);current=leases.find(l=>key(l)===select.value)||null;choose.hidden=leases.length<2&&!missingSelection;
|
||||
if(old&&(!current||key(old)!==key(current)||old.revision!==current.revision||old.manuscriptId!==current.manuscriptId)&&busy){abort?.abort();message.textContent='Word document changed or disconnected. Navigation was not confirmed.';}
|
||||
if(syncPending&&Date.now()-syncPending.started>120000){message.textContent='Saved manuscript check was not confirmed. Check Companion Troubleshooting before retrying; accepted content is retained.';window.PlotDirector?.toast?.error(message.textContent);window.PlotDirector?.wordNotifications?.forget(syncPending.key);}
|
||||
if(syncPending&&(!current||syncPending.key!==key(current)||Date.now()-syncPending.started>120000||(syncPending.requestId&¤t.paragraphTransfer?.requestId===syncPending.requestId&&['accepted','needs-review','failed','cancelled'].includes(current.paragraphTransfer.state))))syncPending=null;
|
||||
const identity=current&&data.canonical?.manuscriptID===current.manuscriptId;const observed=current&&verified(current);
|
||||
state.textContent=data.unavailable?'Word Companion status unavailable. Your saved work is retained.':!current?(missingSelection?'Selected Word document is disconnected. Choose another document explicitly.':leases.length>1?'Choose the correct Word manuscript.':(data.leases||[]).some(l=>l.wordAvailable)?'The open Word manuscript is for another book.':'Word Companion is not connected to this manuscript.'):!identity?'Word is connected, but this manuscript has not been verified.':`Manuscript: ${current.documentTitle}`;
|
||||
position.textContent=observed?`Word is showing ${observed.chapterTitle||'the verified chapter'}${observed.sceneId&&observed.sceneTitle?' · '+observed.sceneTitle:''}. ${observed.chapterId!==chapter?(reviewing?'Your review selection is separate.':'Your working focus is separate.'):''}`:current?.wordSaved===false?'Word has unsaved changes. Current positions await verification; no save will be forced.':current?.wordSaved===null?'Word position awaits a fresh observation. Check the intended document in Word; accepted text is retained.':'Word position has not been verified.';
|
||||
let status=!identity?'Your latest changes have not yet been confirmed in PlotDirector.':current.chapterProgress?.state==='Needs review'||current.chapterIssue==='needs_review'?'Manuscript checking needs attention in Companion. Accepted content is retained.':current.paragraphTransfer?.state==='failed'?'Manuscript update failed. Accepted content is retained.':current.chapterProgress?.state==='Synchronised'&¤t.wordSaved===true?'The last manuscript check completed. Later edits may still be pending.':current.chapterProgress?.state?`${current.chapterProgress.state}: ${current.chapterProgress.message||'Latest changes are not yet confirmed.'}`:'Latest changes are not yet confirmed. Check synchronisation in Companion.';
|
||||
if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+new Date(data.canonical.chapterAcceptedUtc).toLocaleString()+'.';else if(data.canonical?.snapshotUtc)status+=' Accepted snapshot recorded: '+new Date(data.canonical.snapshotUtc).toLocaleString()+'.';freshness.textContent=status;const warning=document.querySelector('[data-review-word-warning]');if(warning)warning.textContent='Showing accepted text. '+(!current?state.textContent:current.wordSaved===false?'Word has unsaved changes; they are not shown here.':status);
|
||||
if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+new Date(data.canonical.chapterAcceptedUtc).toLocaleString()+'.';else if(data.canonical?.snapshotUtc)status+=' Accepted snapshot recorded: '+new Date(data.canonical.snapshotUtc).toLocaleString()+'.';freshness.textContent=status;for(const ribbon of document.querySelectorAll('[data-word-ribbon-status]')){ribbon.textContent=!current?'Word disconnected':current.paragraphTransfer?.state==='failed'?'Sync failed':current.chapterProgress?.state||'Awaiting verification';ribbon.title=status;}const warning=document.querySelector('[data-review-word-warning]');if(warning)warning.textContent='Showing accepted text. '+(!current?state.textContent:current.wordSaved===false?'Word has unsaved changes; they are not shown here.':status);
|
||||
sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync);
|
||||
for(const button of [nav,sceneNav,paragraphButton])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation;
|
||||
if(identity&&!current.canAcknowledgeNavigation)position.textContent+=' Update the Word add-in and Companion together to enable confirmed navigation.';
|
||||
@ -69,14 +71,14 @@ async function navigate(toScene,toParagraph=false){
|
||||
if(result.state!=='requested'){
|
||||
if(result.state==='completed'&&(result.navigationId!==id||result.instanceId!==selected.instanceId||result.sessionId!==selected.sessionId||result.manuscriptId!==selected.manuscriptId||Number(result.revision)!==Number(selected.revision)))throw Error('Navigation confirmation did not match this document and request.');
|
||||
console.debug('Word navigation',id,'confirmation ms',Math.round(performance.now()-dispatch),result.state);
|
||||
message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;
|
||||
message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';window.PlotDirector?.toast?.[result.state==='completed'?'success':'error'](message.textContent);done=true;break;
|
||||
}
|
||||
}
|
||||
if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';
|
||||
}catch(error){availabilityKey='';availability={};message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}
|
||||
if(!done){message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';window.PlotDirector?.toast?.error(message.textContent);}
|
||||
}catch(error){availabilityKey='';availability={};message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;window.PlotDirector?.toast?.error(message.textContent);}
|
||||
finally{window.removeEventListener('plotdirector:native-presence-changed',hint);resume?.();busy=false;abort=null;if(packet)render(packet);requestStatus();}
|
||||
}
|
||||
sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';}finally{requestStatus();}});
|
||||
sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;window.PlotDirector?.wordNotifications?.requested(selected,result.requestId);message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';window.PlotDirector?.toast?.error(message.textContent);}finally{requestStatus();}});
|
||||
paragraphButton?.addEventListener('click',()=>void navigate(false,true));window.addEventListener('review-reference-changed',()=>{if(packet)render(packet);});
|
||||
nav?.addEventListener('click',()=>void navigate(false));sceneNav?.addEventListener('click',()=>void navigate(true));
|
||||
root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;availabilityKey='';availability={};message.textContent='Checking reported connection and accepted updates. Use Synchronise in Companion to request a bounded manuscript check.';requestStatus();setTimeout(()=>checkBusy=false,2000);});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user