trebol-dev 0.1.1 → 0.3.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.
@@ -0,0 +1,249 @@
1
+ Trebol [
2
+ title: "The machines of a file: their states and the ways between them, read from the text with where each sits"
3
+ exports: [
4
+ machines-of fragments-of fragment-named machine-node machine-root machine-children machine-path find-machine-state
5
+ state-names state-child machine-keywords way-targets way-source way-label inside-state? fresh-state-name
6
+ ]
7
+ ]
8
+
9
+ ; A file may make machines: machine [...]. Each is read from its loaded block as the engine reads it,
10
+ ; one level at a time, but without failing: what the designer needs is where every state and way is
11
+ ; written, so that an edit changes only those values. The text stays the truth; nothing is run.
12
+ ;
13
+ ; A machine is an object: name (the word it is set to, or none), block (its loaded block), nodes and ways.
14
+ ; A fragment (retry: fragment [blanks] [body]) is read as a machine of kind fragment, its block the body
15
+ ; and spec its blanks; a state that writes use retry [with [...]] knows the fragment it uses.
16
+ ; A node is a level: the machine itself (id 1, kind machine) or a state (kind state, final or parallel),
17
+ ; known by its place among the nodes, its parent by id, so nothing holds a loop of references.
18
+ ; A way is one from: its level (the node whose block it is written in), where it starts and ends in that
19
+ ; block, its source word, and the places of the states it goes to.
20
+
21
+ machine-keywords: [data initial state final parallel from no on-enter on-exit on-activity on-save timeout ttl defer run invoke shared use]
22
+
23
+ ; words of one value after them: the index of the word is kept, its value is the next
24
+ one-value: [data initial on-enter on-exit on-activity on-save timeout ttl defer run shared]
25
+
26
+ new-node: function [m [object!] name kind [word!] parent] [
27
+ n: make object! [
28
+ id: name: kind: parent: block: holder: from: to: initial: initial-at: outcome: none
29
+ uses: use-at: with-at: none ; use retry with [...]: the fragment's name, where use and with are
30
+ children: copy []
31
+ words: copy [] ; [word index ...]: where each of its own words sits in its block
32
+ strays: copy [] ; indexes of values that are no words of machine
33
+ ]
34
+ append m/nodes n
35
+ n/id: length? m/nodes
36
+ n/name: name n/kind: kind n/parent: parent
37
+ n
38
+ ]
39
+
40
+ new-way: function [m [object!] n [object!] b [block!] i [integer!]] [
41
+ w: make object! [
42
+ id: level: block: from: to: source: kind: target-at: events: events-at: where-at: set-at: branches: branches-at: select-at: none
43
+ targets: copy [] ; [block index ...]: where each state it goes to is written
44
+ choices: copy [] ; [from to target-index ...] in the branches block: one per when, value or else
45
+ ]
46
+ append m/ways w
47
+ w/id: length? m/ways
48
+ w/level: n/id w/block: b w/from: i
49
+ w
50
+ ]
51
+
52
+ read-way: function [m [object!] n [object!] b [block!] i [integer!]] [
53
+ w: new-way m n b i
54
+ w/source: pick b i + 1
55
+ j: i + 2
56
+ w/kind: pick b j
57
+ switch/default w/kind [
58
+ to [
59
+ w/target-at: j + 1
60
+ append w/targets reduce [b j + 1]
61
+ j: j + 2
62
+ ]
63
+ choose [j: j + 1]
64
+ select [w/select-at: j + 1 j: j + 2]
65
+ ] [
66
+ w/kind: none
67
+ w/to: i + 1
68
+ return i + 2
69
+ ]
70
+ if 'on = pick b j [
71
+ e: pick b j + 1
72
+ w/events: either block? :e [copy e] [reduce [e]]
73
+ w/events-at: j
74
+ j: j + 2
75
+ ]
76
+ if all [find [choose select] w/kind block? pick b j] [
77
+ w/branches: pick b j
78
+ w/branches-at: j
79
+ read-branches w w/branches
80
+ j: j + 1
81
+ ]
82
+ if 'where = pick b j [w/where-at: j j: j + 2]
83
+ if 'set = pick b j [w/set-at: j j: j + 2]
84
+ w/to: j - 1
85
+ j
86
+ ]
87
+
88
+ ; when [...] to b [set [...]] | value to b [set [...]] | else to b [set [...]]
89
+ read-branches: function [w [object!] bs [block!]] [
90
+ k: 1
91
+ while [k <= length? bs] [
92
+ start: k
93
+ k: either 'when = pick bs k [k + 2] [k + 1]
94
+ either 'to = pick bs k [
95
+ append w/targets reduce [bs k + 1]
96
+ t: k + 1
97
+ k: k + 2
98
+ if 'set = pick bs k [k: k + 2]
99
+ append w/choices reduce [start k - 1 t]
100
+ ] [k: start + 1]
101
+ ]
102
+ ]
103
+
104
+ read-level: function [m [object!] n [object!] b [block!]] [
105
+ n/block: b
106
+ i: 1
107
+ while [i <= length? b] [
108
+ w: pick b i
109
+ case [
110
+ not word? :w [append n/strays i i: i + 1]
111
+ find [state final parallel] w [
112
+ c: new-node m pick b i + 1 w n/id
113
+ append n/children c/id
114
+ c/holder: b c/from: i
115
+ j: i + 2
116
+ if all [w = 'final word? pick b j not find machine-keywords pick b j] [c/outcome: j j: j + 1]
117
+ if block? pick b j [read-level m c pick b j j: j + 1]
118
+ c/to: j - 1
119
+ i: j
120
+ ]
121
+ w = 'from [i: read-way m n b i]
122
+ w = 'initial [n/initial: pick b i + 1 n/initial-at: i i: i + 2]
123
+ find one-value w [append n/words reduce [w i] i: i + 2]
124
+ w = 'no [append n/words reduce ['no i] i: i + 2]
125
+ w = 'use [
126
+ append n/words reduce ['use i]
127
+ n/uses: pick b i + 1 n/use-at: i
128
+ i: i + 2
129
+ if 'with = pick b i [append n/words reduce ['use-with i] n/with-at: i i: i + 2]
130
+ ]
131
+ w = 'invoke [
132
+ append n/words reduce ['invoke i]
133
+ i: i + 2
134
+ if 'for = pick b i [append n/words reduce ['for i] i: i + 4]
135
+ if 'with = pick b i [append n/words reduce ['with i] i: i + 2]
136
+ ]
137
+ true [append n/strays i i: i + 1]
138
+ ]
139
+ ]
140
+ ]
141
+
142
+ read-machine: function [name b [block!] /fragment spec [block!]] [
143
+ m: make object! [name: block: spec: none kind: 'machine nodes: copy [] ways: copy []]
144
+ m/name: name m/block: b
145
+ if fragment [m/kind: 'fragment m/spec: spec]
146
+ root: new-node m any [name 'machine] 'machine none
147
+ read-level m root b
148
+ m
149
+ ]
150
+
151
+ find-machines: function [code [block! paren!] out [block!] /local b s] [
152
+ name: none
153
+ parse code [any [
154
+ set name set-word! 'machine set b block! (append out read-machine to word! name b)
155
+ | set name set-word! 'fragment set s block! set b block! (append out read-machine/fragment to word! name b s)
156
+ | 'machine set b block! (append out read-machine none b)
157
+ | set b [block! | paren!] (find-machines b out)
158
+ | skip
159
+ ]]
160
+ ]
161
+
162
+ machines-of: function [
163
+ "The machines and fragments a design's file makes, in the order they are written"
164
+ d [object!]
165
+ ] [
166
+ out: copy []
167
+ find-machines d/values out
168
+ out
169
+ ]
170
+
171
+ fragments-of: function ["The fragments among machines read from a file" ms [block!]] [
172
+ collect [foreach m ms [if m/kind = 'fragment [keep m]]]
173
+ ]
174
+
175
+ fragment-named: function ["The fragment of that name among machines read from a file, or none" ms [block!] name] [
176
+ foreach m ms [if all [m/kind = 'fragment m/name = name] [return m]]
177
+ none
178
+ ]
179
+
180
+ machine-node: function ["A node of a machine by its id" m [object!] id [integer!]] [pick m/nodes id]
181
+ machine-root: function ["The machine itself, the level its top words are written in" m [object!]] [first m/nodes]
182
+
183
+ machine-children: function ["The nodes inside a node, in the order they are written" m [object!] id [integer!]] [
184
+ collect [foreach c select pick m/nodes id 'children [keep pick m/nodes c]]
185
+ ]
186
+
187
+ state-child: function [m [object!] id [integer!] name] [
188
+ foreach c select pick m/nodes id 'children [if name = select pick m/nodes c 'name [return c]]
189
+ none
190
+ ]
191
+
192
+ find-machine-state: function [
193
+ "The id of the state a name or path means, looked up from a level and then from each level around it, as the engine does"
194
+ m [object!] scope [integer!] name
195
+ ] [
196
+ names: either path? :name [to block! name] [reduce [:name]]
197
+ while [scope] [
198
+ id: scope
199
+ foreach w names [unless id: state-child m id w [break]]
200
+ if id [return id]
201
+ scope: select pick m/nodes scope 'parent
202
+ ]
203
+ none
204
+ ]
205
+
206
+ machine-path: function ["The names from the machine down to a state: [work waiting]" m [object!] id [integer!]] [
207
+ out: copy []
208
+ while [id <> 1] [
209
+ n: pick m/nodes id
210
+ insert out n/name
211
+ id: n/parent
212
+ ]
213
+ out
214
+ ]
215
+
216
+ inside-state?: function ["Whether a node is a state or inside it" m [object!] id [integer!] state [integer!]] [
217
+ while [id] [
218
+ if id = state [return true]
219
+ id: select pick m/nodes id 'parent
220
+ ]
221
+ false
222
+ ]
223
+
224
+ state-names: function ["Every state's name, at every level" m [object!]] [
225
+ collect [foreach n next m/nodes [keep n/name]]
226
+ ]
227
+
228
+ fresh-state-name: function ["A name no state of the machine has: state-2 after state" m [object!] base [word!]] [
229
+ names: state-names m
230
+ unless find names base [return base]
231
+ k: 2
232
+ while [find names to word! rejoin [base "-" k]] [k: k + 1]
233
+ to word! rejoin [base "-" k]
234
+ ]
235
+
236
+ way-source: function ["The id of the state a way leaves, or none when it names none here" m [object!] w [object!]] [
237
+ state-child m w/level w/source
238
+ ]
239
+
240
+ way-targets: function ["The ids of the states a way can go to, none for those it names wrong" m [object!] w [object!]] [
241
+ collect [foreach [b k] w/targets [keep find-machine-state m w/level pick b k]]
242
+ ]
243
+
244
+ way-label: function ["What a drawing writes on a way: its events, then where or choose" w [object!]] [
245
+ t: either w/events [form w/events] [copy ""]
246
+ if w/where-at [append t either empty? t ["[where]"] [" [where]"]]
247
+ if all [empty? t w/kind = 'choose] [t: "choose"]
248
+ t
249
+ ]
package/app/model.trb CHANGED
@@ -6,7 +6,7 @@ Trebol [
6
6
  set-face-text set-face-name face-label style-word toggle-flag
7
7
  layout-of head-end block-span indent-at after-line shown-faces
8
8
  pane-of own-block written-range values-at inside? set-screen screens-data add-screen piece? set-piece-label add-piece
9
- set-face-label set-face-global
9
+ set-face-label set-face-global more-on-line? blank? line-start
10
10
  ]
11
11
  ]
12
12
 
@@ -0,0 +1,130 @@
1
+ Trebol [
2
+ title: "The designer's properties: what each control of a face's options and handlers does to the text"
3
+ ]
4
+
5
+ ; Run by app.trb (do), so it shares the app's words: d, the-face, edit, prop-entries.
6
+
7
+ ; what a control of the properties did: the k-th option (a group of entries), or 0 for the
8
+ ; texts, what it follows and handlers
9
+ prop-act: function [k [integer!] what [word!] value] [
10
+ g: either k > 0 [pick prop-entries k] [none]
11
+ if what = 'check [return either g [prop-check g value] [true]]
12
+ unless f: the-face [exit]
13
+ e: all [g first g]
14
+ ; typing goes on in the control: the panel is laid out again only for a choice or a removal
15
+ if find [values code text hint is calc react event action label screen-name screen-title screen-args piece-label] what [set 'keep-props true]
16
+ ; a picked icon shows in the panel: laid out again
17
+ t: switch what [
18
+ flag [either value [set-option d f e none] [remove-option d f e]]
19
+ choice [set-option d f e reduce [to word! value]]
20
+ icon [prop-values f g mold to issue! form value]
21
+ custom [either value/2 [set-option/rule d f e none value/1] [remove-option/rule d f e value/1]]
22
+ values [prop-values f g value]
23
+ code [
24
+ either empty? trim copy value [remove-option d f e] [
25
+ b: attempt [load value]
26
+ either block? b [set-option d f e reduce [b]] [none]
27
+ ]
28
+ ]
29
+ remove [
30
+ either e/how = 'custom [
31
+ ; every rule of a program the face has goes
32
+ foreach w custom-rule-words [
33
+ if option-of/rule face-parts d f e w [write-text remove-option/rule d f e w f: the-face]
34
+ ]
35
+ none
36
+ ] [
37
+ q: group-part face-parts d f g
38
+ either q [remove-option d f q/2] [none]
39
+ ]
40
+ ]
41
+ text [set-face-text d f value]
42
+ hint [set-hint d f value]
43
+ is calc react [
44
+ b: attempt [load value]
45
+ set-reaction d f what either all [block? b not empty? b] [b] [none]
46
+ ]
47
+ label [
48
+ w: all [string? value not empty? trim copy value attempt [load value]]
49
+ case [
50
+ none? w [set-face-label d f none]
51
+ word? w [set-face-label d f w]
52
+ true [none]
53
+ ]
54
+ ]
55
+ global [set-face-global d f value]
56
+ screen-name [w: attempt [load value] either word? w [set-screen d f 'name w] [none]]
57
+ screen-title [set-screen d f 'title value]
58
+ screen-args [
59
+ w: attempt [load/all value]
60
+ either all [block? w parse w [any word!]] [set-screen d f 'args w] [none]
61
+ ]
62
+ add-screen [add-screen d f]
63
+ piece-label [set-piece-label d f value]
64
+ add-piece [add-piece d f value]
65
+ action [
66
+ b: all [string? value not empty? trim copy value attempt [load value]]
67
+ set-action d f either all [block? b not empty? b] [b] [none]
68
+ ]
69
+ event [
70
+ b: all [string? value/2 not empty? trim copy value/2 attempt [load value/2]]
71
+ either block? b [set-event d f value/1 b] [remove-event d f value/1]
72
+ ]
73
+ ]
74
+ either t [edit t] [set 'keep-props false]
75
+ ]
76
+
77
+ ; what is typed for an option, as the values of the entry of its group that takes them, or none
78
+ typed-as: function [g [block!] value [string!]] [
79
+ vals: attempt [load/all value]
80
+ unless block? vals [return none]
81
+ foreach e g [
82
+ case [
83
+ find [name label] e/how [if all [1 = length? vals word? first vals] [return reduce [e vals]]]
84
+ ; a block is typed as it is shown: [1 2 1]
85
+ e/how = 'block [if all [1 = length? vals block? first vals] [return reduce [e vals]]]
86
+ true [
87
+ vs: vals
88
+ ; a text is typed as it is shown, with or without its quotes
89
+ if all [find e/args 'text not string? first vals] [vs: reduce [value]]
90
+ if all [(length? vs) = length? e/args args-take? e/args vs] [return reduce [e vs]]
91
+ ]
92
+ ]
93
+ ]
94
+ none
95
+ ]
96
+
97
+ args-take?: function [args [block!] vals [block!]] [
98
+ repeat i length? args [
99
+ a: pick args i v: pick vals i
100
+ ok: case [
101
+ a = 'text [any [string? :v map? :v lit-word? :v]]
102
+ 'one-of = first a [all [word? :v to logic! find either word? a/2 [get a/2] [a/2] v]]
103
+ true [
104
+ rule: copy []
105
+ foreach t a [unless empty? rule [append rule '|] append rule t]
106
+ parse reduce [:v] rule
107
+ ]
108
+ ]
109
+ unless ok [return false]
110
+ ]
111
+ true
112
+ ]
113
+
114
+ prop-check: function [g [block!] value] [
115
+ if any [not string? value empty? trim copy value typed-as g value] [return true]
116
+ m: copy ""
117
+ foreach e g [unless empty? m [append m " or "] append m type-of-args e]
118
+ rejoin ["it takes " m]
119
+ ]
120
+
121
+ ; values typed for an option: written when they are what it takes, taken out when emptied
122
+ prop-values: function [f g [block!] value [string!]] [
123
+ q: group-part face-parts d f g
124
+ if empty? trim copy value [return either q [remove-option d f q/2] [none]]
125
+ unless t: typed-as g value [return none]
126
+ e: t/1 vals: t/2
127
+ if e/how = 'name [return set-face-name d f first vals]
128
+ ; written in another of its ways: in place of it
129
+ either all [q not same? q/2 e] [set-option/over d f e vals q/1] [set-option d f e vals]
130
+ ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trebol-dev",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "The visual designer for Trebol: lays out screens with Trebol's faces and writes the Trebol code back, keeping yours as you wrote it.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -34,10 +34,11 @@
34
34
  "scripts": {
35
35
  "test": "node --test && trebol test app",
36
36
  "start": "node bin/trebol-dev.js",
37
- "build:editor": "esbuild editor/trebol-code.js --bundle --minify --format=esm --target=es2022 --legal-comments=eof --outfile=app/trebol-code.js"
37
+ "build:editor": "esbuild editor/trebol-code.js --bundle --minify --format=esm --target=es2022 --legal-comments=eof --outfile=app/trebol-code.js",
38
+ "build:graph": "esbuild editor/machine-graph.js --bundle --minify --format=esm --target=es2022 --legal-comments=eof --outfile=app/machine-graph.js && { printf '/*! elkjs 0.12.1, https://github.com/kieler/elkjs, EPL-2.0 OR GPL-3.0-or-later */\\n'; cat node_modules/elkjs/lib/elk-worker.min.js; } > app/elk-worker.js"
38
39
  },
39
40
  "dependencies": {
40
- "trebol": "^0.3.1"
41
+ "trebol": "^0.5.0"
41
42
  },
42
43
  "devDependencies": {
43
44
  "@codemirror/commands": "^6.11.1",
@@ -46,6 +47,7 @@
46
47
  "@codemirror/state": "^6.7.6",
47
48
  "@codemirror/view": "^6.43.15",
48
49
  "@lezer/highlight": "^1.2.5",
50
+ "elkjs": "^0.12.1",
49
51
  "esbuild": "^0.28.2"
50
52
  }
51
53
  }
package/server/files.js CHANGED
@@ -4,7 +4,8 @@
4
4
  // itself may ask: the Host must be a local name (no DNS rebinding) and requests carry the
5
5
  // X-Trebol-Dev header, which a page of another site cannot send without the server agreeing.
6
6
 
7
- import { readFile, writeFile, readdir, realpath } from 'node:fs/promises';
7
+ import { createHash } from 'node:crypto';
8
+ import { readFile, writeFile, readdir, realpath, rename, rm } from 'node:fs/promises';
8
9
  import { basename, dirname, extname, relative, resolve, sep } from 'node:path';
9
10
 
10
11
  /** Folders never listed nor read: tools' output and other people's code. */
@@ -61,11 +62,37 @@ export async function listFiles(root) {
61
62
  return out.sort();
62
63
  }
63
64
 
64
- function send(res, status, body, type = 'text/plain; charset=utf-8') {
65
- res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
65
+ function send(res, status, body, type = 'text/plain; charset=utf-8', more = {}) {
66
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store', ...more });
66
67
  res.end(body);
67
68
  }
68
69
 
70
+ /** The version of a file's text: the SHA-256 of its UTF-8 bytes, in lowercase hex. */
71
+ export function versionOf(text) {
72
+ return createHash('sha256').update(text, 'utf8').digest('hex');
73
+ }
74
+
75
+ /** The version a save says it read (?base=), lowercase, or null when it names none. */
76
+ function baseOf(url) {
77
+ const b = url.searchParams.get('base');
78
+ return b === null || b.trim() === '' ? null : b.trim().toLowerCase();
79
+ }
80
+
81
+ /**
82
+ * Writes text to path all at once: into a file beside it, then renamed over it, so a reader
83
+ * never sees half of it and a failed write leaves the old file whole.
84
+ */
85
+ async function writeWhole(path, text) {
86
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
87
+ try {
88
+ await writeFile(tmp, text, 'utf8');
89
+ await rename(tmp, path);
90
+ } catch (e) {
91
+ await rm(tmp, { force: true });
92
+ throw e;
93
+ }
94
+ }
95
+
69
96
  async function bodyOf(req) {
70
97
  const chunks = [];
71
98
  let size = 0;
@@ -77,15 +104,18 @@ async function bodyOf(req) {
77
104
  return Buffer.concat(chunks).toString('utf8');
78
105
  }
79
106
 
80
- /** Answers /api/files and /api/file; gives false for every other request. */
107
+ /**
108
+ * Answers /api/files.json (the listing, which on a page of trebol build is the static file
109
+ * app/api/files.json saying demo) and /api/file; gives false for every other request.
110
+ */
81
111
  export async function handleApi(req, res, url) {
82
- if (url.pathname !== '/api/files' && url.pathname !== '/api/file') return false;
112
+ if (url.pathname !== '/api/files.json' && url.pathname !== '/api/file') return false;
83
113
  if (!trusted(req)) {
84
114
  send(res, 403, 'Only the designer may ask for the files of the project.');
85
115
  return true;
86
116
  }
87
117
  const root = projectRoot();
88
- if (url.pathname === '/api/files') {
118
+ if (url.pathname === '/api/files.json') {
89
119
  if (req.method !== 'GET') return send(res, 405, 'GET only'), true;
90
120
  send(res, 200, JSON.stringify({ name: basename(root), files: await listFiles(root) }), 'application/json');
91
121
  return true;
@@ -98,12 +128,22 @@ export async function handleApi(req, res, url) {
98
128
  if (req.method === 'GET') {
99
129
  const text = await readFile(path, 'utf8').catch(() => null);
100
130
  if (text === null) send(res, 404, 'No such file.');
101
- else send(res, 200, text);
131
+ else send(res, 200, text, undefined, { etag: `"${versionOf(text)}"` });
102
132
  } else if (req.method === 'PUT') {
103
133
  const text = await bodyOf(req);
104
134
  if (text === null) return send(res, 413, 'Too big.'), true;
105
- await writeFile(path, text, 'utf8');
106
- send(res, 200, 'Saved.');
135
+ // base names the version the designer read: when the file changed since, the edit made
136
+ // outside is not lost, the designer is told and asks the person
137
+ const base = baseOf(url);
138
+ if (base !== null) {
139
+ const now = await readFile(path, 'utf8').catch(() => null);
140
+ if (now === null || versionOf(now) !== base) {
141
+ const more = now === null ? {} : { etag: `"${versionOf(now)}"` };
142
+ return send(res, 412, now === null ? 'The file is gone.' : 'The file changed since it was read.', undefined, more), true;
143
+ }
144
+ }
145
+ await writeWhole(path, text);
146
+ send(res, 200, 'Saved.', undefined, { etag: `"${versionOf(text)}"` });
107
147
  } else {
108
148
  send(res, 405, 'GET or PUT only');
109
149
  }