@arkitektio/bsx 6.7.0 → 6.9.0

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.
Files changed (50) hide show
  1. package/dist/bsx/declared.d.ts +35 -3
  2. package/dist/bsx/declared.d.ts.map +1 -1
  3. package/dist/bsx/declared.js +73 -3
  4. package/dist/bsx/declared.js.map +1 -1
  5. package/dist/bsx/expr.d.ts +5 -3
  6. package/dist/bsx/expr.d.ts.map +1 -1
  7. package/dist/bsx/expr.js +18 -7
  8. package/dist/bsx/expr.js.map +1 -1
  9. package/dist/bsx/language.d.ts.map +1 -1
  10. package/dist/bsx/language.js +6 -4
  11. package/dist/bsx/language.js.map +1 -1
  12. package/dist/bsx/parse.d.ts.map +1 -1
  13. package/dist/bsx/parse.js +23 -6
  14. package/dist/bsx/parse.js.map +1 -1
  15. package/dist/bsx/print.d.ts.map +1 -1
  16. package/dist/bsx/print.js +10 -3
  17. package/dist/bsx/print.js.map +1 -1
  18. package/dist/bsx/references.d.ts.map +1 -1
  19. package/dist/bsx/references.js +103 -22
  20. package/dist/bsx/references.js.map +1 -1
  21. package/dist/renderer/bloks/control.d.ts +7 -1
  22. package/dist/renderer/bloks/control.d.ts.map +1 -1
  23. package/dist/renderer/bloks/control.js +24 -6
  24. package/dist/renderer/bloks/control.js.map +1 -1
  25. package/dist/spec/bsx_v2.json +3479 -2185
  26. package/dist/spec/catalogs/base@4.json +35 -6
  27. package/dist/spec/catalogs/base@4.json.js +35 -6
  28. package/dist/spec/vocabulary.d.ts +2 -0
  29. package/dist/spec/vocabulary.d.ts.map +1 -1
  30. package/dist/spec/vocabulary.js +2 -0
  31. package/dist/spec/vocabulary.js.map +1 -1
  32. package/dist/spec/vocabulary.json +19 -12
  33. package/dist/spec/vocabulary.json.js +19 -12
  34. package/package.json +1 -1
  35. package/src/bsx/declared.ts +76 -5
  36. package/src/bsx/expr.ts +17 -8
  37. package/src/bsx/infer.test.ts +1 -1
  38. package/src/bsx/language.test.ts +17 -16
  39. package/src/bsx/language.ts +6 -4
  40. package/src/bsx/logo.test.ts +47 -0
  41. package/src/bsx/parse.ts +23 -4
  42. package/src/bsx/print.ts +9 -2
  43. package/src/bsx/references.test.ts +6 -6
  44. package/src/bsx/references.ts +105 -20
  45. package/src/renderer/bloks/control.tsx +31 -7
  46. package/src/spec/bsx_v2.json +3479 -2185
  47. package/src/spec/catalogs/base@4.json +35 -6
  48. package/src/spec/spec.test.ts +1 -1
  49. package/src/spec/vocabulary.json +19 -12
  50. package/src/spec/vocabulary.ts +4 -0
@@ -26,6 +26,8 @@ export const QUERY_COMPONENT = 'query';
26
26
  export const SUBSCRIPTION_COMPONENT = 'subscription';
27
27
  export const VAR_COMPONENT = 'var';
28
28
  export const DEPENDENCIES_COMPONENT = 'dependencies';
29
+ /** A blok's own logo: a child of its `<Blok>` holding a drawing of the logo catalog. */
30
+ export const LOGO_COMPONENT = 'logo';
29
31
  /** The components that declare what a blok owns and draw nothing. */
30
32
  export const DECLARATION_COMPONENTS: ReadonlySet<string> = new Set([
31
33
  LOCAL_COMPONENT,
@@ -33,7 +35,22 @@ export const DECLARATION_COMPONENTS: ReadonlySet<string> = new Set([
33
35
  SUBSCRIPTION_COMPONENT,
34
36
  VAR_COMPONENT,
35
37
  DEPENDENCIES_COMPONENT,
38
+ LOGO_COMPONENT,
36
39
  ]);
40
+ const LOGO_TITLE_PROP = 'title';
41
+ const LOGO_VIEW_BOX_PROP = 'viewBox';
42
+ /** A logo's grid when its `<logo>` names none: 24 units, the grid of the action logos. */
43
+ export const LOGO_VIEW_BOX = '0 0 24 24';
44
+ /** The pen a `<logo>` draws with unless a shape says otherwise: the action logos' pen. */
45
+ export const LOGO_PEN: ReadonlyArray<readonly [string, string]> = [
46
+ ['fill', 'none'],
47
+ ['stroke', 'ink'],
48
+ ['strokeWidth', '1.8'],
49
+ ['strokeLinecap', 'round'],
50
+ ['strokeLinejoin', 'round'],
51
+ ];
52
+ /** The kind a `<logo>` is drawn as (`blokLogoTree`): one drawn in the logo context. */
53
+ export const LOGO_KIND = 'agent';
37
54
  /** The name a local, a query or a subscription is read by. */
38
55
  export const NAME_PROP = 'name';
39
56
  /** A local's borrowed port: `self.<action>.<arg>` or `deps.<key>.<action>.<arg>`. */
@@ -224,6 +241,49 @@ export const declaredLocal = (node: BlokComponentNode): DeclaredLocal | null =>
224
241
  };
225
242
 
226
243
  /** Every node of `tree` with its ancestors, depth first. */
244
+ /**
245
+ * The blok's own `<logo>`: the first among the children of its `<Blok>`, or
246
+ * null. A `<logo>` anywhere else, or a second one, stands for nothing (the
247
+ * checker says so: `logo.misplaced`, `logo.twice`). The port of the spec's
248
+ * `declared_logo`.
249
+ */
250
+ export const declaredLogo = (tree: BlokComponentNode | null | undefined): BlokComponentNode | null =>
251
+ (tree?.children ?? []).find(child => child.component === LOGO_COMPONENT) ?? null;
252
+
253
+ /**
254
+ * The blok's `<logo>` as a logo blok of its own, or null when it declares
255
+ * none: `<Blok kind="agent" context="logo"><Logo viewBox title><G pen>...`.
256
+ * What is checked (pens, the logo catalog, the logo limits) and drawn for it,
257
+ * in lists, pins and tabs. Its kind is `agent` whatever the blok's: a `<logo>`
258
+ * is literals only and reads nothing. The drawing's nodes are the `<logo>`'s
259
+ * own; the frame takes its id (and two made from it). The port of the spec's
260
+ * `blok_logo_tree`.
261
+ */
262
+ export const blokLogoTree = (tree: BlokComponentNode | null | undefined): BlokComponentNode | null => {
263
+ const logo = declaredLogo(tree);
264
+ if (logo === null) return null;
265
+ const props = new Map((logo.props ?? []).map(prop => [prop.key, prop]));
266
+ const title = props.get(LOGO_TITLE_PROP);
267
+ const drawingProps = [props.get(LOGO_VIEW_BOX_PROP) ?? {key: LOGO_VIEW_BOX_PROP, static_value: LOGO_VIEW_BOX}];
268
+ if (title) drawingProps.push(title);
269
+ const pen: BlokComponentNode = {
270
+ id: `${logo.id}.pen`,
271
+ component: 'G',
272
+ props: LOGO_PEN.map(([key, value]) => ({key, static_value: value})),
273
+ children: logo.children ?? [],
274
+ };
275
+ const drawing: BlokComponentNode = {id: `${logo.id}.drawing`, component: 'Logo', props: drawingProps, children: [pen]};
276
+ return {
277
+ id: logo.id,
278
+ component: BLOK_COMPONENT,
279
+ props: [
280
+ {key: KIND_ATTRIBUTE, static_value: LOGO_KIND},
281
+ {key: CONTEXT_ATTRIBUTE, static_value: 'logo'},
282
+ ],
283
+ children: [drawing],
284
+ };
285
+ };
286
+
227
287
  export const iterWithParents = (tree: BlokComponentNode): Array<[BlokComponentNode, readonly BlokComponentNode[]]> => {
228
288
  const found: Array<[BlokComponentNode, readonly BlokComponentNode[]]> = [];
229
289
  const visit = (node: BlokComponentNode, ancestors: readonly BlokComponentNode[]) => {
@@ -332,8 +392,8 @@ const declaredRead = (node: BlokComponentNode): Record<string, unknown> => {
332
392
  const rootChildren = (tree: BlokComponentNode | null | undefined): BlokComponentNode[] => tree?.children ?? [];
333
393
 
334
394
  /**
335
- * A `<dependencies key="cells" like="self.<action>" />` of an agent blok: the dependencies
336
- * of one of the app's own actions, each read and called as `deps.<key>__<dependency>` and
395
+ * A `<dependencies key="cells" like="self.<action>" />` (custom blok: `agents.<name>.<action>`):
396
+ * the dependencies of one action, each read and called as `deps.<key>__<dependency>` and
337
397
  * handed to a run of that action with `with <key>`.
338
398
  */
339
399
  export type DeclaredDependencies = {
@@ -343,12 +403,23 @@ export type DeclaredDependencies = {
343
403
  like: string | null;
344
404
  };
345
405
 
346
- /** The action when `like` reads `self.<action>`, else null. */
347
- export const dependenciesAction = (declared: DeclaredDependencies): string | null => {
406
+ /**
407
+ * Whose action it names: `['self', action]` for `self.<action>`, `[key, action]` for a custom
408
+ * blok's `agents.<key>.<action>` (stored `deps.<key>.<action>`); else null.
409
+ */
410
+ export const dependenciesTarget = (declared: DeclaredDependencies): readonly [string, string] | null => {
348
411
  const parts = declared.like ? declared.like.split('.') : [];
349
- return parts.length === 2 && parts[0] === 'self' && parts[1] ? parts[1] : null;
412
+ if (parts.length === 2 && parts[0] === 'self' && parts[1]) return ['self', parts[1]];
413
+ if (parts.length === 3 && parts[0] === 'deps' && parts[1] && parts[1] !== 'self' && parts[2]) return [parts[1], parts[2]];
414
+ return null;
350
415
  };
351
416
 
417
+ /** The dependency whose action it names: `self`, or a custom blok's bound agent. */
418
+ export const dependenciesOwner = (declared: DeclaredDependencies): string | null => dependenciesTarget(declared)?.[0] ?? null;
419
+
420
+ /** The action `like` names, else null. */
421
+ export const dependenciesAction = (declared: DeclaredDependencies): string | null => dependenciesTarget(declared)?.[1] ?? null;
422
+
352
423
  /** The keyed `<dependencies>` children of a blok's `<Blok>`, in order. */
353
424
  export const declaredDependencies = (tree: BlokComponentNode | null | undefined): DeclaredDependencies[] =>
354
425
  rootChildren(tree).flatMap(child => {
package/src/bsx/expr.ts CHANGED
@@ -253,6 +253,8 @@ class Lexer {
253
253
  * is the dependency `cells__microscope` of the blok (`deps.cells__microscope`), one segment.
254
254
  */
255
255
  export const REFERENCE_SEPARATOR = '__';
256
+ /** How a custom blok writes an agent it is bound to: `agents.<key>`, stored `deps.<key>`. */
257
+ export const AGENTS_ROOT = 'agents';
256
258
  /** `cells.pick(microscope: id)`: the one call a reference itself takes. */
257
259
  export const PICK_VERB = 'pick';
258
260
 
@@ -262,10 +264,13 @@ class Parser {
262
264
  private readonly lexer: Lexer;
263
265
  private readonly tokens: Token[];
264
266
  private readonly references: ReadonlySet<string>;
267
+ /** In a custom blok: its bound agents are written `agents.<key>` (stored `deps.<key>`). */
268
+ private readonly custom: boolean;
265
269
  private index = 0;
266
270
 
267
- constructor(text: string, base: number, locator: Locator, references: ReadonlySet<string> = NO_REFERENCES) {
271
+ constructor(text: string, base: number, locator: Locator, references: ReadonlySet<string> = NO_REFERENCES, custom = false) {
268
272
  this.references = references;
273
+ this.custom = custom;
269
274
  this.lexer = new Lexer(text, base, locator);
270
275
  this.tokens = this.lexer.tokens();
271
276
  }
@@ -465,6 +470,10 @@ class Parser {
465
470
  // the blok's dependencies, `deps.cells__microscope`; `cells.pick(...)` stays as written.
466
471
  if (this.references.has(segments[0]) && segments.length > 1 && !(this.isOp('(') && segments.length === 2 && segments[1] === PICK_VERB)) {
467
472
  segments = ['deps', `${segments[0]}${REFERENCE_SEPARATOR}${segments[1]}`, ...segments.slice(2)];
473
+ } else if (this.custom && segments[0] === AGENTS_ROOT) {
474
+ segments[0] = 'deps';
475
+ } else if (this.custom && segments[0] === 'deps') {
476
+ throw this.fail('roots.custom_deps', first.offset, {path: segments.join('.')});
468
477
  }
469
478
  if (!this.isOp('(')) return {type: 'path', segments, offset: first.offset};
470
479
  this.advance();
@@ -527,26 +536,26 @@ class Parser {
527
536
  }
528
537
  }
529
538
 
530
- const parser = (text: string, base: number, locator: Locator | undefined, references?: ReadonlySet<string>): Parser => {
531
- const parsing = new Parser(text, base, locator ?? new Locator(text), references);
539
+ const parser = (text: string, base: number, locator: Locator | undefined, references?: ReadonlySet<string>, custom = false): Parser => {
540
+ const parsing = new Parser(text, base, locator ?? new Locator(text), references, custom);
532
541
  if (parsing.isEmpty()) throw parsing.fail('expr.syntax', undefined, {detail: 'the expression is empty'});
533
542
  return parsing;
534
543
  };
535
544
 
536
545
  /**
537
546
  * A value expression (no `into`). `base` is where `text` starts in the source `locator` reads;
538
- * `references` are the keys of the `<dependencies>` it may read through.
547
+ * `references` are the keys of the `<dependencies>` it may read through; `custom` says it is a custom blok's.
539
548
  */
540
- export const parseExpression = (text: string, base = 0, locator?: Locator, references?: ReadonlySet<string>): Expr => {
541
- const parsing = parser(text, base, locator, references);
549
+ export const parseExpression = (text: string, base = 0, locator?: Locator, references?: ReadonlySet<string>, custom = false): Expr => {
550
+ const parsing = parser(text, base, locator, references, custom);
542
551
  const expression = parsing.expression();
543
552
  parsing.finish();
544
553
  return expression;
545
554
  };
546
555
 
547
556
  /** An attribute's expression: a value, or a callback (`<call> into <name>`). */
548
- export const parseAttribute = (text: string, base = 0, locator?: Locator, references?: ReadonlySet<string>): Expr =>
549
- parser(text, base, locator, references).callback();
557
+ export const parseAttribute = (text: string, base = 0, locator?: Locator, references?: ReadonlySet<string>, custom = false): Expr =>
558
+ parser(text, base, locator, references, custom).callback();
550
559
 
551
560
  /** The expressions directly inside `expression`. */
552
561
  export const childrenOf = (expression: Expr): Expr[] => {
@@ -81,7 +81,7 @@ describe('local kind inference', () => {
81
81
  });
82
82
 
83
83
  it('never infers a dependency: a custom blok reading an undeclared one is refused', () => {
84
- const tree = parseBsx(blok('custom', '<Card><Text text={deps.zeta.x} /><Button onClick={deps.alpha.go()} /><Text text={deps.mid.y} /></Card>')).tree;
84
+ const tree = parseBsx(blok('custom', '<Card><Text text={agents.zeta.x} /><Button onClick={agents.alpha.go()} /><Text text={agents.mid.y} /></Card>')).tree;
85
85
  const found = checkBlokTree(tree, mountedBlokScope([], [{key: 'mid', state_dependencies: []}]), null);
86
86
  expect(found.map(finding => finding.code)).toEqual(['deps.unknown', 'deps.unknown', 'deps.unknown_state']);
87
87
  expect(found[0].message).toContain('Fix: dependencies=[AgentDependencyInput(key="zeta")].');
@@ -108,7 +108,8 @@ describe('completeBsx: components and props', () => {
108
108
  describe('completeBsx: expressions', () => {
109
109
  it('offers the roots of the kind, locals, records and namespaces', () => {
110
110
  const items = labels('<Text text={|');
111
- expect(items).toEqual(expect.arrayContaining(['deps', 'args', 'queries', 'viewer', 'speed', 'str', 'true']));
111
+ expect(items).toEqual(expect.arrayContaining(['agents', 'args', 'queries', 'viewer', 'speed', 'str', 'true']));
112
+ expect(items).not.toContain('deps');
112
113
  expect(items).not.toContain('self');
113
114
  expect(items).not.toContain('task');
114
115
  expect(items).not.toContain('event');
@@ -116,14 +117,14 @@ describe('completeBsx: expressions', () => {
116
117
  });
117
118
 
118
119
  it('walks agents: states, tasks, assets, fields, and actions only in callbacks', () => {
119
- expect(labels('<Text text={deps.|')).toEqual(['stage']);
120
- expect(labels('<Text text={deps.stage.|')).toEqual(['position', 'tasks', 'assets', 'id', 'name', 'connected']);
121
- expect(labels('<Button onClick={deps.stage.|')).toContain('move');
122
- expect(at('<Button onClick={deps.stage.|').find(item => item.label === 'move')?.insertText).toBe('move(x: ${1}, y: ${2})');
123
- expect(labels('<Text text={deps.stage.position.|')).toEqual(['x', 'y']);
124
- expect(labels('<Text text={deps.stage.tasks.|')).toEqual(['move']);
125
- expect(labels('<Text text={deps.stage.tasks.move.|')).toEqual(expect.arrayContaining(['status', 'running', 'returns', 'args']));
126
- expect(labels('<Text text={deps.stage.tasks.move.returns.|')).toEqual(['arrived']);
120
+ expect(labels('<Text text={agents.|')).toEqual(['stage']);
121
+ expect(labels('<Text text={agents.stage.|')).toEqual(['position', 'tasks', 'assets', 'id', 'name', 'connected']);
122
+ expect(labels('<Button onClick={agents.stage.|')).toContain('move');
123
+ expect(at('<Button onClick={agents.stage.|').find(item => item.label === 'move')?.insertText).toBe('move(x: ${1}, y: ${2})');
124
+ expect(labels('<Text text={agents.stage.position.|')).toEqual(['x', 'y']);
125
+ expect(labels('<Text text={agents.stage.tasks.|')).toEqual(['move']);
126
+ expect(labels('<Text text={agents.stage.tasks.move.|')).toEqual(expect.arrayContaining(['status', 'running', 'returns', 'args']));
127
+ expect(labels('<Text text={agents.stage.tasks.move.returns.|')).toEqual(['arrived']);
127
128
  });
128
129
 
129
130
  it('offers query records and refetch in a callback', () => {
@@ -145,11 +146,11 @@ describe('completeBsx: expressions', () => {
145
146
  });
146
147
 
147
148
  it('offers into names, lets and event fields where they are bound', () => {
148
- expect(labels('<Card><Button onClick={deps.stage.move(x: 1, y: 2) into run} /><Text>{run.|')).toContain('progress');
149
- expect(labels('<Card><Button onClick={deps.stage.move(x: 1, y: 2) into run} /><Text>{|')).toContain('run');
149
+ expect(labels('<Card><Button onClick={agents.stage.move(x: 1, y: 2) into run} /><Text>{run.|')).toContain('progress');
150
+ expect(labels('<Card><Button onClick={agents.stage.move(x: 1, y: 2) into run} /><Text>{|')).toContain('run');
150
151
  expect(labels('<foreach items={args.image} let="p" key={p}><Text text={|')).toContain('p');
151
- expect(labels('<Slider onChange={deps.stage.move(x: |')).toContain('event');
152
- expect(labels('<Slider onChange={deps.stage.move(x: event.|')).toEqual(['value']);
152
+ expect(labels('<Slider onChange={agents.stage.move(x: |')).toContain('event');
153
+ expect(labels('<Slider onChange={agents.stage.move(x: event.|')).toEqual(['value']);
153
154
  expect(labels('<suspense><error><Text text={|')).toContain('error');
154
155
  });
155
156
 
@@ -161,7 +162,7 @@ describe('completeBsx: expressions', () => {
161
162
  });
162
163
 
163
164
  it('offers into after a task call', () => {
164
- expect(labels('<Button onClick={deps.stage.move(x: 1, y: 2) |')).toEqual(['into']);
165
+ expect(labels('<Button onClick={agents.stage.move(x: 1, y: 2) |')).toEqual(['into']);
165
166
  expect(labels("<Text text={str.upper('|")).toEqual([]);
166
167
  });
167
168
  });
@@ -192,11 +193,11 @@ describe('analyzeBsx', () => {
192
193
  const analyze = (source: string, overrides: Partial<BlokCheckScope> = {}) => analyzeBsx(source, {scope: {...scope, ...overrides}});
193
194
 
194
195
  it('marks a finding at its prop, with its code', () => {
195
- const source = '<Blok kind="custom" context="panel"><Text text={deps.stage.speed} /></Blok>';
196
+ const source = '<Blok kind="custom" context="panel"><Text text={agents.stage.speed} /></Blok>';
196
197
  const {markers} = analyze(source);
197
198
  expect(markers).toHaveLength(1);
198
199
  expect(markers[0]).toMatchObject({code: 'deps.unknown_state', severity: 'error'});
199
- expect(source.slice(markers[0].range.start, markers[0].range.end)).toBe('deps.stage.speed');
200
+ expect(source.slice(markers[0].range.start, markers[0].range.end)).toBe('agents.stage.speed');
200
201
  });
201
202
 
202
203
  it('marks warnings as warnings', () => {
@@ -1,6 +1,6 @@
1
1
  import {defaultBlokView, innerContext, type BlokView, type SpecComponent, type SpecProp} from '../spec/catalogs';
2
2
  import {BLOK_KINDS, kindIn, loadVocabulary, type BlokContextName, type BlokKind, type VocabFunction, type VocabRecordField} from '../spec/vocabulary';
3
- import {BLOK_COMPONENT, declaredQueries, declaredSubscriptions, QUERY_COMPONENT, SUBSCRIPTION_COMPONENT} from './declared';
3
+ import {BLOK_COMPONENT, declaredQueries, declaredSubscriptions, LOGO_COMPONENT, QUERY_COMPONENT, SUBSCRIPTION_COMPONENT} from './declared';
4
4
  import {resolveLocals} from './infer';
5
5
  import {FOREACH_COMPONENT, FOREACH_INDEX_PROP, FOREACH_LET_PROP, INTO_KEYWORD} from './parse';
6
6
  import {parseBsxPartial} from './partial';
@@ -333,7 +333,8 @@ const completeTag = (env: BsxEnvironment, cursor: Extract<BsxCursor, {kind: 'tag
333
333
  if (stack.length === 0) return [blokCompletion(from)];
334
334
  const parent = view.components.get(stack[stack.length - 1].tag);
335
335
  if (parent && !parent.acceptsChildren) return [];
336
- const ancestors = stack.map(element => element.tag);
336
+ // A blok's own <logo> is drawn inside a <Logo> (`blokLogoTree`): what may sit in one may sit in it.
337
+ const ancestors = stack.flatMap(element => (element.tag === LOGO_COMPONENT ? [element.tag, 'Logo'] : [element.tag]));
337
338
  const header = headerAt(stack);
338
339
  const atRoot = stack.length === 1 && stack[0].tag === BLOK_COMPONENT;
339
340
  const declarations = new Set(Object.keys(loadVocabulary().blok.declarations));
@@ -616,7 +617,7 @@ const completeExpression = (env: BsxEnvironment, text: string, expression: strin
616
617
  if (lets.includes(first)) return [];
617
618
  if (into.includes(first)) {
618
619
  // `self.go() with cells into run`: the `with` clause sits between the call and its name.
619
- const call = new RegExp(`(?:self|deps\\.(\\w+))\\.(\\w+)\\([^)]*\\)(?:\\s+with\\s+\\w+)?\\s+${INTO_KEYWORD}\\s+${first}\\b`).exec(text);
620
+ const call = new RegExp(`(?:self|(?:deps|agents)\\.(\\w+))\\.(\\w+)\\([^)]*\\)(?:\\s+with\\s+\\w+)?\\s+${INTO_KEYWORD}\\s+${first}\\b`).exec(text);
620
621
  const dependency = call ? dependencyOf(env, call[1] ?? 'self') : undefined;
621
622
  const action = dependency?.action_dependencies?.find(candidate => candidate.key === call?.[2]);
622
623
  return taskRecord(rest, action?.demand?.return_matches);
@@ -643,6 +644,7 @@ const completeExpression = (env: BsxEnvironment, text: string, expression: strin
643
644
  case 'self':
644
645
  return agent(dependencyOf(env, 'self'), rest);
645
646
  case 'deps':
647
+ case 'agents': // a custom blok's spelling of its bound agents
646
648
  if (rest.length === 0) return dependenciesOf(env).filter(dependency => dependency.key !== 'self').map(dependency => item(dependency.key, 'dependency', 'dependency'));
647
649
  return agent(dependencyOf(env, rest[0]), rest.slice(1));
648
650
  case 'args':
@@ -784,7 +786,7 @@ export const signatureBsx = (text: string, offset: number, env: BsxEnvironment):
784
786
  };
785
787
  }
786
788
  const parts = call.callee.split('.');
787
- const target = parts[0] === 'self' && parts.length === 2 ? ['self', parts[1]] : parts[0] === 'deps' && parts.length === 3 ? [parts[1], parts[2]] : null;
789
+ const target = parts[0] === 'self' && parts.length === 2 ? ['self', parts[1]] : (parts[0] === 'deps' || parts[0] === 'agents') && parts.length === 3 ? [parts[1], parts[2]] : null;
788
790
  if (!target) return null;
789
791
  const action = dependencyOf(env, target[0])?.action_dependencies?.find(candidate => candidate.key === target[1]);
790
792
  if (!action) return null;
@@ -0,0 +1,47 @@
1
+ import {describe, expect, it} from 'vitest';
2
+ import {drawnChildren} from '../renderer/bloks/control';
3
+ import {blokLogoTree, content, declaredLogo, LOGO_VIEW_BOX} from './declared';
4
+ import {completeBsx} from './language';
5
+ import {parseBsx} from './parse';
6
+
7
+ const PANEL =
8
+ '<Blok kind="agent" context="panel"><logo title="Scope"><Circle cx="12" cy="12" r="7" /><Path d="M12 5v14" /></logo><Card><Text text="hi" /></Card></Blok>';
9
+
10
+ const props = (node: {props?: Array<{key: string; static_value?: unknown}> | null}) =>
11
+ Object.fromEntries((node.props ?? []).map(prop => [prop.key, prop.static_value]));
12
+
13
+ describe("a blok's own logo", () => {
14
+ it('draws nothing in the blok', () => {
15
+ const {tree} = parseBsx(PANEL);
16
+ expect(content(tree).map(node => node.component)).toEqual(['Card']);
17
+ expect(drawnChildren(tree).map(node => node.component)).toEqual(['Card']);
18
+ expect(declaredLogo(tree)?.component).toBe('logo');
19
+ });
20
+
21
+ it('is drawn as a logo blok of its own, with the action logos pen', () => {
22
+ const logo = blokLogoTree(parseBsx(PANEL).tree);
23
+ expect(logo).not.toBeNull();
24
+ expect(props(logo!)).toEqual({kind: 'agent', context: 'logo'});
25
+ const [drawing] = logo!.children ?? [];
26
+ expect(drawing.component).toBe('Logo');
27
+ expect(props(drawing)).toEqual({viewBox: LOGO_VIEW_BOX, title: 'Scope'});
28
+ const [pen] = drawing.children ?? [];
29
+ expect(pen.component).toBe('G');
30
+ expect(props(pen)).toMatchObject({fill: 'none', stroke: 'ink'});
31
+ expect((pen.children ?? []).map(node => node.component)).toEqual(['Circle', 'Path']);
32
+ });
33
+
34
+ it('is none when the blok declares none', () => {
35
+ expect(blokLogoTree(parseBsx('<Blok kind="agent" context="panel"><Card /></Blok>').tree)).toBeNull();
36
+ });
37
+
38
+ it('is offered at the top of a blok, and the logo shapes inside it', () => {
39
+ const atRoot = '<Blok kind="agent" context="panel"><|';
40
+ const top = completeBsx(atRoot.replace('|', ''), atRoot.indexOf('|'), {}).map(item => item.label);
41
+ expect(top).toContain('logo');
42
+ const inside = '<Blok kind="agent" context="panel"><logo><|';
43
+ const shapes = completeBsx(inside.replace('|', ''), inside.indexOf('|'), {}).map(item => item.label);
44
+ expect(shapes).toEqual(expect.arrayContaining(['Circle', 'Path']));
45
+ expect(shapes).not.toContain('Card');
46
+ });
47
+ });
package/src/bsx/parse.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  dotted,
15
15
  isLocalName,
16
16
  Locator,
17
+ AGENTS_ROOT,
17
18
  parseAttribute,
18
19
  parseExpression,
19
20
  PICK_VERB,
@@ -75,6 +76,8 @@ export const FETCH_MORE_FUNCTION = 'query.fetch_more';
75
76
  /** What `<key>.pick(<dependency>: <agent id>)` is stored as. */
76
77
  export const PICK_FUNCTION = 'deps.pick';
77
78
  const DEPENDENCIES_COMPONENT = 'dependencies';
79
+ const BLOK_COMPONENT = 'Blok';
80
+ const LIKE_PROP = 'like';
78
81
  export const QUERY_SUGAR: Readonly<Record<string, string>> = {refetch: REFETCH_FUNCTION, fetch_more: FETCH_MORE_FUNCTION};
79
82
 
80
83
  const isQuerySugar = (call: CallExpr): boolean =>
@@ -187,9 +190,14 @@ class Markup {
187
190
 
188
191
  /** The keys of the `<dependencies>` read so far: what a later expression may read through. */
189
192
  readonly references = new Set<string>();
193
+ /** Whether the root is a custom blok: its bound agents are written `agents.<key>`. */
194
+ custom = false;
190
195
 
191
196
  /** A `<dependencies key="cells" />` is read through from here on (`cells.microscope`). */
192
197
  private declares(element: MarkupElement): void {
198
+ if (element.name === BLOK_COMPONENT) {
199
+ this.custom = element.attributes.some(attribute => attribute.name === 'kind' && attribute.value === 'custom');
200
+ }
193
201
  if (element.name !== DEPENDENCIES_COMPONENT) return;
194
202
  const key = element.attributes.find(attribute => attribute.name === 'key')?.value;
195
203
  if (typeof key === 'string' && isLocalName(key)) this.references.add(key);
@@ -264,7 +272,7 @@ class Markup {
264
272
  const inner = this.source.slice(start, end);
265
273
  this.index = end + 1;
266
274
  if (!inner.trim()) throw this.fail('expr.syntax', start, {detail: `the value of ${name} is empty`});
267
- const expression = parseAttribute(inner, start, this.locator, new Set(this.references));
275
+ const expression = parseAttribute(inner, start, this.locator, new Set(this.references), this.custom);
268
276
  return {name, value: expression, offset, nameEnd, valueStart: start, end};
269
277
  }
270
278
  throw this.fail('bsx.syntax', undefined, {detail: `${name}= takes "a string" or {an expression}`});
@@ -324,7 +332,7 @@ class Markup {
324
332
  this.index = end + 1;
325
333
  const stripped = inner.trim();
326
334
  if (!stripped || (stripped.startsWith('/*') && stripped.endsWith('*/'))) continue;
327
- element.children.push({kind: 'container', expression: parseExpression(inner, start, this.locator, new Set(this.references)), offset});
335
+ element.children.push({kind: 'container', expression: parseExpression(inner, start, this.locator, new Set(this.references), this.custom), offset});
328
336
  continue;
329
337
  }
330
338
  if (this.at('}')) throw this.fail('bsx.syntax', undefined, {detail: "unexpected '}' in text; write {'}'}"});
@@ -575,6 +583,9 @@ class Lowering {
575
583
  }
576
584
  if (value === true) return {key: attribute.name, static_value: true};
577
585
  if (typeof value === 'string') {
586
+ if (attribute.name === LIKE_PROP && (component === LOCAL_COMPONENT || component === DEPENDENCIES_COMPONENT) && this.markup.custom) {
587
+ return {key: attribute.name, static_value: this.customLike(value, attribute.offset)};
588
+ }
578
589
  if ((attribute.name === FOREACH_LET_PROP || attribute.name === FOREACH_INDEX_PROP) && component === FOREACH_COMPONENT) {
579
590
  return {key: attribute.name, static_value: value, declares_value: value};
580
591
  }
@@ -585,6 +596,15 @@ class Lowering {
585
596
  return this.value(attribute.name, value, attribute.offset);
586
597
  }
587
598
 
599
+ /** A custom blok's `like="agents.<key>..."` as it is stored: `deps.<key>...`. */
600
+ private customLike(like: string, offset: number): string {
601
+ const dot = like.indexOf('.');
602
+ const root = dot < 0 ? like : like.slice(0, dot);
603
+ const rest = dot < 0 ? '' : like.slice(dot + 1);
604
+ if (root === 'deps') throw this.fail('roots.custom_deps', offset, {path: like});
605
+ return root === AGENTS_ROOT && rest ? `deps.${rest}` : like;
606
+ }
607
+
588
608
  private value(key: string, expression: Expr, offset: number): BlokComponentProp {
589
609
  switch (expression.type) {
590
610
  case 'into': {
@@ -642,7 +662,7 @@ class Lowering {
642
662
  return null;
643
663
  }
644
664
 
645
- /** A task call (`self.<action>(...)`, `deps.<key>.<action>(...)`), or null. */
665
+ /** A task call (`self.<action>(...)`, `deps.<key>.<action>(...)`; a custom blok's `agents.<key>` was read as the latter), or null. */
646
666
  private agentCall(call: CallExpr): BlokAgentCall | null {
647
667
  const {callee} = call;
648
668
  let dependency: string;
@@ -657,7 +677,6 @@ class Lowering {
657
677
  if (call.given !== undefined) throw this.fail('callback.with', call.offset);
658
678
  return null;
659
679
  }
660
- if (call.given !== undefined && dependency !== 'self') throw this.fail('callback.with', call.offset);
661
680
  const args: BlokActionArgument[] = [];
662
681
  const seen = new Set<string>();
663
682
  for (const argument of call.arguments) {
package/src/bsx/print.ts CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  TEMPLATE_FUNCTION,
23
23
  } from './parse';
24
24
  import {declaredDependencies} from './declared';
25
- import {PICK_VERB, REFERENCE_SEPARATOR} from './expr';
25
+ import {AGENTS_ROOT, PICK_VERB, REFERENCE_SEPARATOR} from './expr';
26
26
 
27
27
  /**
28
28
  * Print a stored v2 tree as BSX: the inverse of `parseBsx`, the port of
@@ -283,7 +283,10 @@ class Printer {
283
283
  }
284
284
  const value = prop.static_value;
285
285
  if (value === true) return key;
286
- if (typeof value === 'string') return `${key}=${quoted(value)}`;
286
+ if (typeof value === 'string') {
287
+ const agents = this.custom && key === 'like' && (node.component === 'local' || node.component === 'dependencies') && value.startsWith('deps.');
288
+ return `${key}=${quoted(agents ? `${AGENTS_ROOT}.${value.slice('deps.'.length)}` : value)}`;
289
+ }
287
290
  if (value !== null && typeof value === 'object' && key === CLASS_NAME) {
288
291
  return refuse(`<${node.component}> (${node.id}): a static className list reads back as str.classes`);
289
292
  }
@@ -319,6 +322,8 @@ class Printer {
319
322
 
320
323
  /** The keys of the `<dependencies>` the tree declares: what it reads through, bare. */
321
324
  references: ReadonlySet<string> = new Set();
325
+ /** Whether the tree is a custom blok: its bound agents (stored `deps.<key>`) are written `agents.<key>`. */
326
+ custom = false;
322
327
 
323
328
  /** `path` as BSX writes it: one through declared dependencies (stored `deps.cells__microscope.stage`) reads `cells.microscope.stage`. */
324
329
  private path(path: string): string {
@@ -327,6 +332,7 @@ class Printer {
327
332
  const at = parts[1].indexOf(REFERENCE_SEPARATOR);
328
333
  const key = at < 0 ? '' : parts[1].slice(0, at);
329
334
  if (at >= 0 && this.references.has(key)) return [key, parts[1].slice(at + REFERENCE_SEPARATOR.length), ...parts.slice(2)].join('.');
335
+ if (this.custom) return [AGENTS_ROOT, ...parts.slice(1)].join('.');
330
336
  }
331
337
  return path;
332
338
  }
@@ -435,6 +441,7 @@ export const printBsx = (node: BlokComponentNode, options: {view?: BlokView; ind
435
441
  const lines: string[] = [];
436
442
  const printer = new Printer(options.view ?? defaultBlokView(), options.indent ?? 2);
437
443
  printer.references = new Set(declaredDependencies(node).map(declared => declared.key));
444
+ printer.custom = node.component === 'Blok' && (node.props ?? []).some(prop => prop.key === 'kind' && prop.static_value === 'custom');
438
445
  printer.node(node, `${node.component}[0]`, 0, lines);
439
446
  return lines.join('\n');
440
447
  };
@@ -93,11 +93,11 @@ const mounted = mountedBlokScope();
93
93
 
94
94
  describe('findings', () => {
95
95
  it('name the node and prop they are about, with a filled message', () => {
96
- const {tree} = parseBsx(blok('custom', '<Card><Text text={deps.nope.x} /></Card>'));
96
+ const {tree} = parseBsx(blok('custom', '<Card><Text text={agents.nope.x} /></Card>'));
97
97
  const [found] = checkBlokTree(tree, mounted);
98
98
  expect(found).toMatchObject({code: 'deps.unknown', level: 'error', nodeId: 'Blok[0]/Card[0]/Text[0]', propKey: 'text'});
99
99
  expect(found.message).toBe(
100
- 'deps.nope.x: \'nope\' is not a dependency of the blok (its dependencies: none). Fix: dependencies=[AgentDependencyInput(key="nope")].',
100
+ 'agents.nope.x: \'nope\' is not a dependency of the blok (its dependencies: none). Fix: dependencies=[AgentDependencyInput(key="nope")].',
101
101
  );
102
102
  });
103
103
 
@@ -105,22 +105,22 @@ describe('findings', () => {
105
105
  const {tree} = parseBsx(
106
106
  blok(
107
107
  'custom',
108
- '<query name="positions" service="mikro" document="query { positions { id } }"><var key="agent" value={deps.laser.id} /></query><Card><Text text={queries.positions.status} /><Button onClick={deps.stage.move(x: 1)} /></Card>',
108
+ '<query name="positions" service="mikro" document="query { positions { id } }"><var key="agent" value={agents.laser.id} /></query><Card><Text text={queries.positions.status} /><Button onClick={agents.stage.move(x: 1)} /></Card>',
109
109
  ),
110
110
  );
111
111
  const found = checkBlokTree(tree, mountedBlokScope([], [{key: 'robot'}])).filter(finding => finding.code === 'deps.unknown');
112
112
  expect(found.map(finding => finding.message).sort()).toEqual([
113
113
  'onClick of <Button> (Blok[0]/Card[0]/Button[0]): \'stage\' is not a dependency of the blok (its dependencies: robot). Fix: dependencies=[AgentDependencyInput(key="stage")].',
114
- 'deps.laser.id: \'laser\' is not a dependency of the blok (its dependencies: robot). Fix: dependencies=[AgentDependencyInput(key="laser")].',
114
+ 'agents.laser.id: \'laser\' is not a dependency of the blok (its dependencies: robot). Fix: dependencies=[AgentDependencyInput(key="laser")].',
115
115
  ].sort());
116
116
  });
117
117
 
118
118
  it('take what the mount provides as written where the blok is mounted nowhere', () => {
119
- expect(checkBlokTree(parseBsx(blok('custom', '<Text text={deps.nope.x} /><Button onClick={deps.stage.move(x: 1)} />')).tree)).toEqual([]);
119
+ expect(checkBlokTree(parseBsx(blok('custom', '<Text text={agents.nope.x} /><Button onClick={agents.stage.move(x: 1)} />')).tree)).toEqual([]);
120
120
  });
121
121
 
122
122
  it('hint per kind what a blok reading an undeclared dependency does about it, as the spec does', () => {
123
- const message = (kind: string): string => checkBlokTree(parseBsx(blok(kind, '<Text text={deps.laser.power} />')).tree, mounted)[0]?.message ?? '';
123
+ const message = (kind: string): string => checkBlokTree(parseBsx(blok(kind, `<Text text={${kind === 'custom' ? 'agents' : 'deps'}.laser.power} />`)).tree, mounted)[0]?.message ?? '';
124
124
  expect(message('custom')).toContain('Fix: dependencies=[AgentDependencyInput(key="laser")].');
125
125
  expect(message('task')).toContain('Fix: dependencies=[AgentDependencyInput(key="laser")].');
126
126
  expect(message('action')).toContain('Fix: add a dependency parameter `laser` to the action.');