@rohal12/spindle 0.59.23 → 0.59.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10582,19 +10582,13 @@ function* codeAndText(src, tokens, parametersOf) {
10582
10582
  yield textPiece(value, at, `In the ${name} attribute of <${token.tag}>: `);
10583
10583
  continue;
10584
10584
  }
10585
- let from = 0;
10586
- for (const part of splitSigilTemplate(value)) {
10587
- if (!("expr" in part)) continue;
10588
- const k = locate(value, part.expr, from);
10589
- from = k + part.expr.length;
10590
- yield {
10591
- kind: "code",
10592
- code: part.expr,
10593
- offset: at + k,
10594
- goal: "expression",
10595
- label: `{${part.expr}} in the ${name} attribute of <${token.tag}>`
10596
- };
10597
- }
10585
+ for (const { expr, at: k } of sigilExpressions(value)) yield {
10586
+ kind: "code",
10587
+ code: expr,
10588
+ offset: at + k,
10589
+ goal: "expression",
10590
+ label: `{${expr}} in the ${name} attribute of <${token.tag}>`
10591
+ };
10598
10592
  }
10599
10593
  else if (token.type === "macro" && !token.isClose) {
10600
10594
  const name = token.name.toLowerCase();
@@ -10862,6 +10856,24 @@ function attributeValues(src, token) {
10862
10856
  return values;
10863
10857
  }
10864
10858
  /**
10859
+ * The `{$…}` expressions in the value of a code attribute (`onclick`, see
10860
+ * isCodeAttribute), with where each is in the value.
10861
+ */
10862
+ function sigilExpressions(value) {
10863
+ const found = [];
10864
+ let from = 0;
10865
+ for (const part of splitSigilTemplate(value)) {
10866
+ if (!("expr" in part)) continue;
10867
+ const at = locate(value, part.expr, from);
10868
+ from = at + part.expr.length;
10869
+ found.push({
10870
+ expr: part.expr,
10871
+ at
10872
+ });
10873
+ }
10874
+ return found;
10875
+ }
10876
+ /**
10865
10877
  * Index of `part` in `text` from `from` on, else anywhere, else `from`: the
10866
10878
  * place to report an error in `part` at.
10867
10879
  */
@@ -11071,37 +11083,70 @@ function widgetDef({ name = "", parameters = "" }) {
11071
11083
  function parseWidgetDef(rawArgs) {
11072
11084
  return widgetDef(parseMacroArgs(rawArgs, WIDGET_PARAMETERS));
11073
11085
  }
11086
+ /** Where the name is written in the arguments, without its quotes. */
11087
+ function nameSpan(rawArgs) {
11088
+ const spans = /* @__PURE__ */ new Map();
11089
+ parseMacroArgs(rawArgs, WIDGET_PARAMETERS, spans);
11090
+ const [start, end] = spans.get(WIDGET_PARAMETERS[0]) ?? [0, 0];
11091
+ const quote = rawArgs[start];
11092
+ return (quote === "\"" || quote === "'") && end - start >= 2 ? [start + 1, rawArgs[end - 1] === quote ? end - 1 : end] : [start, end];
11093
+ }
11074
11094
  /**
11075
- * The names of the block widgets (those whose body renders `{@children}`)
11076
- * that StoryInit and the passages tagged `widget` define. They must be
11077
- * known as block macros before any passage is parsed, so that passages
11078
- * invoking them nest their content whatever the passage order.
11095
+ * The widgets that StoryInit and the passages tagged `widget` define, in
11096
+ * source order: the ones the runtime registers, read tolerantly (a half-typed
11097
+ * definition is still reported, without a `closeStart`). Definitions whose
11098
+ * arguments cannot be read are left out.
11079
11099
  *
11080
11100
  * The passages are read as flat tokens, which need no block macros to be
11081
11101
  * known, so a `{@children}` in an HTML comment or in a `{do}` body is text
11082
- * here as it is to the parser, and does not make a block widget (#387).
11102
+ * here as it is to the parser, and does not make a block widget (#387). In
11103
+ * nested definitions, it belongs to the innermost.
11083
11104
  */
11084
- function blockWidgetNames(passages, parametersOf = registeredParameters) {
11085
- const names = [];
11105
+ function widgetDefinitions$1(passages, parametersOf = registeredParameters) {
11106
+ const found = [];
11086
11107
  for (const passage of passages) {
11087
11108
  if (passage.name !== "StoryInit" && !passage.tags?.includes("widget")) continue;
11088
11109
  const open = [];
11089
- for (const token of tokenizeMarkupTolerant(passage.content).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") {
11090
- if (!token.isClose) {
11091
- open.push({
11092
- rawArgs: token.rawArgs,
11093
- isBlock: false
11094
- });
11095
- continue;
11096
- }
11110
+ const done = [];
11111
+ for (const token of tokenizeMarkupTolerant(passage.content).tokens) if (token.type === "macro" && token.name.toLowerCase() === "widget") if (!token.isClose) open.push({
11112
+ token,
11113
+ isBlock: false
11114
+ });
11115
+ else {
11097
11116
  const def = open.pop();
11098
- if (!def?.isBlock) continue;
11099
- try {
11100
- names.push(parseWidgetDef(def.rawArgs).name);
11101
- } catch {}
11102
- } else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11117
+ if (def) done.push({
11118
+ ...def,
11119
+ closeStart: token.start
11120
+ });
11121
+ }
11122
+ else if (open.length > 0 && (token.type === "variable" && token.scope === "local" && token.name === "children" || tokenTextContainsChildren(token, parametersOf))) open[open.length - 1].isBlock = true;
11123
+ done.push(...open);
11124
+ const defs = [];
11125
+ for (const { token, isBlock, closeStart } of done) try {
11126
+ const [from, to] = nameSpan(token.rawArgs);
11127
+ defs.push({
11128
+ ...parseWidgetDef(token.rawArgs),
11129
+ block: isBlock,
11130
+ passage: passage.name,
11131
+ start: token.start,
11132
+ end: token.end,
11133
+ nameStart: token.argsStart + from,
11134
+ nameEnd: token.argsStart + to,
11135
+ ...closeStart === void 0 ? {} : { closeStart }
11136
+ });
11137
+ } catch {}
11138
+ found.push(...defs.sort((a, b) => a.start - b.start));
11103
11139
  }
11104
- return names;
11140
+ return found;
11141
+ }
11142
+ /**
11143
+ * The names of the block widgets (those whose body renders `{@children}`)
11144
+ * that StoryInit and the passages tagged `widget` define, closed. They must
11145
+ * be known as block macros before any passage is parsed, so that passages
11146
+ * invoking them nest their content whatever the passage order.
11147
+ */
11148
+ function blockWidgetNames(passages, parametersOf = registeredParameters) {
11149
+ return widgetDefinitions$1(passages, parametersOf).filter((def) => def.block && def.closeStart !== void 0).map((def) => def.name);
11105
11150
  }
11106
11151
  //#endregion
11107
11152
  //#region src/markup/validate.ts
@@ -11121,7 +11166,7 @@ var NOT_MARKUP = new Set([
11121
11166
  "StoryTransients",
11122
11167
  "SaveTitle"
11123
11168
  ]);
11124
- var NOT_MARKUP_TAGS = ["script", "stylesheet"];
11169
+ var NOT_MARKUP_TAGS$1 = ["script", "stylesheet"];
11125
11170
  /** Branch macros, which their parent macro renders. */
11126
11171
  var BRANCH_MACROS = new Set([
11127
11172
  "elseif",
@@ -11208,7 +11253,7 @@ function validateMarkup(passages, options) {
11208
11253
  for (const passage of passages) {
11209
11254
  passageNames.add(passage.name);
11210
11255
  if (NOT_MARKUP.has(passage.name)) continue;
11211
- if (passage.tags?.some((tag) => NOT_MARKUP_TAGS.includes(tag))) continue;
11256
+ if (passage.tags?.some((tag) => NOT_MARKUP_TAGS$1.includes(tag))) continue;
11212
11257
  const reported = !options.only || options.only(passage);
11213
11258
  try {
11214
11259
  const tokens = tokenizeMarkup(passage.content);
@@ -11570,15 +11615,38 @@ var Reader = class {
11570
11615
  };
11571
11616
  //#endregion
11572
11617
  //#region src/story-variables.ts
11618
+ /**
11619
+ * The tokens of markup, or none if it is malformed (validateMarkup reports
11620
+ * that, with its position); in tolerant mode, those of the well-formed parts.
11621
+ */
11622
+ function tokensOf(text, textMode, { tolerant } = {}) {
11623
+ if (tolerant) return tokenizeMarkupTolerant(text, { text: textMode }).tokens;
11624
+ try {
11625
+ return tokenizeMarkup(text, { text: textMode });
11626
+ } catch (err) {
11627
+ if (err instanceof MarkupError) return [];
11628
+ throw err;
11629
+ }
11630
+ }
11573
11631
  function declarationRegex(sigil) {
11574
11632
  const escaped = sigil.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11575
11633
  return new RegExp(`^${escaped}(\\w+)\\s*=\\s*(.+)$`);
11576
11634
  }
11635
+ /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
11636
+ var VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
11637
+ /** Quoted first argument of an input macro naming a story variable. */
11638
+ var QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
11577
11639
  var VALID_VAR_TYPES = new Set([
11578
11640
  "number",
11579
11641
  "string",
11580
11642
  "boolean"
11581
11643
  ]);
11644
+ /** Boxed sample values whose members a primitive of each type can access. */
11645
+ var PRIMITIVE_SAMPLES = {
11646
+ string: Object(""),
11647
+ number: Object(0),
11648
+ boolean: Object(false)
11649
+ };
11582
11650
  /**
11583
11651
  * The schema of a default value. An object met again (a backreference, a
11584
11652
  * shared subtree) has the schema made for it the first time, so a cyclic
@@ -11718,6 +11786,240 @@ function parseStoryVariables(content, sigil = "$") {
11718
11786
  }
11719
11787
  return schema;
11720
11788
  }
11789
+ /**
11790
+ * Check a reference against the declarations: the error code and message, or
11791
+ * null if it is valid. (Unknown fields of objects are valid: classes
11792
+ * registered with Story.registerClass() can add members that are not in the
11793
+ * defaults.)
11794
+ */
11795
+ function checkReference(ref, declared) {
11796
+ const label = (path) => ref.sigil + [ref.name, ...path].join(".");
11797
+ const nameError = variableNameError(ref.name, ref.sigil + ref.name);
11798
+ if (nameError) return {
11799
+ code: "reserved-name",
11800
+ message: nameError
11801
+ };
11802
+ const schema = ref.sigil === "$" ? declared.variables : declared.transients;
11803
+ if (!schema) return null;
11804
+ if (!schema.has(ref.name)) return ref.sigil === "$" ? {
11805
+ code: "undeclared-variable",
11806
+ message: `Undeclared variable: ${label(ref.path)}`
11807
+ } : {
11808
+ code: "undeclared-transient",
11809
+ message: `Undeclared transient: ${label(ref.path)}`
11810
+ };
11811
+ let current = schema.get(ref.name);
11812
+ for (let i = 0; current && i < ref.path.length; i++) {
11813
+ const part = ref.path[i];
11814
+ if (current.type === "array") return null;
11815
+ if (current.type === "null") return null;
11816
+ const sample = PRIMITIVE_SAMPLES[current.type];
11817
+ if (sample && part in sample) {
11818
+ const memberType = typeof sample[part];
11819
+ if (!VALID_VAR_TYPES.has(memberType)) return null;
11820
+ current = { type: memberType };
11821
+ continue;
11822
+ }
11823
+ if (current.type !== "object" || !current.fields) return {
11824
+ code: "primitive-field",
11825
+ message: `Cannot access field "${part}" on ${label(ref.path.slice(0, i))} (type: ${current.type})`
11826
+ };
11827
+ current = current.fields.get(part);
11828
+ }
11829
+ return null;
11830
+ }
11831
+ var NO_STORE_VAR_MACROS = /* @__PURE__ */ new Set();
11832
+ /** A reference written at `index` of `code`, with its dot path. */
11833
+ function referenceAt(code, index, at) {
11834
+ VAR_PATH_RE.lastIndex = index;
11835
+ const match = VAR_PATH_RE.exec(code);
11836
+ if (!match) return void 0;
11837
+ const [name, ...path] = match[2].split(".");
11838
+ return {
11839
+ sigil: match[1],
11840
+ name,
11841
+ path,
11842
+ start: at(index),
11843
+ end: at(index + match[0].length)
11844
+ };
11845
+ }
11846
+ /**
11847
+ * Scan the value of a code attribute (`onclick`, see isCodeAttribute) for
11848
+ * the `{$…}` references resolved in it; its other braces are code. `at` is
11849
+ * where the value is.
11850
+ */
11851
+ function scanSigilReferences(value, at, emit) {
11852
+ for (const { expr, at: k } of sigilExpressions(value)) scanCode(expr, (i) => at(k + i), emit);
11853
+ }
11854
+ /**
11855
+ * Scan literal text (string contents, HTML attribute values) for the markup
11856
+ * that labels and HTML attributes evaluate at runtime: `{$…}` displays,
11857
+ * expressions and macros, read as in passage text. A bare `$word` in
11858
+ * literal text is not a reference.
11859
+ */
11860
+ function scanInterpolations(text, at, emit, options) {
11861
+ if (!text.includes("{")) return;
11862
+ collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
11863
+ }
11864
+ /**
11865
+ * Report `$var` references in JavaScript code, lexed as the expression
11866
+ * engine lexes it (`lexJs`): references in code, but none inside string or
11867
+ * regex literals or comments, nor property names (`a.$b`, `{ $b: 1 }`).
11868
+ * The text of string and template literals is not scanned: a string in code
11869
+ * is literal text unless a macro argument that holds markup is read as such
11870
+ * (see scanArgs); the `${…}` parts of template literals are code.
11871
+ */
11872
+ function scanCode(code, at, emit, goal = "expression") {
11873
+ const parsed = parseOrError(code, goal);
11874
+ if (parsed instanceof CodeSyntaxError) {
11875
+ scanCodeLeniently(code, at, emit, goal);
11876
+ return;
11877
+ }
11878
+ for (const ref of parsed.refs) {
11879
+ if (ref.sigil !== "$" && ref.sigil !== "%") continue;
11880
+ const found = referenceAt(code, ref.start, at);
11881
+ if (found) emit(found);
11882
+ }
11883
+ }
11884
+ /** `scanCode` for code acorn can't parse: lexed leniently. */
11885
+ function scanCodeLeniently(code, at, emit, goal) {
11886
+ lexJs(code, {
11887
+ variable(sigil, _name, index) {
11888
+ if (sigil !== "$" && sigil !== "%") return;
11889
+ const found = referenceAt(code, index, at);
11890
+ if (found) emit(found);
11891
+ },
11892
+ literal() {}
11893
+ }, goal);
11894
+ }
11895
+ /**
11896
+ * Report the references in the arguments of a macro by what its parameters
11897
+ * say each holds (see ParameterDef.holds): code is scanned as code and
11898
+ * markup as markup, but literal text (a placeholder, a passage name) holds
11899
+ * none. A macro without declared parameters, or arguments that do not
11900
+ * parse, are scanned as code.
11901
+ */
11902
+ function scanArgs(token, params, at, emit, options) {
11903
+ if (!token.rawArgs) return;
11904
+ if (params) {
11905
+ const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
11906
+ if (!pieces.some((piece) => piece.kind === "argument-error")) {
11907
+ for (const piece of pieces) {
11908
+ const pieceAt = (i) => at(pieceOffset(piece, i));
11909
+ if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
11910
+ else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
11911
+ ...options,
11912
+ storeVarMacros: NO_STORE_VAR_MACROS
11913
+ });
11914
+ }
11915
+ return;
11916
+ }
11917
+ }
11918
+ scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
11919
+ }
11920
+ /** Report the `$var` references in the tokens of `content`. */
11921
+ function collectTokenRefs(content, tokens, at, emit, options) {
11922
+ const { storeVarMacros, parametersOf } = options;
11923
+ for (let t = 0; t < tokens.length; t++) {
11924
+ const token = tokens[t];
11925
+ if (token.type === "variable") {
11926
+ if ((token.scope === "variable" || token.scope === "transient") && token.name) {
11927
+ const [name, ...path] = token.name.split(".");
11928
+ emit({
11929
+ sigil: token.scope === "variable" ? "$" : "%",
11930
+ name,
11931
+ path,
11932
+ start: at(token.nameStart - 1),
11933
+ end: at(token.nameEnd)
11934
+ });
11935
+ }
11936
+ } else if (token.type === "link") scanInterpolations(token.display, (i) => at(token.displayStart + i), emit, {
11937
+ ...options,
11938
+ storeVarMacros: NO_STORE_VAR_MACROS
11939
+ });
11940
+ else if (token.type === "expression") scanCode(token.expression, (i) => at(token.expressionStart + i), emit);
11941
+ else if (token.type === "html") for (const { name, value, at: valueAt } of attributeValues(content, token)) {
11942
+ const valueIn = (i) => at(valueAt + i);
11943
+ if (isCodeAttribute(name)) scanSigilReferences(value, valueIn, emit);
11944
+ else scanInterpolations(value, valueIn, emit, options);
11945
+ }
11946
+ else if (token.type === "macro" && !token.isClose) {
11947
+ scanArgs(token, parametersOf(token.name), at, emit, options);
11948
+ if (token.selectorsStart !== void 0 && token.selectorsEnd !== void 0) {
11949
+ const from = token.selectorsStart;
11950
+ scanInterpolations(content.slice(from, token.selectorsEnd), (i) => at(from + i), emit, {
11951
+ ...options,
11952
+ storeVarMacros: NO_STORE_VAR_MACROS
11953
+ });
11954
+ }
11955
+ if (storeVarMacros.has(token.name.toLowerCase())) {
11956
+ const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
11957
+ const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
11958
+ const quoted = QUOTED_VAR_ARG_RE.exec(first);
11959
+ if (quoted) {
11960
+ const [name, ...path] = quoted[1].split(".");
11961
+ const start = token.argsStart + lead + 1;
11962
+ emit({
11963
+ sigil: "$",
11964
+ name,
11965
+ path,
11966
+ start: at(start),
11967
+ end: at(start + 1 + quoted[1].length)
11968
+ });
11969
+ } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
11970
+ }
11971
+ if (token.name.toLowerCase() === "do") {
11972
+ let close = t + 1;
11973
+ while (close < tokens.length) {
11974
+ const c = tokens[close];
11975
+ if (c.type === "macro" && c.isClose && c.name.toLowerCase() === "do") break;
11976
+ close++;
11977
+ }
11978
+ if (close < tokens.length) {
11979
+ scanCode(content.slice(token.end, tokens[close].start), (i) => at(token.end + i), emit, "statements");
11980
+ t = close;
11981
+ }
11982
+ }
11983
+ }
11984
+ }
11985
+ }
11986
+ /**
11987
+ * The `$` and `%` variable references a passage evaluates at runtime, in
11988
+ * source order: `{$var}` displays, `{$expr}` expressions, macro arguments and
11989
+ * `{do}` bodies (as code), quoted variable names bound by input macros, and
11990
+ * `{$…}` interpolations in labels and HTML attributes. Prose is literal text
11991
+ * and not scanned.
11992
+ */
11993
+ function collectVariableReferences(content, options) {
11994
+ const found = [];
11995
+ withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
11996
+ return found;
11997
+ }
11998
+ /**
11999
+ * The invalid variable references of the passages, against what is declared,
12000
+ * with their positions. The passages that hold no markup (the declarations
12001
+ * themselves, SaveTitle) are skipped.
12002
+ */
12003
+ function checkVariableReferences(passages, declared, options) {
12004
+ const diagnostics = [];
12005
+ for (const passage of passages) {
12006
+ if (NOT_MARKUP.has(passage.name)) continue;
12007
+ for (const ref of collectVariableReferences(passage.content, options)) {
12008
+ const error = checkReference(ref, declared);
12009
+ if (!error) continue;
12010
+ diagnostics.push({
12011
+ passage: passage.name,
12012
+ code: error.code,
12013
+ name: ref.name,
12014
+ ...ref.path.length > 0 ? { path: ref.path } : {},
12015
+ start: ref.start,
12016
+ end: ref.end,
12017
+ message: error.message
12018
+ });
12019
+ }
12020
+ }
12021
+ return diagnostics;
12022
+ }
11721
12023
  //#endregion
11722
12024
  //#region src/components/macros/include-args.ts
11723
12025
  /**
@@ -11860,5 +12162,49 @@ function passagePieces(source, macros = []) {
11860
12162
  function collectStoryPassageReferences(source, macros) {
11861
12163
  return referencesOf(passagePieces(source, macros));
11862
12164
  }
12165
+ /**
12166
+ * The widgets the story defines, as the runtime reads them: those of
12167
+ * StoryInit and of the passages tagged `widget`, with their parameters,
12168
+ * whether their body renders `{@children}` (a block widget) and where they
12169
+ * are written, in source order. Half-typed definitions are reported without a
12170
+ * `closeStart`. The macros are those the markup may use, built-in and
12171
+ * user-defined (a `{@children}` in an attribute or label counts).
12172
+ */
12173
+ function widgetDefinitions(passages, macros = []) {
12174
+ return widgetDefinitions$1(passages, parameterLookup([...macros]));
12175
+ }
12176
+ /** Passages tagged so hold code or styles, not markup. */
12177
+ var NOT_MARKUP_TAGS = ["script", "stylesheet"];
12178
+ /** What reading the variable references of markup depends on. */
12179
+ function referenceOptions(macros) {
12180
+ const all = [...macros];
12181
+ return {
12182
+ storeVarMacros: new Set(all.filter((m) => m.storeVar).map((m) => m.name.toLowerCase())),
12183
+ parametersOf: parameterLookup(all),
12184
+ tolerant: true
12185
+ };
12186
+ }
12187
+ /**
12188
+ * The `$` and `%` variable references that the markup of a passage evaluates,
12189
+ * in source order, with the dotted path of fields accessed and where each is
12190
+ * written (offsets into `source`, UTF-16): `{$var}` displays, code in
12191
+ * expressions, conditions, `{do}` bodies and macro arguments, quoted names
12192
+ * bound by input macros, and the markup in labels and HTML attributes. Prose
12193
+ * is literal text. Malformed tags are skipped, so it reads half-typed markup.
12194
+ * The macros are those the markup may use, built-in and user-defined.
12195
+ */
12196
+ function variableReferences(source, macros = []) {
12197
+ return collectVariableReferences(source, referenceOptions(macros));
12198
+ }
12199
+ /**
12200
+ * The variable references of the passages' markup that are not valid against
12201
+ * the declarations, as the story start checks them: a variable (or, when
12202
+ * `transients` is given, a transient) that is not declared, and a field of a
12203
+ * primitive that it has no member of. Built on `variableReferences`:
12204
+ * tolerant of half-typed markup, and it evaluates no project code.
12205
+ */
12206
+ function validateVariableReferences(passages, declarations, macros = []) {
12207
+ return checkVariableReferences([...passages].filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros));
12208
+ }
11863
12209
  //#endregion
11864
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, passagePieces, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup };
12210
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
@@ -37,6 +37,10 @@ export {
37
37
  stripLooseQuotes,
38
38
  unescapeQuoted,
39
39
  splitIncludeFlag,
40
+ parseWidgetDef,
41
+ widgetDefinitions,
42
+ variableReferences,
43
+ validateVariableReferences,
40
44
  } from './story-variables.js';
41
45
 
42
46
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.59.23",
3
+ "version": "0.59.25",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -331,17 +331,13 @@ export function* codeAndText(
331
331
  );
332
332
  continue;
333
333
  }
334
- let from = 0;
335
- for (const part of splitSigilTemplate(value)) {
336
- if (!('expr' in part)) continue;
337
- const k = locate(value, part.expr, from);
338
- from = k + part.expr.length;
334
+ for (const { expr, at: k } of sigilExpressions(value)) {
339
335
  yield {
340
336
  kind: 'code',
341
- code: part.expr,
337
+ code: expr,
342
338
  offset: at + k,
343
339
  goal: 'expression',
344
- label: `{${part.expr}} in the ${name} attribute of <${token.tag}>`,
340
+ label: `{${expr}} in the ${name} attribute of <${token.tag}>`,
345
341
  };
346
342
  }
347
343
  }
@@ -652,7 +648,7 @@ const textPiece = (text: string, offset: number, where: string): TextPiece => ({
652
648
  * value is: the first of equal names, which is the one in effect. A token
653
649
  * with no spans (made from an AST) has them found in `src`, in order.
654
650
  */
655
- function attributeValues(
651
+ export function attributeValues(
656
652
  src: string,
657
653
  token: HtmlToken,
658
654
  ): { name: string; value: string; at: number }[] {
@@ -680,11 +676,29 @@ function attributeValues(
680
676
  return values;
681
677
  }
682
678
 
679
+ /**
680
+ * The `{$…}` expressions in the value of a code attribute (`onclick`, see
681
+ * isCodeAttribute), with where each is in the value.
682
+ */
683
+ export function sigilExpressions(
684
+ value: string,
685
+ ): { expr: string; at: number }[] {
686
+ const found = [];
687
+ let from = 0;
688
+ for (const part of splitSigilTemplate(value)) {
689
+ if (!('expr' in part)) continue;
690
+ const at = locate(value, part.expr, from);
691
+ from = at + part.expr.length;
692
+ found.push({ expr: part.expr, at });
693
+ }
694
+ return found;
695
+ }
696
+
683
697
  /**
684
698
  * Index of `part` in `text` from `from` on, else anywhere, else `from`: the
685
699
  * place to report an error in `part` at.
686
700
  */
687
- function locate(text: string, part: string, from: number): number {
701
+ export function locate(text: string, part: string, from: number): number {
688
702
  const at = text.indexOf(part, from);
689
703
  if (at >= 0) return at;
690
704
  const anywhere = text.indexOf(part);
@@ -1,5 +1,11 @@
1
1
  import { createContext } from 'preact';
2
- import { useCallback, useLayoutEffect, useMemo, useRef } from 'preact/hooks';
2
+ import {
3
+ useCallback,
4
+ useId,
5
+ useLayoutEffect,
6
+ useMemo,
7
+ useRef,
8
+ } from 'preact/hooks';
3
9
  import { parseMarkup } from '../markup/parse';
4
10
  import {
5
11
  renderNodes,
@@ -20,6 +26,11 @@ interface PassageDialogProps {
20
26
  fallbackMarkup?: string;
21
27
  panelClass?: string;
22
28
  onClose: () => void;
29
+ /**
30
+ * The dialog's accessible name. Without one, the first heading authored in
31
+ * the dialog names it, or else its passage.
32
+ */
33
+ label?: string;
23
34
  /** Show the default `✕` button. Defaults to `dismissible`. */
24
35
  showCloseButton?: boolean;
25
36
  /**
@@ -35,6 +46,7 @@ export function PassageDialog({
35
46
  fallbackMarkup,
36
47
  panelClass,
37
48
  onClose,
49
+ label,
38
50
  dismissible = true,
39
51
  showCloseButton = dismissible,
40
52
  }: PassageDialogProps) {
@@ -71,6 +83,7 @@ export function PassageDialog({
71
83
  }, [markup, nobr]);
72
84
 
73
85
  const panelRef = useRef<HTMLDivElement>(null);
86
+ const labelId = useId();
74
87
  const viewScope = useViewScope();
75
88
 
76
89
  // Focus into the dialog, trap Tab, Escape to close, restore focus on close.
@@ -80,6 +93,19 @@ export function PassageDialog({
80
93
  // Be on the stack of displayed dialogs the Story dialog API works on.
81
94
  useLayoutEffect(() => registerOpenDialog(stableOnClose), [stableOnClose]);
82
95
 
96
+ // Name the dialog after its first heading when no label is given
97
+ useLayoutEffect(() => {
98
+ const panel = panelRef.current;
99
+ if (!panel || label) return;
100
+ const heading = panel.querySelector<HTMLElement>(
101
+ '.dialog-body :is(h1, h2, h3, h4, h5, h6)',
102
+ );
103
+ if (!heading) return;
104
+ heading.id ||= `${labelId}-heading`;
105
+ panel.setAttribute('aria-labelledby', heading.id);
106
+ return () => panel.removeAttribute('aria-labelledby');
107
+ }, [label, markup]);
108
+
83
109
  // Signal that the dialog's DOM is committed (once per open).
84
110
  useLayoutEffect(() => {
85
111
  if (panelRef.current) {
@@ -107,6 +133,7 @@ export function PassageDialog({
107
133
  class={cls}
108
134
  role="dialog"
109
135
  aria-modal="true"
136
+ aria-label={label ?? passageName}
110
137
  tabIndex={-1}
111
138
  >
112
139
  {showCloseButton && (
@@ -77,6 +77,9 @@ export function defineMenubarAction(config: MenubarActionConfig) {
77
77
  passageName={config.dialog.passageName}
78
78
  fallbackMarkup={config.dialog.fallbackMarkup}
79
79
  panelClass={config.dialog.panelClass}
80
+ label={
81
+ typeof config.label === 'string' ? config.label : config.name
82
+ }
80
83
  onClose={() => setDialogOpen(false)}
81
84
  showCloseButton={config.dialog.showCloseButton}
82
85
  />
@@ -1,14 +1,18 @@
1
- import { useState } from 'preact/hooks';
2
- import { settings, type SettingDef } from '../../settings';
1
+ import { useEffect, useState } from 'preact/hooks';
2
+ import { settings, subscribeSettings, type SettingDef } from '../../settings';
3
3
  import { defineMacro } from '../../define-macro';
4
4
 
5
5
  function SettingControl({ name, def }: { name: string; def: SettingDef }) {
6
6
  const [value, setValue] = useState(() => settings.get(name));
7
7
 
8
- const update = (newValue: unknown) => {
9
- setValue(newValue);
10
- settings.set(name, newValue);
11
- };
8
+ // Follow changes made elsewhere: Story.settings.set(), another view
9
+ useEffect(() => {
10
+ const sync = () => setValue(settings.get(name));
11
+ sync();
12
+ return subscribeSettings(sync);
13
+ }, [name]);
14
+
15
+ const update = (newValue: unknown) => settings.set(name, newValue);
12
16
 
13
17
  switch (def.type) {
14
18
  case 'toggle':