diff --git a/PlotLine.Tests/Browser/word-destination-badges.cjs b/PlotLine.Tests/Browser/word-destination-badges.cjs new file mode 100644 index 00000000..ba8c9664 --- /dev/null +++ b/PlotLine.Tests/Browser/word-destination-badges.cjs @@ -0,0 +1,125 @@ +// Real Razor shell, simulated Companion transport. --installed runs an installed Chromium PWA. +const { chromium } = require('playwright'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const base = 'http://127.0.0.1:5238'; +(async () => { + const installed = process.argv.includes('--installed'); + const profile = installed ? fs.mkdtempSync('/tmp/pd-word-badge-pwa-') : null; + const context = installed + ? await chromium.launchPersistentContext(profile, { headless: false, viewport: {width:1440,height:1000} }) + : await (await chromium.launch()).newContext({ viewport: {width:1440,height:1000} }); + const browser = context.browser(); + await context.addInitScript(() => localStorage.setItem('plotdirector.desktop.v1.4', JSON.stringify({dismissedAt:Date.now()}))); + try { + let release, arrived; + const gate = new Promise(resolve => { release = resolve; }); + const requested = new Promise(resolve => { arrived = resolve; }); + 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,revision:2,expires:new Date(Date.now()+3600000).toISOString() }; + const packet = {leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[]}; + await context.route('**/native-companion/status*', async r => { arrived(); await gate; await r.fulfill({json:packet}); }); + await context.route('**/WriterWord/Availability?*', r => r.fulfill({json:{chapter:true,scene:true,paragraph:true}})); + await context.route('**/Writer/Work/State?*', r => r.fulfill({json:{session:null}})); + await context.route('**/signalr.min.js', r => r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))})); + const posts = []; + await context.route('**/WriterWord/Navigate', r => { + posts.push(Object.fromEntries(new URLSearchParams(r.request().postData()))); + return r.fulfill({status:202,json:{}}); + }); + await context.route('**/WriterWord/Navigation?*', r => r.fulfill({json:{state:'completed'}})); + let page; + if (installed) { + const tab = context.pages()[0]; await tab.goto(base+'/fixture'); + const cdp = await browser.newBrowserCDPSession(), manifestId = base+'/Projects'; + await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'}); + await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'}); + const opened = context.waitForEvent('page'); + await cdp.send('PWA.launch',{manifestId,url:base+'/fixture'}); + page = await opened; await page.waitForLoadState(); + assert(await page.evaluate(() => matchMedia('(display-mode: standalone)').matches)); + } else page = await context.newPage(); + const errors = []; page.on('pageerror', e => errors.push(e.message)); + const url = base+'/Writer/Write?projectId=7&bookId=12&objective=true'; + await page.goto(url, {waitUntil:'domcontentloaded'}); await requested; + const group = page.getByRole('group',{name:'Open in Word',exact:true}); + assert.equal(await group.locator('.pd-ribbon-group-label').textContent(),'Open in Word'); + const geometry = () => group.evaluate(n => [n.closest('.pd-ribbon-surface'), ...n.querySelectorAll('button,button > svg')].map(el => { + const r = el.getBoundingClientRect(); return [r.x,r.y,r.width,r.height]; + })); + const before = await geometry(); + for (const [target,label] of [['chapter','Chapter'],['scene','Scene'],['paragraph','Paragraph']]) { + const command = group.locator(`[data-ribbon-word=${target}]`); + assert(await command.isDisabled(), 'Safe initial state'); + assert.equal(await command.locator(':scope > span').textContent(),label); + assert.equal(await command.getAttribute('aria-label'),`Open current ${target} in Microsoft Word.`); + assert((await command.getAttribute('title')).includes(`Open current ${target} in Microsoft Word.`)); + assert.equal(await command.getAttribute('data-command-destination'),await command.locator('svg.pd-icon').getAttribute('data-destination')); + assert.equal(await command.locator('svg.pd-icon > path').count(),1); + assert.equal(await command.locator('.pd-destination-badge text').textContent(),'W'); + assert(await command.locator('.pd-destination-badge').isVisible(), 'Badge exists before status response'); + } + release(); + await page.waitForFunction(() => !document.querySelector('[data-ribbon-word=chapter]').disabled); + assert.deepEqual(await geometry(),before,'Async availability must not move the ribbon'); + assert.equal(await group.locator('[data-ribbon-word=chapter]').getAttribute('title'),'Open current chapter in Microsoft Word.'); + assert(await group.locator('[data-ribbon-word=paragraph]').isDisabled(),'Unverified paragraph remains disabled'); + // Verify each visual command still delegates the exact chapter/scene/paragraph target. + const expected = await page.locator('[data-writer-word]').evaluate(n => { + n.dataset.paragraphId='44444444-4444-4444-4444-444444444444';n.dataset.acceptedRevision='5'; + return {chapterId:n.dataset.chapterId,sceneId:n.dataset.sceneId,paragraphId:n.dataset.paragraphId}; + }); + await page.evaluate(packet => window.dispatchEvent(new CustomEvent('writer-word-state',{detail:packet})),packet); + await page.waitForFunction(() => !document.querySelector('[data-ribbon-word=paragraph]').disabled); + for (const target of ['chapter','scene','paragraph']) { + const previous = posts.length; + await group.locator(`[data-ribbon-word=${target}]`).click(); + await page.waitForFunction(() => document.querySelector('[data-word-command]').textContent.includes('Word confirmed navigation')); + assert.equal(posts.length,previous+1); + const sent=posts.at(-1);assert.equal(sent.chapterId,expected.chapterId); + assert.equal(sent.sceneId,target==='scene'?expected.sceneId:undefined); + assert.equal(sent.paragraphId,target==='paragraph'?expected.paragraphId:undefined); + if(target==='paragraph')assert.equal(sent.acceptedRevision,'5'); + } + let combinations = 0; + for (const theme of ['modern-light','modern-dark']) for (const width of [1440,800,390]) for (const zoom of [1,1.25,1.5]) { + await page.setViewportSize({width,height:1000}); + await page.evaluate(({theme,zoom}) => {window.PlotDirectorApplyApplicationTheme(theme);document.documentElement.style.zoom=zoom;},{theme,zoom}); + await group.scrollIntoViewIfNeeded(); + for (const command of await group.locator('button').all()) { + const metrics = await command.evaluate(n => { + const icon=n.querySelector('svg.pd-icon'),badge=n.querySelector('.pd-destination-badge'),r=icon.getBoundingClientRect(),b=badge.getBoundingClientRect(); + return {button:n.offsetHeight,w:icon.clientWidth,h:icon.clientHeight,inside:b.right<=r.right+.1&&b.bottom<=r.bottom+.1,ratio:b.width/r.width,blue:getComputedStyle(badge.querySelector('rect')).fill,white:getComputedStyle(badge.querySelector('text')).fill}; + }); + assert.equal(metrics.button,68);assert.equal(metrics.w,22);assert.equal(metrics.h,22); + assert(metrics.inside);assert(metrics.ratio>=.35&&metrics.ratio<=.4); + assert.equal(metrics.blue,'rgb(24, 90, 189)');assert.equal(metrics.white,'rgb(255, 255, 255)'); + } + if (width===1440&&zoom===1) { + fs.mkdirSync('/tmp/pd-word-badge-visuals',{recursive:true}); + await group.screenshot({path:`/tmp/pd-word-badge-visuals/${installed?'pwa':'browser'}-${theme}.png`}); + } + combinations++; + } + await page.evaluate(() => {document.documentElement.style.zoom='';}); + const previousPosts=posts.length; + for(const unsafe of [ + {leases:[]}, + {...packet,canonical:{manuscriptID:'mismatched'}}, + {...packet,leases:[{...lease,bookId:99}]}, + {...packet,leases:[{...lease,wordSaved:false}]}, + {...packet,leases:[{...lease,canAcknowledgeNavigation:false}]} + ]) { + await page.evaluate(value => window.dispatchEvent(new CustomEvent('writer-word-state',{detail:value})),unsafe); + for (const command of await group.locator('button').all()) { + assert(await command.isDisabled(),'Unsafe command remains disabled'); + await command.evaluate(n => n.click()); + } + } + assert.equal(posts.length,previousPosts,'Unsafe states dispatch no navigation'); + assert.deepEqual(errors,[]); + console.log(`PASS ${installed?'installed Chromium PWA':'browser'}: immediate badges, accessible names/tooltips, stable async geometry, safe disabled states; ${combinations} theme/width/scaling combinations, 22px icons and 68px buttons.`); + } finally { + await context.close(); await browser.close(); + if (profile) fs.rmSync(profile,{recursive:true,force:true}); + } +})().catch(e => {console.error(e);process.exitCode=1;}); diff --git a/PlotLine.Tests/Browser/writer3-word.cjs b/PlotLine.Tests/Browser/writer3-word.cjs index 6bdf0668..16469f79 100644 --- a/PlotLine.Tests/Browser/writer3-word.cjs +++ b/PlotLine.Tests/Browser/writer3-word.cjs @@ -3,22 +3,24 @@ const{chromium}=require('playwright'),assert=require('node:assert/strict'),fs=re const c=await browser.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()})));if(pwa)await c.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:{sessionID:'55555555-5555-5555-5555-555555555555',kind:'AudioReview',bookID:12,chapterID:22,chapterTitle:'Bound audio chapter',startedUtc:new Date().toISOString(),engagedSeconds:60,playbackSeconds:20,uniqueSeconds:10,pauseOnEdit:true,live:true,playbackState:'playing',capabilities:'play,pause,back15,forward15',sequence:1},defaultPauseOnEdit:true}})); 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,revision:2,documentTitle:'Disposable verified manuscript',chapterId:22,chapterTitle:'Other chapter',expires:new Date(Date.now()+3600000).toISOString(),updated:new Date().toISOString(),chapterProgress:{state:'Synchronised'}}; let packet={leases:[lease],canonical:{manuscriptID:lease.manuscriptId,revision:5,chapterAcceptedUtc:'2026-11-16T12:00:00Z'},verifiedPositions:[{instanceId:lease.instanceId,sessionId:lease.sessionId,chapterId:22,chapterTitle:'Other chapter'}]},posts=0,statusCalls=0,receipt='requested',syncs=0; + // Verified target availability is simulated with the rest of the transport. + await c.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:true,scene:true,paragraph:true}})); await c.route('**/native-companion/status*',r=>{statusCalls++;return r.fulfill({json:packet})});await c.route('**/WriterWord/Navigate',r=>{posts++;const body=new URLSearchParams(r.request().postData());assert.equal(body.get('chapterId'),'21');assert.equal(body.get('bookId'),'12');assert.equal(body.get('sessionId'),lease.sessionId);return r.fulfill({status:202,json:{message:'requested'}})});await c.route('**/WriterWord/Navigation?*',r=>r.fulfill({json:{state:receipt}}));await c.route('**/manuscript/paragraphs/snapshot',r=>{syncs++;assert(!new URLSearchParams(r.request().postData()).has('fullSnapshot'));return r.fulfill({json:{requestId:'request',message:'Bounded check requested'}})}); const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));const url='http://127.0.0.1:5238/Writer/Write?projectId=7&bookId=12&objective=true';await p.goto(url);await p.locator('[data-word-state]').filter({hasText:'Disposable verified manuscript'}).waitFor().catch(async e=>{throw Error(`${e.message}; state=${await p.locator('[data-word-state]').textContent()}; errors=${errors.join(';')}`)});assert((await p.locator('[data-word-position]').textContent()).includes('Other chapter'));assert((await p.locator('[data-writer-focus] h2').first().textContent()).includes('Arrival'));assert((await p.locator('[data-word-freshness]').textContent()).includes('last accepted'));assert(!/up to date/i.test(await p.locator('[data-word-freshness]').textContent())); const count=statusCalls;const resumed=p.waitForResponse(r=>r.url().includes('/native-companion/status'));await p.evaluate(()=>{window.dispatchEvent(new PageTransitionEvent('pagehide',{persisted:true}));window.dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}));});await resumed;assert(statusCalls>count,'shared status resumes after cached return'); const update=async value=>{packet=value;await p.evaluate(v=>window.dispatchEvent(new CustomEvent('writer-word-state',{detail:v})),value)};const initial=structuredClone(packet); await p.locator('[data-help-key="writer3.word"] button').click();await p.locator('.plotline-help-popover').waitFor();await p.locator('.plotline-help-more').click();await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-close]').click(); await p.locator('[data-work-note]').evaluate(n=>n.value='Unsaved return note');const work=await p.locator('[data-writer-work]').elementHandle();await p.locator('[data-word-navigate]').evaluate(b=>{b.click();b.click()});await p.locator('[data-word-command]').filter({hasText:'waiting for confirmation'}).waitFor();assert.equal(posts,1);assert(!(await p.locator('[data-word-command]').textContent()).includes('confirmed navigation'));receipt='completed';await p.locator('[data-word-command]').filter({hasText:'Word confirmed navigation.'}).waitFor();assert(await work.evaluate(n=>n===document.querySelector('[data-writer-work]')));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved return note');assert((await p.locator('[data-work-bound]').textContent()).includes('Bound audio chapter'));assert(await p.locator('[data-work-audio]').isVisible()); - receipt='timed-out';await p.locator('[data-word-navigate]').click();await p.locator('[data-word-command]').filter({hasText:'expired'}).waitFor(); + receipt='timed-out';await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'expired'}).waitFor(); await p.getByText('Connection and update options',{exact:true}).click();await p.locator('[data-word-sync]').click();await p.locator('[data-word-command]').filter({hasText:'acceptance has not yet been confirmed'}).waitFor();assert.equal(syncs,1); await update({...initial,leases:[{...lease,canAcknowledgeNavigation:false}]});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-position]').textContent()).includes('Update the Word add-in')); await update({...initial,canonical:{manuscriptID:'foreign'}});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-state]').textContent()).includes('not been verified')); await update({...initial,leases:[{...lease,wordSaved:false}],verifiedPositions:[]});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-position]').textContent()).includes('unsaved')); await update({...initial,leases:[{...lease,bookId:99}],verifiedPositions:[]});assert(await p.locator('[data-word-navigate]').isDisabled());assert((await p.locator('[data-word-state]').textContent()).includes('another book')); await update({unavailable:true});assert((await p.locator('[data-word-state]').textContent()).includes('unavailable'));assert.equal(await p.locator('[data-work-note]').inputValue(),'Unsaved return note'); - const second={...lease,sessionId:'44444444-4444-4444-4444-444444444444',documentTitle:'Second manuscript'};await update({...initial,leases:[lease,second]});assert(await p.locator('[data-word-choose]').isVisible());assert(await p.locator('[data-word-navigate]').isDisabled());await p.locator('[data-word-document]').selectOption(lease.instanceId+'/'+lease.sessionId);assert(await p.locator('[data-word-navigate]').isEnabled()); - receipt='requested';await p.locator('[data-word-navigate]').click();await p.locator('[data-word-command]').filter({hasText:'waiting for confirmation'}).waitFor();await update({...initial,leases:[second],verifiedPositions:[]});await p.locator('[data-word-command]').filter({hasText:'not confirmed'}).waitFor(); + const second={...lease,sessionId:'44444444-4444-4444-4444-444444444444',documentTitle:'Second manuscript'};await update({...initial,leases:[lease,second]});assert(await p.locator('[data-word-choose]').isVisible());assert(await p.locator('[data-word-navigate]').isDisabled());await p.locator('[data-word-document]').selectOption(lease.instanceId+'/'+lease.sessionId);await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);assert(await p.locator('[data-word-navigate]').isEnabled()); + receipt='requested';await p.locator('[data-ribbon-word=chapter]').click();await p.locator('[data-word-command]').filter({hasText:'waiting for confirmation'}).waitFor();await update({...initial,leases:[second],verifiedPositions:[]});await p.locator('[data-word-command]').filter({hasText:'not confirmed'}).waitFor(); await p.goto(url+'&wordInstanceId='+lease.instanceId+'&wordSessionId='+lease.sessionId);packet=initial;await update(initial);await p.locator('[data-word-adopt]').waitFor().catch(async e=>{throw Error(`${e.message}; ${JSON.stringify(await p.locator('[data-writer-word]').evaluate(n=>({chapter:n.dataset.chapterId,adoptHidden:n.querySelector('[data-word-adopt]').hidden,state:n.querySelector('[data-word-state]').textContent,position:n.querySelector('[data-word-position]').textContent,asideHidden:n.closest('aside').hidden})))}`)});assert.equal(await p.locator('[data-word-adopt] [name=ChapterID]').inputValue(),'22');assert((await p.locator('[data-word-origin]').textContent()).includes('unchanged')); if(!pwa&&process.env.PD_WRITER3_SCREENSHOTS){fs.mkdirSync(process.env.PD_WRITER3_SCREENSHOTS,{recursive:true});await p.evaluate(()=>window.PlotDirectorApplyApplicationTheme('modern-dark'));await p.screenshot({path:process.env.PD_WRITER3_SCREENSHOTS+'/Write-verified-simulated.png',animations:'disabled'});} - await p.setViewportSize({width:390,height:844});await p.locator('.writer3-layout-tools button').first().click();await p.locator('[data-writer-word]').scrollIntoViewIfNeeded();assert(await p.locator('[data-word-navigate]').isVisible());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert(await p.locator('.writer3-reference').isVisible());await p.keyboard.press('Escape');assert(await p.locator('.writer3-reference').isHidden());assert.deepEqual(errors,[]);await c.close();} - console.log('PASS Writer Word browser/simulated PWA: exact document status, focus isolation, old/uncertain/unsaved/cross-book rejection, explicit chapter handoff, acknowledgement versus request, timeout, repeat guard, bounded check, multi-document selection, disconnect, retained notes/DOM, verified-origin adoption, Help and narrow overlay. Native events and acknowledgements simulated.');}finally{await browser.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); + await p.setViewportSize({width:390,height:844});await p.locator('[data-ribbon-word=chapter]').scrollIntoViewIfNeeded();assert(await p.locator('[data-ribbon-word=chapter]').isVisible());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert.deepEqual(errors,[]);await c.close();} + console.log('PASS Writer Word browser/simulated PWA: exact document status, focus isolation, old/uncertain/unsaved/cross-book rejection, explicit chapter handoff, acknowledgement versus request, timeout, repeat guard, bounded check, multi-document selection, disconnect, retained notes/DOM, verified-origin adoption, Help and narrow ribbon. Native events and acknowledgements simulated.');}finally{await browser.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine/TagHelpers/DestinationIconTagHelper.cs b/PlotLine/TagHelpers/DestinationIconTagHelper.cs new file mode 100644 index 00000000..102f27b3 --- /dev/null +++ b/PlotLine/TagHelpers/DestinationIconTagHelper.cs @@ -0,0 +1,42 @@ +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Razor.TagHelpers; +using PlotLine.Services; + +namespace PlotLine.TagHelpers; + +// Content and destination stay independent. Omit destination for an unbadged icon. +[HtmlTargetElement("destination-icon", Attributes = "primary-icon")] +public sealed class DestinationIconTagHelper : TagHelper +{ + public string PrimaryIcon { get; set; } = ""; + public string? Destination { get; set; } + public string? AccessibleLabel { get; set; } + + public override void Process(TagHelperContext context, TagHelperOutput output) + { + output.TagName = "svg"; + output.TagMode = TagMode.StartTagAndEndTag; + output.Attributes.SetAttribute("class", "pd-icon pd-destination-icon"); + output.Attributes.SetAttribute("viewBox", "0 0 24 24"); + output.Attributes.SetAttribute("focusable", "false"); + output.Attributes.SetAttribute("data-destination", Destination); + if (string.IsNullOrWhiteSpace(AccessibleLabel)) + output.Attributes.SetAttribute("aria-hidden", "true"); + else + { + output.Attributes.SetAttribute("role", "img"); + output.Attributes.SetAttribute("aria-label", AccessibleLabel); + } + + var primary = new TagBuilder("path"); + primary.Attributes["d"] = ApplicationRibbon.Icon(PrimaryIcon).IconPath; + output.Content.AppendHtml(primary); + if (Destination == "word") + output.Content.AppendHtml(""" + + """); + } +} diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index 6970e3f0..743f04cd 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -173,10 +173,12 @@ } @if(category.Key==selectedCategory && book!=null && category.Key is "writer" or "book" or "story"){ -