Persist shared chapter and scene Intent checklists
This commit is contained in:
parent
5875ba53fb
commit
53dd80d9da
@ -26,6 +26,51 @@ let session, stage = 'login';
|
||||
}
|
||||
stage='chapter-only/no-prose read';
|
||||
assert.deepEqual((await read()).entries, []);
|
||||
const chapterUrl = '/Writing/Context?' + new URLSearchParams({
|
||||
projectId:project, bookId:book, chapterId:chapter, pinned:true
|
||||
});
|
||||
stage='chapter checklist without a scene or manuscript';
|
||||
await session.goto(chapterUrl);
|
||||
await session.page.locator('[data-context-tab]').first().selectOption('intent');
|
||||
const checklist = session.page.locator('[data-intent-checklist]');
|
||||
const items = checklist.locator('[data-checklist-items] > li');
|
||||
const getChecklist = () => session.page.evaluate(async ({bookID,chapterID}) =>
|
||||
(await fetch('/Writing/Context/Intent/Checklist?' + new URLSearchParams({bookID,chapterID}))).json(), base);
|
||||
await checklist.getByText('Paste a checklist', {exact:true}).click();
|
||||
await checklist.getByLabel('Checklist text').fill('- [ ] Reveal the promise\n- [ ] Establish the setting');
|
||||
await checklist.getByRole('button',{name:'Preview',exact:true}).click();
|
||||
const review = checklist.locator('[data-checklist-preview-items]');
|
||||
await review.getByLabel('Item').first().fill('Keep the promise');
|
||||
await checklist.getByRole('button',{name:'Add reviewed items'}).click();
|
||||
await items.nth(1).getByRole('button',{name:'Up',exact:true}).click();
|
||||
await items.nth(1).getByLabel('Complete',{exact:true}).check();
|
||||
await items.nth(1).getByLabel('Changed',{exact:true}).check();
|
||||
await items.nth(1).getByLabel('Notes',{exact:true}).fill('Author note survives a fresh login');
|
||||
const original = await getChecklist();
|
||||
await checklist.getByRole('button',{name:'Save checklist'}).click();
|
||||
await checklist.getByRole('button',{name:'Save checklist'}).waitFor({state:'visible'});
|
||||
await session.page.waitForFunction(() => document.querySelector('[data-checklist-save]').disabled &&
|
||||
!document.querySelector('[data-checklist-items]').inert);
|
||||
const saved = await getChecklist();
|
||||
assert.deepEqual(saved.items.map(item => [item.text,item.completed,item.changed]), [
|
||||
['Establish the setting',false,false], ['Keep the promise',true,true]
|
||||
]);
|
||||
assert.equal(saved.items[1].notes,'Author note survives a fresh login');
|
||||
const stale = await checklist.evaluate(async (element, {base,original}) => {
|
||||
const response = await fetch(element.dataset.url, {
|
||||
method:'POST', headers:{
|
||||
'Content-Type':'application/json',
|
||||
RequestVerificationToken:element.querySelector('[name=__RequestVerificationToken]').value
|
||||
},
|
||||
body:JSON.stringify({...base,version:original.version,items:[]})
|
||||
});
|
||||
return response.status;
|
||||
}, {base,original});
|
||||
assert.equal(stale,409,'A stale save cannot delete the new checklist');
|
||||
await session.page.reload();
|
||||
await session.page.locator('[data-context-tab]').first().selectOption('intent');
|
||||
await items.nth(1).getByLabel('Complete',{exact:true}).waitFor();
|
||||
assert.equal(await items.nth(1).getByLabel('Complete',{exact:true}).isChecked(),true);
|
||||
stage='canonical equal-label fixtures';
|
||||
const name='Palette shared name';
|
||||
const person = await session.create('Characters','?projectId='+project,{CharacterName:name},async page=>{
|
||||
@ -66,7 +111,7 @@ let session, stage = 'login';
|
||||
await session.page.locator('[data-context-tab]').first().selectOption('intent');
|
||||
const panel=session.page.locator('[data-context-intent]');
|
||||
await panel.locator('[data-entity-key="location:'+literal+'"]').waitFor();
|
||||
await panel.getByLabel('Current scene only').check();
|
||||
await panel.locator('[data-intent-palette]').getByLabel('Current scene only').check();
|
||||
const search=panel.getByRole('searchbox',{name:'Search story'});
|
||||
await panel.getByText('Scene location',{exact:false}).first().waitFor();
|
||||
await panel.locator('[data-entity-key="location:'+literal+'"]').waitFor({state:'detached'});
|
||||
@ -74,8 +119,22 @@ let session, stage = 'login';
|
||||
await panel.locator('[data-entity-key="character:'+person+'"]').waitFor();
|
||||
assert.equal(await search.evaluate(input=>input===document.activeElement),true);
|
||||
assert.equal(session.page.url().endsWith(contextUrl),true,'Palette browsing preserves Context position');
|
||||
stage='held checklist Story Element link and coverage';
|
||||
await panel.locator('[data-entity-key="character:'+person+'"]').getByRole('button',{name:'Select Palette shared name to link'}).click();
|
||||
await items.first().getByRole('button',{name:'Link Palette shared name'}).click();
|
||||
assert.equal(await items.first().getByLabel('Complete',{exact:true}).isChecked(),false);
|
||||
await items.first().getByLabel('Palette shared name covered').check();
|
||||
assert.equal(await items.first().getByLabel('Complete',{exact:true}).isChecked(),false);
|
||||
await checklist.getByRole('button',{name:'Save checklist'}).click();
|
||||
await session.page.waitForFunction(() => document.querySelector('[data-checklist-save]').disabled &&
|
||||
!document.querySelector('[data-checklist-items]').inert);
|
||||
assert.deepEqual((await getChecklist()).items[0].links,[{key:'character:'+person,name,covered:true}]);
|
||||
await checklist.getByLabel('Scene checklist').check();
|
||||
await checklist.getByText('No checklist items',{exact:true}).waitFor();
|
||||
await checklist.getByLabel('Scene checklist').uncheck();
|
||||
await items.first().getByLabel('Palette shared name covered').waitFor();
|
||||
await panel.getByText('Story Elements',{exact:true}).click();
|
||||
assert.equal(await panel.locator('details').evaluate(details=>details.open),false);
|
||||
assert.equal(await panel.locator('[data-intent-palette]').evaluate(details=>details.open),false);
|
||||
stage='invalid and mismatched scope denial';
|
||||
stage='chapter/book mismatch denial';await read({chapterID:otherChapter},403);
|
||||
stage='book/chapter mismatch denial';await read({bookID:otherBook},403);
|
||||
@ -84,6 +143,12 @@ let session, stage = 'login';
|
||||
stage='oversized search rejection';await read({search:'x'.repeat(201)},400);
|
||||
stage='fresh login persistence and read-only source';
|
||||
await session.close(); session=await open();
|
||||
await session.goto(chapterUrl);
|
||||
await session.page.locator('[data-context-tab]').first().selectOption('intent');
|
||||
await session.page.locator('[data-intent-checklist] [data-checklist-items] > li').first().waitFor();
|
||||
const reloaded = await getChecklist();
|
||||
assert.equal(reloaded.items[0].links[0].key,'character:'+person);
|
||||
assert.equal(reloaded.items[1].notes,'Author note survives a fresh login');
|
||||
scoped=await read({sceneID:first});
|
||||
assert.equal(scoped.entries[0].key,'location:'+place,'Fresh palette identity');
|
||||
// Independently reload the normal authorised source form from the server. This
|
||||
@ -92,13 +157,14 @@ let session, stage = 'login';
|
||||
const editor=session.page.locator('form[data-scene-editor-form]');
|
||||
assert.equal(await editor.locator('[name=PrimaryLocationID]').inputValue(),String(place),'Source location');
|
||||
assert.equal(await editor.locator('[name=SceneTitle]').inputValue(),'Palette first scene','Source title');
|
||||
console.log(JSON.stringify({passed:true,milestone:'Context Story Elements palette',checks:[
|
||||
'chapter without prose or scenes','canonical identity separation and hidden-label ambiguity',
|
||||
console.log(JSON.stringify({passed:true,milestone:'Context Intent and Story Elements',checks:[
|
||||
'chapter without prose or scenes, paste preview, order, flags and notes',
|
||||
'stale checklist write denial and independent link coverage', 'canonical identity separation and hidden-label ambiguity',
|
||||
'case-insensitive wider search and literal percent','chapter and optional scene associations/provenance',
|
||||
'Context chapter and scene browsing, search, collapse and focus',
|
||||
'book/chapter/scene mismatch denial and query limits','fresh login reads authoritative saved sources'
|
||||
],featureUrl:'https://dev.plotdirector.com/Writing/Context/Intent/Palette?'+new URLSearchParams(base),
|
||||
limitations:['interactive checklist, docked Writer and candidate fixture acceptance remain outstanding']}));
|
||||
limitations:['Docked Writer, Word evidence and review candidate fixtures are outside this script']}));
|
||||
} catch(error) {
|
||||
console.error('Intent palette acceptance failed at '+stage+' ('+error.name+'). No credentials logged.');
|
||||
if(error.name==='AssertionError') console.error(error.message);
|
||||
|
||||
@ -8,7 +8,7 @@ namespace PlotLine.Controllers;
|
||||
[Authorize]
|
||||
[Route("Writing/Context/Intent")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ContextIntentController(ContextIntentPalette palette) : Controller
|
||||
public sealed class ContextIntentController(ContextIntentPalette palette, ContextIntentChecklist checklist) : Controller
|
||||
{
|
||||
// Reusable read endpoint for both Context and the docked Writer component.
|
||||
// It takes an explicit held scope and never follows or changes the Word caret.
|
||||
@ -24,6 +24,48 @@ public sealed class ContextIntentController(ContextIntentPalette palette) : Cont
|
||||
new IntentPaletteScope(projectId, bookId, chapterId, sceneId));
|
||||
}
|
||||
|
||||
[HttpGet("Checklist")]
|
||||
public Task<IActionResult> Checklist(int bookId, int chapterId, int? sceneId) =>
|
||||
ReadChecklist(bookId, chapterId, sceneId);
|
||||
|
||||
[HttpGet("Passages")]
|
||||
public async Task<IActionResult> Passages(int bookId, int chapterId, int? sceneId)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest();
|
||||
try { return Json(await checklist.Passages(bookId, chapterId, sceneId)); }
|
||||
catch (ArgumentException e) { return BadRequest(new { message = e.Message }); }
|
||||
catch (UnauthorizedAccessException) { return StatusCode(StatusCodes.Status403Forbidden); }
|
||||
catch (SqlException e) when (e.Number == 51010) { return StatusCode(StatusCodes.Status403Forbidden); }
|
||||
}
|
||||
|
||||
[HttpPost("Checklist")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public Task<IActionResult> SaveChecklist([FromBody] IntentChecklistSave? request) =>
|
||||
request is null ? Task.FromResult<IActionResult>(BadRequest())
|
||||
: ReadChecklist(request.BookID, request.ChapterID, request.SceneID, request);
|
||||
|
||||
[HttpPost("Preview")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public IActionResult Preview([FromBody] string? text)
|
||||
{
|
||||
if (!ModelState.IsValid || text is null) return BadRequest();
|
||||
try { return Json(ContextIntentText.Parse(text)); }
|
||||
catch (ArgumentException e) { return BadRequest(new { message = e.Message }); }
|
||||
}
|
||||
|
||||
private async Task<IActionResult> ReadChecklist(int bookId, int chapterId, int? sceneId,
|
||||
IntentChecklistSave? save = null)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest();
|
||||
try { return Json(await checklist.Load(bookId, chapterId, sceneId, save)); }
|
||||
catch (ArgumentException e) { return BadRequest(new { message = e.Message }); }
|
||||
catch (UnauthorizedAccessException) { return StatusCode(StatusCodes.Status403Forbidden); }
|
||||
catch (SqlException e) when (e.Number == 51010) { return StatusCode(StatusCodes.Status403Forbidden); }
|
||||
catch (InvalidOperationException e) { return Conflict(new { message = e.Message }); }
|
||||
catch (SqlException e) when (e.Number == 51011) { return Conflict(new { message = "The saved checklist changed. Your draft is still here." }); }
|
||||
catch (SqlException e) when (e.Number == 51012) { return BadRequest(new { message = "Review the checklist items and try again." }); }
|
||||
}
|
||||
|
||||
[HttpGet("Palette")]
|
||||
public async Task<IActionResult> Palette([FromQuery] IntentPaletteQuery query)
|
||||
{
|
||||
|
||||
@ -28,6 +28,14 @@ public sealed class ParagraphManuscriptRepository(ISqlConnectionFactory factory)
|
||||
using var db=factory.CreateConnection(); db.Open(); using var transaction=db.BeginTransaction();
|
||||
var previousJson=await db.QuerySingleOrDefaultAsync<string>("dbo.WritingActivity",new{Action="lock",UserID=user,BookID=state.BookId},transaction,commandType:CommandType.StoredProcedure);
|
||||
var previous=previousJson==null?null:JsonSerializer.Deserialize<ParagraphManuscript>(previousJson);
|
||||
if (previous?.LastRequestId != request)
|
||||
{
|
||||
var priorText = previous?.Paragraphs.ToDictionary(p => p.Occurrence.Id, p => p.Occurrence.Text);
|
||||
state.IntentChangedParagraphs = priorText is null ? null : state.Paragraphs
|
||||
.Where(p => p.Story && (!priorText.TryGetValue(p.Occurrence.Id, out var before)
|
||||
|| !string.Equals(before, p.Occurrence.Text, StringComparison.Ordinal)))
|
||||
.Select(p => p.Occurrence.Id).ToArray();
|
||||
}
|
||||
var json=await db.QuerySingleAsync<string>("dbo.ParagraphManuscript",new{Action="save",UserID=user,BookID=state.BookId,ExpectedRevision=expected,RequestID=request,ChangedChapterID=chapter,Payload=JsonSerializer.Serialize(state)},transaction,commandType:CommandType.StoredProcedure);
|
||||
var accepted=JsonSerializer.Deserialize<ParagraphManuscript>(json)!;
|
||||
if(previous?.LastRequestId!=request)
|
||||
|
||||
@ -2252,7 +2252,17 @@ public sealed class SceneChecklistItem
|
||||
public DateTime? CreatedDateUTC { get; set; }
|
||||
public DateTime? ModifiedDateUTC { get; set; }
|
||||
public int SceneChecklistItemID { get; set; }
|
||||
public int SceneID { get; set; }
|
||||
public int? SceneID { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
|
||||
public int? ChapterID { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault)]
|
||||
public bool IsChanged { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? AuthorNotes { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? IntentLinksJson { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? IntentEvidenceJson { get; set; }
|
||||
public string ItemText { get; set; } = string.Empty;
|
||||
public bool IsCompleted { get; set; }
|
||||
public int? SortOrder { get; set; }
|
||||
|
||||
@ -15,6 +15,8 @@ public sealed class ParagraphManuscript
|
||||
public string Mode {get;set;}="Manual";
|
||||
public DateTime UpdatedUtc {get;set;}
|
||||
public List<PlotLine.Services.Manuscript.ChapterCheckpoint> ChapterCheckpoints {get;set;}=[];
|
||||
[System.Text.Json.Serialization.JsonIgnore(Condition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull)]
|
||||
public Guid[]? IntentChangedParagraphs { get; set; }
|
||||
public List<StoryParagraph> Paragraphs {get;set;}=[];
|
||||
public List<ParagraphChapter> Chapters {get;set;}=[];
|
||||
public List<ParagraphScene> Scenes {get;set;}=[];
|
||||
|
||||
@ -312,6 +312,7 @@ public class Program
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextThreads>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextAssets>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextIntentPalette>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextIntentChecklist>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextWarnings>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Context.ContextRelationshipEditing>();
|
||||
builder.Services.AddScoped<PlotLine.Data.IContextRelationshipReader,PlotLine.Data.ContextRelationshipReader>();
|
||||
|
||||
218
PlotLine/Services/Context/ContextIntentChecklist.cs
Normal file
218
PlotLine/Services/Context/ContextIntentChecklist.cs
Normal file
@ -0,0 +1,218 @@
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
|
||||
namespace PlotLine.Services.Context;
|
||||
|
||||
public sealed record IntentChecklistLink(string Key, bool Covered, string? Name = null);
|
||||
public sealed record IntentChecklistEvidence(Guid? Id, Guid Paragraph, long Revision, string Quote);
|
||||
public sealed record IntentChecklistItem(int? Id, string Text, bool Completed, bool Changed, string? Notes,
|
||||
IntentChecklistLink[]? Links = null, IntentChecklistEvidence[]? Evidence = null);
|
||||
|
||||
internal static class IntentChecklistLinks
|
||||
{
|
||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
private static readonly IReadOnlyDictionary<string, string> Collections = new Dictionary<string, string>
|
||||
{
|
||||
["character"] = "Characters", ["location"] = "Locations", ["asset"] = "StoryAssets",
|
||||
["plotline"] = "PlotLines", ["thread"] = "PlotThreads", ["candidate"] = "StoryIntelligenceReviewCandidates",
|
||||
["narrative-candidate"] = "StoryIntelligenceNarrativeCandidates"
|
||||
};
|
||||
|
||||
public static bool Valid(IntentChecklistLink[]? links) => links is null || links.Length <= 40
|
||||
&& links.All(link => link is not null && link.Key is { Length: > 0 and <= 80 }
|
||||
&& (TryIdentity(link.Key, out _, out _) || Historical(link.Key)))
|
||||
&& links.Select(link => link.Key).Distinct(StringComparer.Ordinal).Count() == links.Length;
|
||||
|
||||
private static bool Historical(string key) => key.StartsWith("historical:", StringComparison.Ordinal)
|
||||
&& Guid.TryParseExact(key[11..], "N", out _);
|
||||
|
||||
private static bool TryIdentity(string key, out string table, out int id)
|
||||
{
|
||||
table = "";
|
||||
id = 0;
|
||||
var delimiter = key.IndexOf(':');
|
||||
if (delimiter < 1 || !Collections.TryGetValue(key[..delimiter], out var collection)
|
||||
|| !int.TryParse(key[(delimiter + 1)..], System.Globalization.NumberStyles.None,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out id) || id <= 0
|
||||
|| key[(delimiter + 1)..] != id.ToString(System.Globalization.CultureInfo.InvariantCulture))
|
||||
return false;
|
||||
table = collection;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool IsValidBackup(string? value)
|
||||
{
|
||||
if (value is null) return true;
|
||||
try
|
||||
{
|
||||
var links = JsonSerializer.Deserialize<IntentChecklistLink[]>(value, Json);
|
||||
return links is not null && Valid(links)
|
||||
&& links.All(link => link.Name is { Length: > 0 and <= 450 });
|
||||
}
|
||||
catch (JsonException) { return false; }
|
||||
}
|
||||
|
||||
public static string? Remap(string? value, Dictionary<string, Dictionary<int, int>> maps)
|
||||
{
|
||||
if (value is null) return null;
|
||||
var links = JsonSerializer.Deserialize<IntentChecklistLink[]>(value, Json)!;
|
||||
return JsonSerializer.Serialize(links.Select(link =>
|
||||
{
|
||||
if (!TryIdentity(link.Key, out var table, out var id)) return link;
|
||||
var key = maps.TryGetValue(table, out var mapping) && mapping.TryGetValue(id, out var target)
|
||||
? link.Key[..(link.Key.IndexOf(':') + 1)] + target.ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
: "historical:" + Guid.NewGuid().ToString("N");
|
||||
return link with { Key = key };
|
||||
}), Json);
|
||||
}
|
||||
}
|
||||
public sealed record IntentChecklistSave(int BookID, int ChapterID, int? SceneID, string Version, IntentChecklistItem[] Items);
|
||||
public sealed record IntentChecklistFrame(int ProjectID, bool CanEdit, string Version, string? Objective, string? Outcome, IntentChecklistItem[] Items);
|
||||
|
||||
public sealed record IntentPassageReference(Guid Paragraph, long Revision, string Text, IReadOnlyList<IntentPassageMention> Mentions, bool MatchingLimited = false);
|
||||
public sealed record IntentPassageMention(string Text, IReadOnlyList<IntentChecklistLink> Elements);
|
||||
|
||||
public sealed class ContextIntentChecklist(ISqlConnectionFactory connections, ICurrentUserService user,
|
||||
IParagraphManuscriptRepository manuscripts,
|
||||
ContextWorkspaceNotifications notifications)
|
||||
{
|
||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||
private sealed record State(int ProjectID, bool CanEdit, string Version, string ItemsJson, string? Objective, string? Outcome);
|
||||
|
||||
private sealed record Identity(string EntityKey, string Name);
|
||||
|
||||
private static IEnumerable<StoryParagraph> Scoped(ParagraphManuscript state, int chapterId, int? sceneId)
|
||||
{
|
||||
var scenes = state.Scenes.Where(s => !s.Retired && s.CanonicalId > 0 && s.ChapterId == chapterId
|
||||
&& (!sceneId.HasValue || s.CanonicalId == sceneId)).Select(s => s.Id).ToHashSet();
|
||||
return state.Paragraphs.Where(p => p.Story && p.PositionVerified && p.ChapterId == chapterId
|
||||
&& p.SceneId.HasValue && scenes.Contains(p.SceneId.Value));
|
||||
}
|
||||
|
||||
public async Task<IntentPassageReference[]> Passages(int bookId, int chapterId, int? sceneId)
|
||||
{
|
||||
var checklist = await Load(bookId, chapterId, sceneId);
|
||||
var author = user.UserId!.Value;
|
||||
var manuscript = await manuscripts.Get(author, bookId);
|
||||
if (manuscript?.IntentChangedParagraphs is not { Length: > 0 } changed
|
||||
|| manuscript.ProjectId != checklist.ProjectID) return [];
|
||||
|
||||
var ids = changed.ToHashSet();
|
||||
var passages = Scoped(manuscript, chapterId, sceneId)
|
||||
.Where(p => ids.Contains(p.Occurrence.Id) && !string.IsNullOrWhiteSpace(p.Occurrence.Text)
|
||||
&& p.Occurrence.Text.Length <= ContextIntentText.MaximumPassageLength).Take(20).ToArray();
|
||||
if (passages.Length == 0) return [];
|
||||
|
||||
using var db = connections.CreateConnection();
|
||||
using var reader = await db.QueryMultipleAsync("dbo.ContextIntent_MatchingIndex",
|
||||
new { UserID = author, BookID = bookId, ChapterID = chapterId, SceneID = sceneId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
var names = (await reader.ReadAsync<Identity>()).ToDictionary(i => i.EntityKey, i => i.Name, StringComparer.Ordinal);
|
||||
var aliases = (await reader.ReadAsync<ContextIntentPalette.AliasRow>()).ToLookup(a => a.EntityKey, a => a.Alias, StringComparer.Ordinal);
|
||||
var catalog = names.Select(pair => new ContextIntentText.Entity(pair.Key, pair.Value, aliases[pair.Key].ToArray(), [])).ToArray();
|
||||
return passages.Select(p =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var mentions = ContextIntentText.Match(p.Occurrence.Text, catalog)
|
||||
.Select(m => new IntentPassageMention(m.Text, m.EntityKeys
|
||||
.Select(key => new IntentChecklistLink(key, false, names[key])).ToArray()))
|
||||
.ToArray();
|
||||
return new IntentPassageReference(p.Occurrence.Id, manuscript.Revision, p.Occurrence.Text, mentions);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return new IntentPassageReference(p.Occurrence.Id, manuscript.Revision, p.Occurrence.Text, [], MatchingLimited: true);
|
||||
}
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
internal static bool ValidEvidence(IntentChecklistEvidence[]? evidence) => evidence is null ||
|
||||
evidence.Length <= ContextIntentDraft.MaximumEvidence && evidence.All(e => e is not null
|
||||
&& e.Id != Guid.Empty && e.Paragraph != Guid.Empty && e.Revision >= 0
|
||||
&& !string.IsNullOrWhiteSpace(e.Quote) && e.Quote.Length <= ContextIntentText.MaximumPassageLength)
|
||||
&& evidence.Where(e => e.Id.HasValue).Select(e => e.Id).Distinct().Count() == evidence.Count(e => e.Id.HasValue);
|
||||
|
||||
internal static bool ValidBackupEvidence(string? value)
|
||||
{
|
||||
if (value is null) return true;
|
||||
try
|
||||
{
|
||||
var evidence = JsonSerializer.Deserialize<IntentChecklistEvidence[]>(value, Json);
|
||||
return evidence is not null && ValidEvidence(evidence) && evidence.All(e => e.Id.HasValue);
|
||||
}
|
||||
catch (JsonException) { return false; }
|
||||
}
|
||||
|
||||
public async Task<IntentChecklistFrame> Load(int bookId, int chapterId, int? sceneId, IntentChecklistSave? save = null)
|
||||
{
|
||||
ContextIntentPalette.Validate(new(bookId, chapterId, sceneId));
|
||||
var author = user.UserId ?? throw new UnauthorizedAccessException();
|
||||
string? items = null;
|
||||
long? manuscriptRevision = null;
|
||||
if (save is not null)
|
||||
{
|
||||
if (save.Version is not { Length: 64 } || !save.Version.All(Uri.IsHexDigit) ||
|
||||
save.Items is null || save.Items.Length > ContextIntentText.MaximumItems ||
|
||||
save.Items.Any(item => item is null || item.Id <= 0 ||
|
||||
string.IsNullOrWhiteSpace(item.Text) || item.Text.Length > ContextIntentText.MaximumItemLength ||
|
||||
item.Notes?.Length > ContextIntentDraft.MaximumNotesLength || !IntentChecklistLinks.Valid(item.Links)
|
||||
|| !ValidEvidence(item.Evidence)))
|
||||
throw new ArgumentException("Review the checklist items and try again.");
|
||||
|
||||
var incoming = save.Items.Select(item => item with { Text = item.Text.Trim() }).ToArray();
|
||||
if (incoming.Any(i => i.Evidence is { Length: > 0 }))
|
||||
{
|
||||
var saved = await Load(bookId, chapterId, sceneId);
|
||||
if (!saved.CanEdit) throw new UnauthorizedAccessException();
|
||||
if (saved.Version != save.Version) throw new InvalidOperationException("The saved checklist changed. Your draft is still here.");
|
||||
var existing = saved.Items.ToDictionary(i => i.Id!.Value);
|
||||
var manuscript = incoming.Any(i => i.Evidence?.Any(e => !e.Id.HasValue) == true)
|
||||
? await manuscripts.Get(author, bookId) : null;
|
||||
var paragraphs = manuscript is not null && manuscript.ProjectId == saved.ProjectID
|
||||
? Scoped(manuscript, chapterId, sceneId).ToDictionary(p => p.Occurrence.Id, p => p.Occurrence.Text)
|
||||
: [];
|
||||
|
||||
for (var i = 0; i < incoming.Length; i++)
|
||||
{
|
||||
var item = incoming[i];
|
||||
if (item.Evidence is null) continue;
|
||||
var original = item.Id.HasValue ? existing.GetValueOrDefault(item.Id.Value)?.Evidence : null;
|
||||
var evidence = new List<IntentChecklistEvidence>();
|
||||
foreach (var entry in item.Evidence)
|
||||
{
|
||||
if (entry.Id.HasValue)
|
||||
{
|
||||
evidence.Add(original?.SingleOrDefault(e => e.Id == entry.Id)
|
||||
?? throw new UnauthorizedAccessException());
|
||||
continue;
|
||||
}
|
||||
if (manuscript is null || manuscript.Revision != entry.Revision ||
|
||||
!paragraphs.TryGetValue(entry.Paragraph, out var text) ||
|
||||
!text.Contains(entry.Quote, StringComparison.Ordinal))
|
||||
throw new ArgumentException("Choose an exact passage from the current accepted manuscript in this scope.");
|
||||
manuscriptRevision = manuscript.Revision;
|
||||
evidence.Add(entry with { Id = Guid.NewGuid() });
|
||||
}
|
||||
incoming[i] = item with { Evidence = evidence.ToArray() };
|
||||
}
|
||||
}
|
||||
items = JsonSerializer.Serialize(incoming, Json);
|
||||
}
|
||||
|
||||
using var db = connections.CreateConnection();
|
||||
var state = await db.QuerySingleAsync<State>("dbo.ContextIntent_Checklist",
|
||||
new { UserID = author, BookID = bookId, ChapterID = chapterId, SceneID = sceneId,
|
||||
ExpectedVersion = save?.Version, Items = items, ManuscriptRevision = manuscriptRevision },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
|
||||
if (save is not null)
|
||||
await notifications.Invalidate(author, bookId, chapterId, sceneId, state.ProjectID, kind: "intent");
|
||||
|
||||
return new(state.ProjectID, state.CanEdit, state.Version, state.Objective, state.Outcome,
|
||||
JsonSerializer.Deserialize<IntentChecklistItem[]>(state.ItemsJson, Json)!);
|
||||
}
|
||||
}
|
||||
@ -1434,7 +1434,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
foreach (var item in backup.Data.SceneChecklistItems)
|
||||
{
|
||||
item.SceneChecklistItemID = NewId("SceneChecklistItems", item.SceneChecklistItemID);
|
||||
item.SceneID = ExistingOrNew("Scenes", item.SceneID);
|
||||
item.SceneID = ExistingOrNewNullable("Scenes", item.SceneID);
|
||||
item.ChapterID = ExistingOrNewNullable("Chapters", item.ChapterID);
|
||||
}
|
||||
|
||||
foreach (var attachment in backup.Data.SceneAttachments)
|
||||
@ -1947,6 +1948,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
}
|
||||
foreach (var preset in backup.Data.TimelineViewPresets)
|
||||
ProjectBackupTimelineState.Remap(preset,projectId,ExistingOrNewNullable);
|
||||
foreach (var item in backup.Data.SceneChecklistItems)
|
||||
item.IntentLinksJson = Context.IntentChecklistLinks.Remap(item.IntentLinksJson, maps);
|
||||
BookBackupGraph.RemapState(backup,maps,importingUserId);
|
||||
return maps;
|
||||
}
|
||||
|
||||
@ -96,7 +96,7 @@ internal static class ProjectBackupGraphValidation
|
||||
new("SceneAssetLocations", "SceneAssetLocationID", new Link("LocationID", "Locations", "LocationID"), new Link("SceneID", "Scenes", "SceneID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID")),
|
||||
new("SceneAttachments", "SceneAttachmentID", new Link("SceneID", "Scenes", "SceneID")),
|
||||
new("SceneCharacters", "SceneCharacterID", new Link("CharacterID", "Characters", "CharacterID"), new Link("EntryLocationID", "Locations", "LocationID"), new Link("ExitLocationID", "Locations", "LocationID"), new Link("LocationID", "Locations", "LocationID"), new Link("SceneID", "Scenes", "SceneID")),
|
||||
new("SceneChecklistItems", "SceneChecklistItemID", new Link("SceneID", "Scenes", "SceneID")),
|
||||
new("SceneChecklistItems", "SceneChecklistItemID", new Link("SceneID", "Scenes", "SceneID"), new Link("ChapterID", "Chapters", "ChapterID")),
|
||||
new("SceneDependencies", "SceneDependencyID", new Link("SourceSceneID", "Scenes", "SceneID"), new Link("TargetSceneID", "Scenes", "SceneID")),
|
||||
new("SceneFloorPlanOccupancy", "SceneFloorPlanOccupancyID", new Link("CharacterID", "Characters", "CharacterID"), new Link("FloorPlanFloorID", "FloorPlanFloors", "FloorPlanFloorID"), new Link("FloorPlanID", "FloorPlans", "FloorPlanID"), new Link("LocationID", "Locations", "LocationID"), new Link("SceneID", "Scenes", "SceneID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID")),
|
||||
new("SceneManuscriptSources", null, new Link("BookID", "Books", "BookID"), new Link("ChapterID", "Chapters", "ChapterID"), new Link("ProjectID", "Project", "ProjectID"), new Link("SceneID", "Scenes", "SceneID")),
|
||||
@ -141,6 +141,12 @@ internal static class ProjectBackupGraphValidation
|
||||
return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record.";
|
||||
}
|
||||
}
|
||||
if (backup.Data.SceneChecklistItems.Any(item => item.SceneID.HasValue == item.ChapterID.HasValue))
|
||||
return "Project backup contains a checklist item without exactly one chapter or scene.";
|
||||
if (backup.Data.SceneChecklistItems.Any(item => !Context.IntentChecklistLinks.IsValidBackup(item.IntentLinksJson)))
|
||||
return "Project backup contains invalid Intent checklist links.";
|
||||
if (backup.Data.SceneChecklistItems.Any(item => !Context.ContextIntentChecklist.ValidBackupEvidence(item.IntentEvidenceJson)))
|
||||
return "Project backup contains invalid Intent checklist evidence.";
|
||||
if (backup.Data.SceneThreads.Select(x => (x.SceneID, x.PlotThreadID)).Distinct().Count() != backup.Data.SceneThreads.Count)
|
||||
return "Project backup contains duplicate scene/thread associations.";
|
||||
if (backup.Data.SceneThreads.Count > 0)
|
||||
|
||||
@ -64,7 +64,7 @@ internal static partial class ProjectBackupStoredFieldContract
|
||||
["SceneAttachments"]=("SceneAttachmentID,SceneID,SceneAttachmentTypeID,Title,FilePath,ExternalUrl,Notes,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","FilePath,ExternalUrl,Notes,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
|
||||
["SceneCharacterSuggestions"]=("SceneCharacterSuggestionID,SceneID,CharacterID,SuggestionSource,DetectedUtc,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc","Reason,ReviewedByUserID,ReviewedUtc"),
|
||||
["SceneCharacters"]=("SceneCharacterID,SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID,LocationID,EntryLocationID,ExitLocationID,AppearanceNotes,OutfitDescription,PhysicalCondition,EmotionalState,KnowledgeNotes,CreatedDate,UpdatedDate,MatchSource,MatchedText,OccurrenceCount,FirstOccurrenceIndex","RoleInSceneTypeID,PresenceTypeID,LocationID,EntryLocationID,ExitLocationID,AppearanceNotes,OutfitDescription,PhysicalCondition,EmotionalState,KnowledgeNotes,MatchSource,MatchedText,OccurrenceCount,FirstOccurrenceIndex"),
|
||||
["SceneChecklistItems"]=("SceneChecklistItemID,SceneID,ItemText,IsCompleted,SortOrder,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","SortOrder,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
|
||||
["SceneChecklistItems"]=("SceneChecklistItemID,SceneID,ChapterID,ItemText,IsCompleted,IsChanged,AuthorNotes,IntentLinksJson,IntentEvidenceJson,SortOrder,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","SceneID,ChapterID,AuthorNotes,IntentLinksJson,IntentEvidenceJson,IsChanged,SortOrder,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
|
||||
["SceneDependencies"]=("SceneDependencyID,SourceSceneID,TargetSceneID,SceneDependencyTypeID,Description,CreatedDate,UpdatedDate,IsArchived,ProjectID,IsHardDependency","Description,ProjectID"),
|
||||
["SceneFloorPlanOccupancy"]=("SceneFloorPlanOccupancyID,SceneID,FloorPlanID,FloorPlanFloorID,CharacterID,StoryAssetID,LocationID,CreatedDate,ModifiedDate","FloorPlanFloorID,CharacterID,StoryAssetID,ModifiedDate"),
|
||||
["SceneLocationSuggestions"]=("SceneLocationSuggestionID,SceneID,LocationID,SuggestionSource,DetectedUtc,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc","Reason,ReviewedByUserID,ReviewedUtc"),
|
||||
|
||||
209
PlotLine/Sql/346_ContextIntentChecklist.sql
Normal file
209
PlotLine/Sql/346_ContextIntentChecklist.sql
Normal file
@ -0,0 +1,209 @@
|
||||
IF COL_LENGTH(N'dbo.SceneChecklistItems', N'ChapterID') IS NULL
|
||||
BEGIN
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRANSACTION;
|
||||
DROP INDEX IF EXISTS IX_SceneChecklistItems_SceneID ON dbo.SceneChecklistItems;
|
||||
ALTER TABLE dbo.SceneChecklistItems DROP CONSTRAINT FK_SceneChecklistItems_Scenes;
|
||||
ALTER TABLE dbo.SceneChecklistItems ALTER COLUMN SceneID int NULL;
|
||||
ALTER TABLE dbo.SceneChecklistItems ADD
|
||||
ChapterID int NULL,
|
||||
IsChanged bit NULL CONSTRAINT DF_SceneChecklistItems_IsChanged DEFAULT (0),
|
||||
AuthorNotes nvarchar(4000) NULL,
|
||||
IntentLinksJson nvarchar(max) NULL,
|
||||
IntentEvidenceJson nvarchar(max) NULL;
|
||||
ALTER TABLE dbo.SceneChecklistItems ADD CONSTRAINT FK_SceneChecklistItems_Scenes
|
||||
FOREIGN KEY (SceneID) REFERENCES dbo.Scenes(SceneID);
|
||||
CREATE INDEX IX_SceneChecklistItems_SceneID ON dbo.SceneChecklistItems(SceneID, IsCompleted, SortOrder);
|
||||
COMMIT TRANSACTION;
|
||||
END;
|
||||
GO
|
||||
IF OBJECT_ID(N'dbo.FK_SceneChecklistItems_Chapters', N'F') IS NULL
|
||||
ALTER TABLE dbo.SceneChecklistItems ADD CONSTRAINT FK_SceneChecklistItems_Chapters
|
||||
FOREIGN KEY (ChapterID) REFERENCES dbo.Chapters(ChapterID) ON DELETE CASCADE;
|
||||
IF OBJECT_ID(N'dbo.CK_SceneChecklistItems_Scope', N'C') IS NULL
|
||||
ALTER TABLE dbo.SceneChecklistItems ADD CONSTRAINT CK_SceneChecklistItems_Scope CHECK
|
||||
((SceneID IS NULL AND ChapterID IS NOT NULL) OR (SceneID IS NOT NULL AND ChapterID IS NULL));
|
||||
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID(N'dbo.SceneChecklistItems') AND name=N'IX_SceneChecklistItems_IntentScope')
|
||||
CREATE INDEX IX_SceneChecklistItems_IntentScope ON dbo.SceneChecklistItems(ChapterID, SceneID, SceneChecklistItemID);
|
||||
GO
|
||||
|
||||
CREATE OR ALTER FUNCTION dbo.ContextIntent_LinkTargets(@project int, @BookID int)
|
||||
RETURNS TABLE
|
||||
AS
|
||||
RETURN
|
||||
(
|
||||
SELECT CONVERT(nvarchar(80), CONCAT(N'character:',CharacterID)) AS EntityKey, CharacterName AS Name FROM dbo.Characters WHERE ProjectID=@project AND IsArchived=0
|
||||
UNION ALL SELECT CONCAT(N'location:',LocationID),LocationName FROM dbo.Locations WHERE ProjectID=@project AND IsArchived=0
|
||||
UNION ALL SELECT CONCAT(N'asset:',StoryAssetID),AssetName FROM dbo.StoryAssets WHERE ProjectID=@project AND IsArchived=0
|
||||
UNION ALL SELECT CONCAT(N'plotline:',PlotLineID),PlotLineName FROM dbo.PlotLines WHERE ProjectID=@project AND IsArchived=0 AND (BookID IS NULL OR BookID=@BookID)
|
||||
UNION ALL SELECT CONCAT(N'thread:',t.PlotThreadID),t.ThreadTitle FROM dbo.PlotThreads t
|
||||
JOIN dbo.PlotLines l ON l.PlotLineID=t.PlotLineID AND l.ProjectID=@project AND l.IsArchived=0 AND (l.BookID IS NULL OR l.BookID=@BookID) WHERE t.IsArchived=0
|
||||
UNION ALL SELECT CONCAT(N'candidate:',c.ReviewCandidateID),c.DisplayName
|
||||
FROM dbo.StoryIntelligenceReviewCandidates c
|
||||
JOIN dbo.StoryIntelligenceReviewCandidateGenerations g ON g.ReviewCandidateGenerationID=c.ReviewCandidateGenerationID
|
||||
WHERE c.ProjectID=@project AND c.BookID=@BookID AND g.ProjectID=@project AND g.BookID=@BookID
|
||||
AND g.IsCurrent=1 AND g.Status=N'Ready' AND c.Module=g.Module
|
||||
AND c.Module IN(N'Characters',N'Locations',N'Assets') AND c.DecisionStatus=N'Pending'
|
||||
UNION ALL SELECT CONCAT(N'narrative-candidate:',NarrativeCandidateID),ProposedTitle
|
||||
FROM dbo.StoryIntelligenceNarrativeCandidates
|
||||
WHERE ProjectID=@project AND BookID=@BookID AND Status=N'Pending' AND CandidateType IN(N'PlotLine',N'Thread')
|
||||
);
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.ContextIntent_Checklist
|
||||
@UserID int,
|
||||
@BookID int,
|
||||
@ChapterID int,
|
||||
@SceneID int = NULL,
|
||||
@ExpectedVersion varchar(64) = NULL,
|
||||
@Items nvarchar(max) = NULL,
|
||||
@ManuscriptRevision bigint = NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
DECLARE @ProjectID int, @CanEdit bit, @Rows nvarchar(max), @Version varchar(64);
|
||||
SELECT @ProjectID = b.ProjectID,
|
||||
@CanEdit = CASE WHEN a.AccessRole IN (N'Owner', N'Collaborator') THEN 1 ELSE 0 END
|
||||
FROM dbo.Chapters c WITH (HOLDLOCK)
|
||||
JOIN dbo.Books b WITH (HOLDLOCK) ON b.BookID = c.BookID AND b.IsArchived = 0
|
||||
JOIN dbo.Projects p WITH (HOLDLOCK) ON p.ProjectID = b.ProjectID AND p.IsArchived = 0
|
||||
JOIN dbo.ProjectUserAccess a WITH (HOLDLOCK) ON a.ProjectID = p.ProjectID AND a.UserID = @UserID AND a.IsActive = 1
|
||||
WHERE c.ChapterID = @ChapterID AND c.BookID = @BookID AND c.IsArchived = 0;
|
||||
|
||||
IF @ProjectID IS NULL OR (@SceneID IS NOT NULL AND NOT EXISTS
|
||||
(SELECT 1 FROM dbo.Scenes WITH (HOLDLOCK) WHERE SceneID = @SceneID AND ChapterID = @ChapterID AND IsArchived = 0))
|
||||
THROW 51010, 'This Intent scope is unavailable.', 1;
|
||||
|
||||
DECLARE @ScopeChapterID int = CASE WHEN @SceneID IS NULL THEN @ChapterID END;
|
||||
DECLARE @Scope table (ID int PRIMARY KEY);
|
||||
INSERT @Scope
|
||||
SELECT SceneChecklistItemID FROM dbo.SceneChecklistItems WITH (UPDLOCK, HOLDLOCK)
|
||||
WHERE (ChapterID = @ScopeChapterID AND SceneID IS NULL)
|
||||
OR (ChapterID IS NULL AND SceneID = @SceneID);
|
||||
|
||||
SET @Rows = (SELECT i.SceneChecklistItemID AS id, i.ItemText AS text, i.IsCompleted AS completed,
|
||||
COALESCE(i.IsChanged, CONVERT(bit, 0)) AS changed, i.AuthorNotes AS notes, JSON_QUERY(COALESCE(i.IntentLinksJson, N'[]')) AS links, JSON_QUERY(COALESCE(i.IntentEvidenceJson, N'[]')) AS evidence, i.UpdatedDate AS updated, i.SortOrder AS sortOrder
|
||||
FROM dbo.SceneChecklistItems i JOIN @Scope s ON s.ID = i.SceneChecklistItemID
|
||||
ORDER BY ISNULL(i.SortOrder, 9999), i.SceneChecklistItemID FOR JSON PATH, INCLUDE_NULL_VALUES);
|
||||
SET @Version = CONVERT(varchar(64), HASHBYTES('SHA2_256', COALESCE(@Rows, N'[]')), 2);
|
||||
|
||||
IF @Items IS NOT NULL
|
||||
BEGIN
|
||||
IF @CanEdit = 0 THROW 51010, 'Editing this Intent is unavailable.', 1;
|
||||
IF @ExpectedVersion IS NULL OR @ExpectedVersion <> @Version
|
||||
THROW 51011, 'This checklist has changed.', 1;
|
||||
IF @ManuscriptRevision IS NOT NULL AND NOT EXISTS
|
||||
(SELECT 1 FROM dbo.BookParagraphManuscripts WITH (HOLDLOCK)
|
||||
WHERE BookID = @BookID AND Revision = @ManuscriptRevision)
|
||||
THROW 51011, 'The accepted manuscript changed.', 1;
|
||||
IF ISJSON(@Items, ARRAY) <> 1 THROW 51012, 'Invalid checklist.', 1;
|
||||
|
||||
DECLARE @Incoming table (Position int PRIMARY KEY, ID int NULL, ItemText nvarchar(max),
|
||||
Completed bit, Changed bit, Notes nvarchar(max), Links nvarchar(max), SavedLinks nvarchar(max), Evidence nvarchar(max));
|
||||
INSERT @Incoming
|
||||
SELECT CONVERT(int, j.[key]), i.ID, i.ItemText, i.Completed, i.Changed, i.Notes, i.Links, NULL, i.Evidence
|
||||
FROM OPENJSON(@Items) j CROSS APPLY OPENJSON(j.value) WITH
|
||||
(ID int '$.id', ItemText nvarchar(max) '$.text', Completed bit '$.completed',
|
||||
Changed bit '$.changed', Notes nvarchar(max) '$.notes', Links nvarchar(max) '$.links' AS JSON, Evidence nvarchar(max) '$.evidence' AS JSON) i;
|
||||
|
||||
IF (SELECT COUNT(*) FROM @Incoming) > 200 OR EXISTS
|
||||
(SELECT 1 FROM @Incoming WHERE ItemText IS NULL OR LEN(ItemText) = 0
|
||||
OR DATALENGTH(ItemText) > 600 OR DATALENGTH(Notes) > 8000 OR Completed IS NULL OR Changed IS NULL)
|
||||
OR EXISTS (SELECT ID FROM @Incoming WHERE ID IS NOT NULL GROUP BY ID HAVING COUNT(*) > 1)
|
||||
THROW 51012, 'Invalid checklist.', 1;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM @Incoming i WHERE i.ID IS NOT NULL AND NOT EXISTS (SELECT 1 FROM @Scope s WHERE s.ID = i.ID))
|
||||
THROW 51010, 'Checklist item is outside this scope.', 1;
|
||||
|
||||
DECLARE @Links table (Position int NOT NULL, EntityKey nvarchar(80) NOT NULL, Covered bit NOT NULL,
|
||||
Name nvarchar(450) NULL);
|
||||
IF EXISTS (SELECT 1 FROM @Incoming WHERE Links IS NOT NULL AND ISJSON(Links, ARRAY) <> 1)
|
||||
THROW 51012, 'Invalid checklist links.', 1;
|
||||
|
||||
INSERT @Links
|
||||
SELECT n.Position, link.EntityKey, link.Covered,
|
||||
COALESCE(entity.Name, historical.Name)
|
||||
FROM @Incoming n
|
||||
CROSS APPLY OPENJSON(n.Links) WITH
|
||||
(EntityKey nvarchar(80) '$.key', Covered bit '$.covered') link
|
||||
LEFT JOIN dbo.ContextIntent_LinkTargets(@ProjectID, @BookID) entity
|
||||
ON entity.EntityKey = link.EntityKey
|
||||
LEFT JOIN dbo.SceneChecklistItems i ON i.SceneChecklistItemID = n.ID
|
||||
OUTER APPLY (SELECT previous.Name FROM OPENJSON(i.IntentLinksJson) WITH
|
||||
(EntityKey nvarchar(80) '$.key', Name nvarchar(450) '$.name') previous
|
||||
WHERE previous.EntityKey = link.EntityKey) historical;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM @Links WHERE Name IS NULL)
|
||||
THROW 51010, 'A Story Element is unavailable in this scope.', 1;
|
||||
IF EXISTS (SELECT Position FROM @Links GROUP BY Position HAVING COUNT(*) > 40)
|
||||
OR EXISTS (SELECT Position, EntityKey FROM @Links GROUP BY Position, EntityKey HAVING COUNT(*) > 1)
|
||||
THROW 51012, 'Invalid checklist links.', 1;
|
||||
|
||||
UPDATE n SET SavedLinks = (
|
||||
SELECT l.EntityKey AS [key], l.Name AS name, l.Covered AS covered FROM @Links l
|
||||
WHERE l.Position = n.Position ORDER BY l.EntityKey FOR JSON PATH)
|
||||
FROM @Incoming n;
|
||||
|
||||
DELETE i FROM dbo.SceneChecklistItems i JOIN @Scope s ON s.ID = i.SceneChecklistItemID
|
||||
WHERE NOT EXISTS (SELECT 1 FROM @Incoming n WHERE n.ID = s.ID);
|
||||
|
||||
UPDATE i SET ItemText = n.ItemText, IsCompleted = n.Completed, IsChanged = n.Changed,
|
||||
AuthorNotes = n.Notes, IntentLinksJson = n.SavedLinks, IntentEvidenceJson = n.Evidence, SortOrder = n.Position, UpdatedDate = SYSUTCDATETIME()
|
||||
FROM dbo.SceneChecklistItems i JOIN @Incoming n ON n.ID = i.SceneChecklistItemID;
|
||||
|
||||
INSERT dbo.SceneChecklistItems (ChapterID, SceneID, ItemText, IsCompleted, IsChanged, AuthorNotes, IntentLinksJson, IntentEvidenceJson, SortOrder)
|
||||
SELECT @ScopeChapterID, @SceneID, ItemText, Completed, Changed, Notes, SavedLinks, Evidence, Position
|
||||
FROM @Incoming WHERE ID IS NULL;
|
||||
|
||||
SET @Rows = (SELECT i.SceneChecklistItemID AS id, i.ItemText AS text, i.IsCompleted AS completed,
|
||||
COALESCE(i.IsChanged, CONVERT(bit, 0)) AS changed, i.AuthorNotes AS notes, JSON_QUERY(COALESCE(i.IntentLinksJson, N'[]')) AS links, JSON_QUERY(COALESCE(i.IntentEvidenceJson, N'[]')) AS evidence, i.UpdatedDate AS updated, i.SortOrder AS sortOrder
|
||||
FROM dbo.SceneChecklistItems i
|
||||
WHERE (ChapterID = @ScopeChapterID AND SceneID IS NULL) OR (ChapterID IS NULL AND SceneID = @SceneID)
|
||||
ORDER BY ISNULL(i.SortOrder, 9999), i.SceneChecklistItemID FOR JSON PATH, INCLUDE_NULL_VALUES);
|
||||
SET @Version = CONVERT(varchar(64), HASHBYTES('SHA2_256', COALESCE(@Rows, N'[]')), 2);
|
||||
END;
|
||||
|
||||
DECLARE @Objective nvarchar(max), @Outcome nvarchar(max);
|
||||
IF @SceneID IS NULL
|
||||
SELECT @Objective = GoalSummary FROM dbo.ChapterGoals WHERE ChapterID = @ChapterID;
|
||||
ELSE
|
||||
SELECT @Objective = ScenePurposeNotes, @Outcome = SceneOutcomeNotes FROM dbo.Scenes WHERE SceneID = @SceneID;
|
||||
|
||||
COMMIT TRANSACTION;
|
||||
SELECT @ProjectID AS ProjectID, @CanEdit AS CanEdit, @Version AS Version,
|
||||
COALESCE(@Rows, N'[]') AS ItemsJson, @Objective AS Objective, @Outcome AS Outcome;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH
|
||||
END;
|
||||
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ContextIntent_MatchingIndex @UserID int, @BookID int, @ChapterID int, @SceneID int = NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
DECLARE @ProjectID int;
|
||||
SELECT @ProjectID = b.ProjectID
|
||||
FROM dbo.Books b
|
||||
JOIN dbo.Projects p ON p.ProjectID = b.ProjectID AND p.IsArchived = 0
|
||||
JOIN dbo.ProjectUserAccess a ON a.ProjectID = b.ProjectID AND a.UserID = @UserID AND a.IsActive = 1
|
||||
JOIN dbo.Chapters c ON c.BookID = b.BookID AND c.ChapterID = @ChapterID AND c.IsArchived = 0
|
||||
WHERE b.BookID = @BookID AND b.IsArchived = 0;
|
||||
IF @ProjectID IS NULL OR (@SceneID IS NOT NULL AND NOT EXISTS
|
||||
(SELECT 1 FROM dbo.Scenes WHERE SceneID = @SceneID AND ChapterID = @ChapterID AND IsArchived = 0))
|
||||
THROW 51010, 'This Intent scope is unavailable.', 1;
|
||||
|
||||
SELECT EntityKey, Name INTO #Candidates FROM dbo.ContextIntent_LinkTargets(@ProjectID, @BookID);
|
||||
SELECT EntityKey, Name FROM #Candidates;
|
||||
SELECT EntityKey, Alias FROM
|
||||
(
|
||||
SELECT e.EntityKey, a.Alias FROM dbo.CharacterAliases a JOIN #Candidates e ON e.EntityKey = CONCAT(N'character:', a.CharacterID)
|
||||
UNION ALL SELECT e.EntityKey, a.Alias FROM dbo.LocationAliases a JOIN #Candidates e ON e.EntityKey = CONCAT(N'location:', a.LocationID)
|
||||
UNION ALL SELECT e.EntityKey, a.Alias FROM dbo.AssetAliases a JOIN #Candidates e ON e.EntityKey = CONCAT(N'asset:', a.StoryAssetID)
|
||||
) aliases;
|
||||
END;
|
||||
31
PlotLine/Sql/347_ContextIntentChecklistBackup.sql
Normal file
31
PlotLine/Sql/347_ContextIntentChecklistBackup.sql
Normal file
@ -0,0 +1,31 @@
|
||||
-- Keep the current export procedure and every unrelated result set intact.
|
||||
DECLARE @definition nvarchar(max) = REPLACE(OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectBackup_Export')), NCHAR(13), N'');
|
||||
IF @definition IS NULL THROW 51000, 'Missing canonical project export.', 1;
|
||||
IF CHARINDEX(N'sci.IntentEvidenceJson', @definition) = 0
|
||||
BEGIN
|
||||
DECLARE @previous nvarchar(max) = N' SELECT sci.SceneChecklistItemID, sci.SceneID, sci.ItemText, sci.IsCompleted, sci.SortOrder,
|
||||
sci.CreatedDate, sci.UpdatedDate,
|
||||
sci.CreatedByUserID, sci.ModifiedByUserID, sci.CreatedDateUTC, sci.ModifiedDateUTC
|
||||
FROM dbo.SceneChecklistItems sci
|
||||
INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID
|
||||
INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID
|
||||
INNER JOIN dbo.Books b ON b.BookID = c.BookID
|
||||
WHERE b.ProjectID = @ProjectID
|
||||
ORDER BY sci.SceneID, sci.SortOrder, sci.SceneChecklistItemID;';
|
||||
SET @previous = REPLACE(@previous, NCHAR(13), N'');
|
||||
DECLARE @start int = CHARINDEX(@previous, @definition);
|
||||
IF @start = 0 OR CHARINDEX(@previous, @definition, @start + 1) <> 0
|
||||
THROW 51000, 'Unexpected checklist export projection.', 1;
|
||||
SET @definition = STUFF(@definition, @start, LEN(@previous), N' SELECT sci.SceneChecklistItemID, sci.SceneID, sci.ChapterID, sci.ItemText, sci.IsCompleted,
|
||||
ISNULL(sci.IsChanged, CONVERT(bit, 0)) AS IsChanged, sci.AuthorNotes, sci.IntentLinksJson, sci.IntentEvidenceJson,
|
||||
sci.SortOrder, sci.CreatedDate, sci.UpdatedDate,
|
||||
sci.CreatedByUserID, sci.ModifiedByUserID, sci.CreatedDateUTC, sci.ModifiedDateUTC
|
||||
FROM dbo.SceneChecklistItems sci
|
||||
LEFT JOIN dbo.Scenes s ON s.SceneID = sci.SceneID
|
||||
INNER JOIN dbo.Chapters c ON c.ChapterID = COALESCE(s.ChapterID, sci.ChapterID)
|
||||
INNER JOIN dbo.Books b ON b.BookID = c.BookID
|
||||
WHERE b.ProjectID = @ProjectID
|
||||
ORDER BY c.ChapterID, sci.SceneID, sci.SortOrder, sci.SceneChecklistItemID;');
|
||||
SET @definition = STUFF(@definition, 1, CHARINDEX(N'PROCEDURE', @definition) - 1, N'CREATE OR ALTER ');
|
||||
EXEC sys.sp_executesql @definition;
|
||||
END;
|
||||
@ -32,6 +32,7 @@
|
||||
@if(Model.Destination=="Review"){<link rel="stylesheet" href="~/css/writer-review-layout.css" asp-append-version="true" /><script src="~/js/writer-review-layout.js" asp-append-version="true"></script><script src="~/js/manuscript-reader.js" asp-append-version="true"></script><script src="~/js/review-authoring.js" asp-append-version="true"></script><script src="~/js/writer-review.js" asp-append-version="true"></script><script src="~/js/narrative-focus-review.js" asp-append-version="true"></script><script src="~/js/writer-work.js" asp-append-version="true"></script>}
|
||||
@if(Model.Destination is "Write" or "Plan"){
|
||||
|
||||
<script src="~/js/context-intent-checklist.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-intent-palette.js" asp-append-version="true"></script>
|
||||
<script src="~/js/writer-authoring.js" asp-append-version="true"></script>
|
||||
<script src="~/js/writer-focus.js" asp-append-version="true"></script>
|
||||
|
||||
@ -46,6 +46,8 @@
|
||||
}
|
||||
<p class="writer3-caption">Saved records only; no manuscript analysis or inferred story facts. Open Context for the full reference categories and recorded metrics.</p>
|
||||
</section>
|
||||
<partial name="~/Views/Writing/_ContextIntentChecklist.cshtml"
|
||||
model="@(new PlotLine.Services.Context.IntentPaletteScope(0, Model.BookID, Model.ChapterID, Model.SceneID))" />
|
||||
<partial name="~/Views/Writing/_ContextIntentPalette.cshtml"
|
||||
model="@(new PlotLine.Services.Context.IntentPaletteScope(0, Model.BookID, Model.ChapterID, Model.SceneID))" />
|
||||
</template>
|
||||
|
||||
@ -86,6 +86,7 @@
|
||||
<script src="~/js/context-assets.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-calendar-model.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-calendar.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-intent-checklist.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-intent-palette.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-workspace.js" asp-append-version="true"></script>
|
||||
<script src="~/js/context-environment.js" asp-append-version="true"></script>
|
||||
|
||||
37
PlotLine/Views/Writing/_ContextIntentChecklist.cshtml
Normal file
37
PlotLine/Views/Writing/_ContextIntentChecklist.cshtml
Normal file
@ -0,0 +1,37 @@
|
||||
@model PlotLine.Services.Context.IntentPaletteScope
|
||||
<section class="border rounded p-2 mb-2" data-intent-checklist
|
||||
data-url="@Url.Action("Checklist", "ContextIntent")"
|
||||
data-passages-url="@Url.Action("Passages", "ContextIntent")"
|
||||
data-preview-url="@Url.Action("Preview", "ContextIntent")"
|
||||
data-book-id="@Model.BookID" data-chapter-id="@Model.ChapterID" data-scene-id="@Model.SceneID">
|
||||
@Html.AntiForgeryToken()
|
||||
<h3 class="h6">Intent checklist</h3>
|
||||
<label class="small" data-checklist-scope-label hidden="@(!Model.SceneID.HasValue)">
|
||||
<input type="checkbox" data-checklist-scene /> Scene checklist
|
||||
</label>
|
||||
<p class="small text-body-secondary mb-1" data-checklist-objective hidden></p>
|
||||
<p class="small text-body-secondary mb-1" data-checklist-outcome hidden></p>
|
||||
<p class="small text-body-secondary mb-1" role="status" data-checklist-status></p>
|
||||
<ol class="list-group list-group-numbered mb-2" data-checklist-items></ol>
|
||||
<div data-checklist-controls hidden>
|
||||
<div class="d-flex flex-wrap gap-2 mb-2">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" data-checklist-add>Add item</button>
|
||||
<button type="button" class="btn btn-sm btn-primary" data-checklist-save>Save checklist</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" data-checklist-discard>Discard draft</button>
|
||||
</div>
|
||||
<details data-checklist-paste-panel>
|
||||
<summary>Paste a checklist</summary>
|
||||
<label class="d-block mt-2">Checklist text
|
||||
<textarea class="form-control form-control-sm" rows="3" data-checklist-paste></textarea>
|
||||
</label>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary mt-1" data-checklist-preview>Preview</button>
|
||||
<ol class="list-group list-group-numbered mt-1" data-checklist-preview-items></ol>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary mt-1" data-checklist-apply hidden>Add reviewed items</button>
|
||||
</details>
|
||||
</div>
|
||||
<details data-checklist-passages hidden>
|
||||
<summary>Changed Word passages</summary>
|
||||
<p class="small text-body-secondary m-1">Drag a passage onto an item to attach evidence and complete it.</p>
|
||||
<ul class="list-group list-group-flush" data-checklist-passage-list></ul>
|
||||
</details>
|
||||
</section>
|
||||
@ -2,5 +2,6 @@
|
||||
@{ Layout = null; }
|
||||
<div data-context-tab-fragment data-context-intent data-project-id="@Model.ProjectID"
|
||||
data-book-id="@Model.BookID" data-chapter-id="@Model.ChapterID" data-scene-id="@Model.SceneID">
|
||||
<partial name="~/Views/Writing/_ContextIntentChecklist.cshtml" model="Model" />
|
||||
<partial name="~/Views/Writing/_ContextIntentPalette.cshtml" model="Model" />
|
||||
</div>
|
||||
|
||||
434
PlotLine/wwwroot/js/context-intent-checklist.js
Normal file
434
PlotLine/wwwroot/js/context-intent-checklist.js
Normal file
@ -0,0 +1,434 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
const instances = new WeakMap();
|
||||
function mount(root) {
|
||||
if (!root || instances.has(root)) return;
|
||||
const get = name => root.querySelector('[data-checklist-' + name + ']');
|
||||
const scene = get('scene');
|
||||
const status = get('status');
|
||||
const rows = get('items');
|
||||
const controls = get('controls');
|
||||
const previewRows = get('preview-items');
|
||||
const paste = get('paste');
|
||||
const events = new AbortController();
|
||||
const listen = (node, event, callback) => node.addEventListener(event, callback, { signal: events.signal });
|
||||
let frame, items = [], prepared = [], busy = false, dirty = false, dragged;
|
||||
let pending, readingPassages, selectedElement, selectedPassage;
|
||||
const passageType = "application/x-plotdirector-intent-passage";
|
||||
const entityType = "application/x-plotdirector-intent-element";
|
||||
|
||||
function updateControls() {
|
||||
scene.disabled = dirty || busy;
|
||||
get('save').disabled = !dirty || busy;
|
||||
get('discard').disabled = !dirty || busy;
|
||||
rows.inert = busy;
|
||||
get('paste-panel').inert = busy;
|
||||
get('add').disabled = busy;
|
||||
root.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { dirty, busy } }));
|
||||
}
|
||||
|
||||
function changed() {
|
||||
dirty = true;
|
||||
status.textContent = 'Unsaved changes';
|
||||
updateControls();
|
||||
}
|
||||
|
||||
function button(label, action) {
|
||||
const control = document.createElement('button');
|
||||
control.type = 'button';
|
||||
control.className = 'btn btn-sm btn-outline-secondary';
|
||||
control.textContent = label;
|
||||
control.addEventListener('click', action);
|
||||
return control;
|
||||
}
|
||||
|
||||
function field(label, input) {
|
||||
const wrapper = document.createElement('label');
|
||||
wrapper.className = 'd-block my-1';
|
||||
wrapper.append(label + ' ', input);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function move(from, to) {
|
||||
if (from === to || to < 0 || to >= items.length) return;
|
||||
const [item] = items.splice(from, 1);
|
||||
items.splice(to, 0, item);
|
||||
changed();
|
||||
render();
|
||||
rows.children[to].querySelector('button:not(:disabled)')?.focus();
|
||||
}
|
||||
|
||||
function link(item, entity) {
|
||||
if (!entity?.key || !entity.name) return;
|
||||
item.links ||= [];
|
||||
if (item.links.some(link => link.key === entity.key)) {
|
||||
status.textContent = 'That Story Element is already linked.';
|
||||
return;
|
||||
}
|
||||
if (item.links.length >= 40) {
|
||||
status.textContent = 'Keep at most 40 Story Elements per item.';
|
||||
return;
|
||||
}
|
||||
item.links.push({ key: entity.key, name: entity.name, covered: false });
|
||||
changed();
|
||||
render();
|
||||
}
|
||||
|
||||
function attach(item, evidence) {
|
||||
if (!evidence?.paragraph || !evidence.quote || item.evidence?.length >= 20) return;
|
||||
item.evidence ||= [];
|
||||
item.evidence.push({ ...evidence, id: null });
|
||||
item.completed = true;
|
||||
changed();
|
||||
render();
|
||||
rows.children[items.indexOf(item)]?.querySelector('input')?.focus();
|
||||
}
|
||||
|
||||
function render() {
|
||||
rows.replaceChildren(...items.map((item, index) => {
|
||||
const row = document.createElement('li');
|
||||
row.className = 'list-group-item';
|
||||
if (!frame.canEdit) {
|
||||
row.textContent = [item.text, item.completed ? 'Complete' : '', item.changed ? 'Changed' : '', item.notes,
|
||||
...(item.links || []).map(element => element.name + (element.covered ? ' (covered)' : '')),
|
||||
...(item.evidence || []).map(evidence => evidence.quote)]
|
||||
.filter(Boolean).join(' · ');
|
||||
return row;
|
||||
}
|
||||
const text = document.createElement('input');
|
||||
text.className = 'form-control form-control-sm';
|
||||
text.maxLength = 300;
|
||||
text.value = item.text;
|
||||
text.addEventListener('input', () => { item.text = text.value; changed(); });
|
||||
const notes = document.createElement('textarea');
|
||||
notes.className = 'form-control form-control-sm';
|
||||
notes.rows = 2;
|
||||
notes.maxLength = 4000;
|
||||
notes.value = item.notes || '';
|
||||
notes.addEventListener('input', () => { item.notes = notes.value; changed(); });
|
||||
const flags = document.createElement('div');
|
||||
flags.className = 'd-flex flex-wrap gap-2';
|
||||
for (const [key, label] of [['completed', 'Complete'], ['changed', 'Changed']]) {
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.checked = item[key];
|
||||
checkbox.addEventListener('change', () => { item[key] = checkbox.checked; changed(); });
|
||||
flags.append(field(label, checkbox));
|
||||
}
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'd-flex flex-wrap gap-1';
|
||||
const handle = document.createElement('span');
|
||||
handle.className = 'btn btn-sm btn-outline-secondary';
|
||||
handle.textContent = 'Drag';
|
||||
handle.draggable = true;
|
||||
handle.title = 'Drag to reorder, or use the Up and Down buttons';
|
||||
handle.addEventListener('dragstart', event => {
|
||||
dragged = index;
|
||||
event.dataTransfer.setData('text/plain', 'Reorder checklist item');
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
});
|
||||
handle.addEventListener('dragend', () => { dragged = undefined; });
|
||||
row.addEventListener('dragover', event => {
|
||||
if (dragged !== undefined || event.dataTransfer.types.includes(entityType) || event.dataTransfer.types.includes(passageType)) event.preventDefault();
|
||||
});
|
||||
row.addEventListener('drop', event => {
|
||||
if (dragged !== undefined) {
|
||||
event.preventDefault();
|
||||
move(dragged, index);
|
||||
dragged = undefined;
|
||||
} else if (event.dataTransfer.types.includes(passageType)) {
|
||||
event.preventDefault();
|
||||
try { attach(item, JSON.parse(event.dataTransfer.getData(passageType))); }
|
||||
catch { status.textContent = 'That passage could not be attached.'; }
|
||||
} else if (event.dataTransfer.types.includes(entityType)) {
|
||||
event.preventDefault();
|
||||
try { link(item, JSON.parse(event.dataTransfer.getData(entityType))); }
|
||||
catch { status.textContent = 'That Story Element could not be linked.'; }
|
||||
}
|
||||
});
|
||||
const up = button('Up', () => move(index, index - 1));
|
||||
const down = button('Down', () => move(index, index + 1));
|
||||
up.disabled = index === 0;
|
||||
down.disabled = index === items.length - 1;
|
||||
actions.append(handle, up, down, button('Remove', () => {
|
||||
items.splice(index, 1);
|
||||
changed();
|
||||
render();
|
||||
(rows.children[index]?.querySelector('input') || get('add')).focus();
|
||||
}));
|
||||
if (selectedElement) actions.append(button('Link ' + selectedElement.name, () => link(item, selectedElement)));
|
||||
const links = document.createElement('ul');
|
||||
links.className = 'list-unstyled';
|
||||
for (const element of item.links || []) {
|
||||
const entry = document.createElement('li');
|
||||
entry.className = 'd-flex flex-wrap align-items-center gap-2';
|
||||
const covered = document.createElement('input');
|
||||
covered.type = 'checkbox';
|
||||
covered.checked = element.covered;
|
||||
covered.addEventListener('change', () => { element.covered = covered.checked; changed(); });
|
||||
entry.append(field(element.name + ' covered', covered), button('Unlink', () => {
|
||||
item.links = item.links.filter(link => link !== element);
|
||||
changed();
|
||||
render();
|
||||
rows.children[index]?.querySelector('input')?.focus();
|
||||
}));
|
||||
links.append(entry);
|
||||
}
|
||||
const evidenceList = document.createElement('ul');
|
||||
evidenceList.className = 'list-unstyled';
|
||||
for (const evidence of item.evidence || []) {
|
||||
const entry = document.createElement('li');
|
||||
const quote = document.createElement('blockquote');
|
||||
quote.className = 'small mb-1';
|
||||
quote.textContent = evidence.quote;
|
||||
entry.append(quote, button('Remove evidence', () => {
|
||||
item.evidence = item.evidence.filter(value => value !== evidence);
|
||||
changed();
|
||||
render();
|
||||
rows.children[index]?.querySelector('input')?.focus();
|
||||
}));
|
||||
evidenceList.append(entry);
|
||||
}
|
||||
if (selectedPassage) actions.append(button('Attach passage and complete', () => attach(item, selectedPassage)));
|
||||
row.append(field('Item', text), flags, field('Notes', notes), links, evidenceList, actions);
|
||||
return row;
|
||||
}));
|
||||
}
|
||||
|
||||
function accept(next) {
|
||||
frame = next;
|
||||
items = next.items.map(item => ({ ...item }));
|
||||
dirty = false;
|
||||
controls.hidden = !next.canEdit;
|
||||
const objective = get('objective');
|
||||
objective.textContent = next.objective || '';
|
||||
objective.hidden = !next.objective;
|
||||
const outcome = get('outcome');
|
||||
outcome.textContent = next.outcome ? 'Outcome: ' + next.outcome : '';
|
||||
outcome.hidden = !next.outcome;
|
||||
status.textContent = items.length ? '' : 'No checklist items';
|
||||
render();
|
||||
}
|
||||
|
||||
const scope = () => ({
|
||||
bookId: Number(root.dataset.bookId),
|
||||
chapterId: Number(root.dataset.chapterId),
|
||||
sceneId: scene.checked ? Number(root.dataset.sceneId) : null
|
||||
});
|
||||
|
||||
async function request(url, body, signal) {
|
||||
const options = { signal, cache: 'no-store' };
|
||||
if (body !== undefined) Object.assign(options, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
RequestVerificationToken: root.querySelector('[name="__RequestVerificationToken"]').value
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const response = await fetch(url, options);
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok || response.redirected || !data) throw new Error(data?.message || 'The checklist request failed.');
|
||||
return data;
|
||||
}
|
||||
|
||||
async function loadPassages() {
|
||||
readingPassages?.abort();
|
||||
const controller = new AbortController();
|
||||
readingPassages = controller;
|
||||
const url = new URL(root.dataset.passagesUrl, location.origin);
|
||||
for (const [key, value] of Object.entries(scope())) if (value) url.searchParams.set(key, value);
|
||||
const list = get('passage-list');
|
||||
get('passages').hidden = true;
|
||||
selectedPassage = undefined;
|
||||
try {
|
||||
const passages = await request(url, undefined, controller.signal);
|
||||
if (controller.signal.aborted || !root.isConnected) return;
|
||||
list.replaceChildren(...passages.map(passage => {
|
||||
const row = document.createElement('li');
|
||||
row.className = 'list-group-item';
|
||||
const quote = document.createElement('blockquote');
|
||||
quote.className = 'small mb-1';
|
||||
quote.textContent = passage.text;
|
||||
const evidence = () => {
|
||||
const selection = window.getSelection();
|
||||
const selectedText = selection?.anchorNode && selection.focusNode &&
|
||||
quote.contains(selection.anchorNode) && quote.contains(selection.focusNode)
|
||||
? selection.toString() : '';
|
||||
return { paragraph: passage.paragraph, revision: passage.revision, quote: selectedText || passage.text };
|
||||
};
|
||||
const grab = button('Select passage', () => {
|
||||
selectedPassage = evidence();
|
||||
render();
|
||||
status.textContent = 'Choose an item to attach this passage and complete it.';
|
||||
rows.querySelector('input')?.focus();
|
||||
});
|
||||
grab.draggable = true;
|
||||
grab.addEventListener('dragstart', event => {
|
||||
event.dataTransfer.setData(passageType, JSON.stringify(evidence()));
|
||||
event.dataTransfer.effectAllowed = 'link';
|
||||
});
|
||||
row.append(quote, grab);
|
||||
if (passage.matchingLimited) {
|
||||
const notice = document.createElement('p');
|
||||
notice.className = 'small text-body-secondary';
|
||||
notice.textContent = 'This passage exceeds the Story Element matching limit.';
|
||||
row.append(notice);
|
||||
}
|
||||
for (const mention of passage.mentions) {
|
||||
const match = document.createElement('div');
|
||||
match.className = 'small text-body-secondary mt-1';
|
||||
match.textContent = mention.text + ' · ' +
|
||||
mention.elements.map(e => e.name + ' (' + e.key.split(':')[0] + ')').join(', ') +
|
||||
(mention.elements.length > 1 ? ' · Ambiguous' : '');
|
||||
row.append(match);
|
||||
}
|
||||
return row;
|
||||
}));
|
||||
get('passages').hidden = !passages.length;
|
||||
} catch {
|
||||
if (!controller.signal.aborted) get('passages').hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (busy || dirty) return;
|
||||
readingPassages?.abort();
|
||||
get('passages').hidden = true;
|
||||
selectedPassage = undefined;
|
||||
pending?.abort();
|
||||
const controller = new AbortController();
|
||||
pending = controller;
|
||||
const url = new URL(root.dataset.url, location.origin);
|
||||
for (const [key, value] of Object.entries(scope())) if (value) url.searchParams.set(key, value);
|
||||
controls.hidden = true;
|
||||
rows.replaceChildren();
|
||||
get('objective').hidden = true;
|
||||
get('outcome').hidden = true;
|
||||
status.textContent = 'Loading checklist…';
|
||||
try {
|
||||
const next = await request(url, undefined, controller.signal);
|
||||
if (!controller.signal.aborted && root.isConnected) {
|
||||
accept(next);
|
||||
readingPassages?.abort();
|
||||
if (next.canEdit) void loadPassages();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) status.textContent = error.message;
|
||||
} finally {
|
||||
if (!controller.signal.aborted) updateControls();
|
||||
}
|
||||
}
|
||||
|
||||
function append(newItems) {
|
||||
if (items.length + newItems.length > 200) {
|
||||
status.textContent = 'Keep at most 200 items per checklist.';
|
||||
return false;
|
||||
}
|
||||
items.push(...newItems);
|
||||
changed();
|
||||
render();
|
||||
rows.lastElementChild?.querySelector('input')?.focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
function clearPreview() {
|
||||
prepared = [];
|
||||
previewRows.replaceChildren();
|
||||
get('apply').hidden = true;
|
||||
}
|
||||
|
||||
listen(scene, 'change', () => { clearPreview(); paste.value = ''; void load(); });
|
||||
listen(paste, 'input', () => { clearPreview(); changed(); });
|
||||
listen(get('add'), 'click', () => append([{ id: null, text: '', completed: false, changed: false, notes: '' }]));
|
||||
listen(get('discard'), 'click', () => {
|
||||
paste.value = '';
|
||||
clearPreview();
|
||||
dirty = false;
|
||||
void load();
|
||||
});
|
||||
listen(get('save'), 'click', async () => {
|
||||
if (!dirty || busy || !frame) return;
|
||||
if (items.some(item => !item.text.trim()) || paste.value.trim()) {
|
||||
status.textContent = 'Fill in each item and add or clear the pasted text before saving.';
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
updateControls();
|
||||
try {
|
||||
const next = await request(root.dataset.url, { ...scope(), version: frame.version, items }, events.signal);
|
||||
if (!root.isConnected) return;
|
||||
accept(next);
|
||||
window.PlotDirector?.toast?.success('Checklist saved');
|
||||
} catch (error) {
|
||||
if (!events.signal.aborted) status.textContent = error.message;
|
||||
} finally {
|
||||
busy = false;
|
||||
updateControls();
|
||||
}
|
||||
});
|
||||
listen(get('preview'), 'click', async () => {
|
||||
if (busy) return;
|
||||
const source = paste.value;
|
||||
clearPreview();
|
||||
try {
|
||||
const parsed = await request(root.dataset.previewUrl, source, events.signal);
|
||||
if (source !== paste.value) return;
|
||||
prepared = parsed.map(item => ({ id: null, text: item.text, completed: item.requestedCompleted, changed: false, notes: '' }));
|
||||
for (const item of prepared) {
|
||||
const row = document.createElement('li');
|
||||
row.className = 'list-group-item';
|
||||
const text = document.createElement('input');
|
||||
text.className = 'form-control form-control-sm';
|
||||
text.maxLength = 300;
|
||||
text.value = item.text;
|
||||
text.addEventListener('input', () => { item.text = text.value; });
|
||||
const done = document.createElement('input');
|
||||
done.type = 'checkbox';
|
||||
done.checked = item.completed;
|
||||
done.addEventListener('change', () => { item.completed = done.checked; });
|
||||
row.append(field('Item', text), field('Complete', done));
|
||||
previewRows.append(row);
|
||||
}
|
||||
get('apply').hidden = !prepared.length;
|
||||
if (!prepared.length) status.textContent = 'No items found in the pasted text.';
|
||||
} catch (error) {
|
||||
if (!events.signal.aborted) status.textContent = error.message;
|
||||
}
|
||||
});
|
||||
listen(get('apply'), 'click', () => {
|
||||
if (prepared.some(item => !item.text.trim())) {
|
||||
status.textContent = 'Fill in each preview item before adding it.';
|
||||
return;
|
||||
}
|
||||
if (append(prepared)) { clearPreview(); paste.value = ''; }
|
||||
});
|
||||
|
||||
const instance = {
|
||||
load,
|
||||
guarded: () => dirty || busy,
|
||||
selectElement(entity) {
|
||||
if (!frame?.canEdit || busy) return;
|
||||
selectedElement = entity;
|
||||
render();
|
||||
status.textContent = 'Choose an item for ' + entity.name + '.';
|
||||
},
|
||||
setScene(id) {
|
||||
const wasSceneScope = scene.checked;
|
||||
root.dataset.sceneId = id || '';
|
||||
get('scope-label').hidden = !id;
|
||||
if (!id) scene.checked = false;
|
||||
if (wasSceneScope) void load();
|
||||
},
|
||||
dispose() { pending?.abort(); readingPassages?.abort(); events.abort(); instances.delete(root); }
|
||||
};
|
||||
instances.set(root, instance);
|
||||
void load();
|
||||
}
|
||||
|
||||
window.PlotDirectorIntentChecklist = {
|
||||
mountWithin(node) { node.querySelectorAll('[data-intent-checklist]').forEach(mount); },
|
||||
within(node) { return instances.get(node.querySelector('[data-intent-checklist]')); }
|
||||
};
|
||||
})();
|
||||
@ -40,6 +40,19 @@
|
||||
aliasList.textContent = 'Aliases ' + aliases.join(', ');
|
||||
row.append(aliasList);
|
||||
}
|
||||
row.draggable = true;
|
||||
const selection = { key: entry.key, name: entry.name };
|
||||
row.addEventListener('dragstart', event => {
|
||||
event.dataTransfer.setData('application/x-plotdirector-intent-element', JSON.stringify(selection));
|
||||
event.dataTransfer.effectAllowed = 'link';
|
||||
});
|
||||
const select = document.createElement('button');
|
||||
select.type = 'button';
|
||||
select.className = 'btn btn-sm btn-outline-secondary mt-1';
|
||||
select.textContent = 'Select to link';
|
||||
select.setAttribute('aria-label', 'Select ' + entry.name + ' to link');
|
||||
select.addEventListener('click', () => checklist(root.parentElement)?.selectElement(selection));
|
||||
row.append(select);
|
||||
return row;
|
||||
});
|
||||
|
||||
@ -88,7 +101,11 @@
|
||||
if (!connection || wired.has(connection)) return;
|
||||
wired.add(connection);
|
||||
const invalidate = hint => {
|
||||
if (!hint?.projectId || Number(hint.projectId) === projectId) void refresh();
|
||||
if (!hint?.projectId || Number(hint.projectId) === projectId) {
|
||||
void refresh();
|
||||
if (!hint?.chapterId || Number(hint.chapterId) === Number(root.dataset.chapterId))
|
||||
void checklist(root.parentElement)?.load();
|
||||
}
|
||||
};
|
||||
connection.on('ContextInvalidated', invalidate);
|
||||
events.signal.addEventListener('abort', () => connection.off('ContextInvalidated', invalidate), { once: true });
|
||||
@ -118,25 +135,34 @@
|
||||
return instance;
|
||||
}
|
||||
|
||||
const checklist = node => window.PlotDirectorIntentChecklist?.within(node);
|
||||
const mountChecklist = node => window.PlotDirectorIntentChecklist?.mountWithin(node);
|
||||
const palette = node => node.querySelector('[data-intent-palette]');
|
||||
window.PlotDirectorIntentPalette = {
|
||||
mountWithin(node) { node.querySelectorAll('[data-intent-palette]').forEach(mount); },
|
||||
mountWithin(node) { mountChecklist(node); node.querySelectorAll('[data-intent-palette]').forEach(mount); },
|
||||
disposeWithin(node) {
|
||||
checklist(node)?.dispose();
|
||||
node.querySelectorAll('[data-intent-palette]').forEach(root => instances.get(root)?.dispose());
|
||||
}
|
||||
};
|
||||
window.PlotDirectorContextLifecycles = {
|
||||
...window.PlotDirectorContextLifecycles,
|
||||
intent: {
|
||||
mount(node) { mount(palette(node)); },
|
||||
dispose(node) { instances.get(palette(node))?.dispose(); },
|
||||
mount(node) { mountChecklist(node); mount(palette(node)); },
|
||||
canRefresh(node) { return !checklist(node)?.guarded(); },
|
||||
dispose(node) { checklist(node)?.dispose(); instances.get(palette(node))?.dispose(); },
|
||||
onPosition(node, next, previous) {
|
||||
if (next.chapterId !== previous.chapterId) return false;
|
||||
instances.get(palette(node))?.setScene(next.sceneId);
|
||||
checklist(node)?.setScene(next.sceneId);
|
||||
return true;
|
||||
},
|
||||
onCacheInvalidation(hint, node) {
|
||||
if (node && checklist(node)?.guarded()) void instances.get(palette(node))?.refresh();
|
||||
},
|
||||
onInvalidation(node) {
|
||||
void instances.get(palette(node))?.refresh();
|
||||
void checklist(node)?.load();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,12 +3,13 @@
|
||||
const root=document.querySelector('[data-writer-authoring]');if(!root)return;
|
||||
const main=root.closest('.writer3-main');
|
||||
main.addEventListener('plotdirector:work-state',e=>{const block=e.target.closest('.writer3-session-block');if(!block)return;if(e.detail.session){if(block.nextElementSibling!==root)root.before(block);}else if(block.previousElementSibling!==root)root.after(block);});
|
||||
let allowLeave=false;const dirty=()=>[...root.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true'||f.dataset.busy==='true');
|
||||
const intent=()=>window.PlotDirectorIntentChecklist?.within(document);
|
||||
let allowLeave=false;const dirty=()=>intent()?.guarded()||[...root.querySelectorAll('[data-authoring-form]')].some(f=>f.dataset.dirty==='true'||f.dataset.busy==='true');
|
||||
const cardOf=n=>n.closest('[data-authoring-card]');
|
||||
const focusEditor=card=>card.querySelector('textarea,select,input:not([type=hidden])')?.focus();
|
||||
function replaceReferences(template){
|
||||
const references=document.querySelector('[data-authoring-references]');
|
||||
if(!references||!template)return;
|
||||
if(!references||!template||intent()?.guarded())return;
|
||||
window.PlotDirectorIntentPalette?.disposeWithin(references);
|
||||
references.replaceChildren(template.content.cloneNode(true));
|
||||
window.PlotDirectorIntentPalette?.mountWithin(references);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user