@volter/dawproject 0.5.67
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.
- package/LICENSE +202 -0
- package/README.md +32 -0
- package/package.json +33 -0
- package/src/index.ts +191 -0
- package/src/notation.ts +107 -0
- package/src/perform.ts +206 -0
- package/src/piece.ts +277 -0
- package/src/render.ts +240 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Volter AI, Inc.
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# @volter/dawproject
|
|
2
|
+
|
|
3
|
+
A piece of music as a React component. The elements are DAWproject's (the open
|
|
4
|
+
interchange format Bitwig and PreSonus publish): `Project`, `Transport`, `Track`,
|
|
5
|
+
`Channel`, `Send`, `Device`, `Clip`, `Note`, `Marker`, `Points`, `Point`. A
|
|
6
|
+
reconciler (`render.ts`, the shape of `@pixi/react`) mounts the component into a
|
|
7
|
+
plain graph, and `readPiece` (`piece.ts`) reads the graph as a piece. Nothing in
|
|
8
|
+
a piece imports anything but this package and its own modules.
|
|
9
|
+
|
|
10
|
+
```tsx
|
|
11
|
+
<Track name="Flute">
|
|
12
|
+
<Channel volume={-3} pan={0.15}>
|
|
13
|
+
<Device plugin="soundfont" params={{ bank: BANK, program: 73 }} />
|
|
14
|
+
<Send to="Hall" level={-14} />
|
|
15
|
+
</Channel>
|
|
16
|
+
<Clip at="1" bars={8}>
|
|
17
|
+
<Note at="1:1" pitch="F#5" dur="h" vel={0.6} />
|
|
18
|
+
<Note at="1:3" pitch="E5" dur="q" artic="legato" />
|
|
19
|
+
</Clip>
|
|
20
|
+
</Track>
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Written units (`notation.ts`): `at` is an absolute `bar:beat`, `pitch` a note
|
|
24
|
+
name, `dur` a note value (`w h q 8 16 32`, dots, `t` for triplets). A `<Clip>`
|
|
25
|
+
takes `at` and `bars`; the transport takes `tempo` and `meter`.
|
|
26
|
+
|
|
27
|
+
`perform(piece)` (`perform.ts`) is the one performance both the editor's
|
|
28
|
+
preview and the export play: the tempo map (`<Points target="tempo">`, beats to
|
|
29
|
+
seconds), articulations, controller lanes sampled into events, and the
|
|
30
|
+
`humanize` device's seeded drift.
|
|
31
|
+
|
|
32
|
+
Apache-2.0. A piece carries this package when it ships.
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@volter/dawproject",
|
|
3
|
+
"author": "Volter AI, Inc.",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"version": "0.5.67",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"description": "A piece of music as React elements named for DAWproject's own model (Project, Transport, Track, Channel, Device, Clip, Note, Marker), and the renderer that mounts one into a plain graph.",
|
|
10
|
+
"type": "module",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/volter-ai/editor.git",
|
|
14
|
+
"directory": "packages/dawproject"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"src",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./src/index.ts",
|
|
22
|
+
"./*": "./src/*.ts"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"react-reconciler": "0.31.0"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"react": "^19.0.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A PIECE OF MUSIC IS A REACT COMPONENT whose elements are DAWproject's own model
|
|
3
|
+
* (github.com/bitwig/dawproject, `Project.xsd`) — the same nouns — written in a composer's
|
|
4
|
+
* units (`./notation`): positions as `bar:beat`, pitches as note names, lengths as note values.
|
|
5
|
+
* A piece imports these and nothing of the editor:
|
|
6
|
+
*
|
|
7
|
+
* ```tsx
|
|
8
|
+
* import { Channel, Clip, Device, Note, Project, Track, Transport } from '@volter/dawproject';
|
|
9
|
+
*
|
|
10
|
+
* export default function Theme() {
|
|
11
|
+
* return (
|
|
12
|
+
* <Project>
|
|
13
|
+
* <Transport tempo={96} meter="4/4" />
|
|
14
|
+
* <Track name="Lead">
|
|
15
|
+
* <Channel volume={-6} pan={0} />
|
|
16
|
+
* <Clip at="1" bars={2}>
|
|
17
|
+
* <Note at="1:1" pitch="E4" dur="q" vel={0.8} />
|
|
18
|
+
* <Note at="1:2.5" pitch="F#4" dur="8" />
|
|
19
|
+
* </Clip>
|
|
20
|
+
* </Track>
|
|
21
|
+
* </Project>
|
|
22
|
+
* );
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Positions are ABSOLUTE bars of the piece; a clip is a region of the arrangement, and every
|
|
27
|
+
* note inside it states the bar it sounds in.
|
|
28
|
+
*
|
|
29
|
+
* Each export is the element's TYPE NAME, a string, so the elements carry no identity of
|
|
30
|
+
* this module: the renderer (`./render`) recognizes them by name wherever the piece's copy
|
|
31
|
+
* of this package was resolved from. DAWproject's `Note` spells its key `key`, which React
|
|
32
|
+
* reserves, so the note name is `pitch`.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import type { FC, ReactNode } from 'react';
|
|
36
|
+
|
|
37
|
+
/** A position in the piece: `bar` or `bar:beat`, both counted from 1 (`9:2.5`). */
|
|
38
|
+
export type Position = string;
|
|
39
|
+
/** A note value: `w h q 8 16 32`, dots, `t` for a triplet; or a number of quarter-note beats. */
|
|
40
|
+
export type Length = string | number;
|
|
41
|
+
|
|
42
|
+
export interface ProjectProps {
|
|
43
|
+
readonly children?: ReactNode;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** DAWproject `Transport`: `Tempo` in BPM and `TimeSignature` as `n/d` (default `4/4`). */
|
|
47
|
+
export interface TransportProps {
|
|
48
|
+
readonly tempo: number;
|
|
49
|
+
readonly meter?: string;
|
|
50
|
+
/** A tempo lane: `<Points target="tempo">`. */
|
|
51
|
+
readonly children?: ReactNode;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** DAWproject `Track`: a named lane that owns a channel and its clips. */
|
|
55
|
+
export interface TrackProps {
|
|
56
|
+
readonly name: string;
|
|
57
|
+
readonly color?: string;
|
|
58
|
+
readonly children?: ReactNode;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* DAWproject `Channel`: the mixer strip. `volume` is in decibels, `pan` in −1…1. `role` is the
|
|
63
|
+
* schema's: `regular` (a track's own strip, the default), `effect` (a bus other channels send to,
|
|
64
|
+
* such as a reverb), `submix` (a group track's strip: the tracks inside that `<Track>` sum into
|
|
65
|
+
* it), or `master` (the one strip everything ends in).
|
|
66
|
+
*/
|
|
67
|
+
export interface ChannelProps {
|
|
68
|
+
readonly role?: 'regular' | 'effect' | 'master' | 'submix';
|
|
69
|
+
readonly volume?: number;
|
|
70
|
+
readonly pan?: number;
|
|
71
|
+
readonly mute?: boolean;
|
|
72
|
+
readonly solo?: boolean;
|
|
73
|
+
readonly children?: ReactNode;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** DAWproject `Send`: this channel feeds the `effect` channel of the track named `to`, at `level` dB. */
|
|
77
|
+
export interface SendProps {
|
|
78
|
+
readonly to: string;
|
|
79
|
+
readonly level: number;
|
|
80
|
+
/** Taken before the fader (`pre`) rather than after it (the default). */
|
|
81
|
+
readonly pre?: boolean;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A device parameter: a number, a string, a switch, or a list of them (an equaliser's bands). */
|
|
85
|
+
export type DeviceParam =
|
|
86
|
+
| number
|
|
87
|
+
| string
|
|
88
|
+
| boolean
|
|
89
|
+
| readonly Readonly<Record<string, number | string | boolean>>[]
|
|
90
|
+
| Readonly<Record<string, number>>;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* DAWproject `Device`: an instrument or effect on a channel, named by its plugin. The built-in
|
|
94
|
+
* effects take the schema's own device types: `equalizer` (`bands`: `{ type: 'highPass' | 'lowPass'
|
|
95
|
+
* | 'lowShelf' | 'highShelf' | 'bell', freq, gain?, q? }`), `compressor` (`threshold`, `ratio`,
|
|
96
|
+
* `attack`, `release`, `knee`, `makeup`), `limiter` (`ceiling`, `release`), and `convolution`
|
|
97
|
+
* (`ir`: a project path to an impulse response WAV, `predelay` ms, `wet` 0–1).
|
|
98
|
+
*
|
|
99
|
+
* The instrument is `soundfont` (`bank`: a project path to an .sf2/.sf3, `program`, `bankNumber`,
|
|
100
|
+
* `drums`). Its `articulations` maps a note's `artic` to the program in the same bank that plays
|
|
101
|
+
* it, where the bank records that articulation apart (`{ staccato: 101, pizzicato: 102 }`): a
|
|
102
|
+
* note with a mapped `artic` sounds on that patch, every other note on `program`.
|
|
103
|
+
*/
|
|
104
|
+
export interface DeviceProps {
|
|
105
|
+
readonly plugin: string;
|
|
106
|
+
readonly name?: string;
|
|
107
|
+
/** The plugin's own parameters, by the plugin's own names. */
|
|
108
|
+
readonly params?: Readonly<Record<string, DeviceParam>>;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** DAWproject `Clip`: a region of a track's timeline, from bar `at` for `bars` bars. */
|
|
112
|
+
export interface ClipProps {
|
|
113
|
+
readonly at: Position;
|
|
114
|
+
readonly bars: number;
|
|
115
|
+
readonly name?: string;
|
|
116
|
+
readonly children?: ReactNode;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* DAWproject `Note`: a note name at a position for a length. `vel` and `rel` are 0…1. `artic` is
|
|
121
|
+
* how it is played: `staccato`, `staccatissimo`, `tenuto`, `accent`, `marcato` or `legato`, or a
|
|
122
|
+
* technique a sampled instrument records apart, `pizzicato` or `tremolo`. A soundfont device's
|
|
123
|
+
* `articulations` names the patch that plays each (see `DeviceProps`).
|
|
124
|
+
*/
|
|
125
|
+
export interface NoteProps {
|
|
126
|
+
readonly at: Position;
|
|
127
|
+
readonly pitch: string;
|
|
128
|
+
readonly dur: Length;
|
|
129
|
+
readonly vel?: number;
|
|
130
|
+
readonly rel?: number;
|
|
131
|
+
readonly artic?: 'staccato' | 'staccatissimo' | 'tenuto' | 'accent' | 'marcato' | 'legato' | 'pizzicato' | 'tremolo';
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* DAWproject `Points`: an automation lane. In a `<Clip>`, `target` is a MIDI controller
|
|
136
|
+
* (`cc1` modulation, `cc11` expression, `cc64` sustain, …) or `pitchbend`, with values 0–1
|
|
137
|
+
* (pitch bend −1…1). In `<Transport>`, `target="tempo"` and values are BPM.
|
|
138
|
+
*/
|
|
139
|
+
export interface PointsProps {
|
|
140
|
+
readonly target: string;
|
|
141
|
+
readonly children?: ReactNode;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A point on a lane. Values move linearly to the next point unless the point `hold`s. */
|
|
145
|
+
export interface PointProps {
|
|
146
|
+
readonly at: Position;
|
|
147
|
+
readonly value: number;
|
|
148
|
+
readonly hold?: boolean;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** DAWproject `Marker`: a named point on the arrangement's timeline. */
|
|
152
|
+
export interface MarkerProps {
|
|
153
|
+
readonly at: Position;
|
|
154
|
+
readonly name: string;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function element<P>(name: string): FC<P> {
|
|
158
|
+
return name as unknown as FC<P>;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export const Project = element<ProjectProps>('dawproject.Project');
|
|
162
|
+
export const Transport = element<TransportProps>('dawproject.Transport');
|
|
163
|
+
export const Track = element<TrackProps>('dawproject.Track');
|
|
164
|
+
export const Channel = element<ChannelProps>('dawproject.Channel');
|
|
165
|
+
export const Send = element<SendProps>('dawproject.Send');
|
|
166
|
+
export const Device = element<DeviceProps>('dawproject.Device');
|
|
167
|
+
export const Clip = element<ClipProps>('dawproject.Clip');
|
|
168
|
+
export const Note = element<NoteProps>('dawproject.Note');
|
|
169
|
+
export const Marker = element<MarkerProps>('dawproject.Marker');
|
|
170
|
+
export const Points = element<PointsProps>('dawproject.Points');
|
|
171
|
+
export const Point = element<PointProps>('dawproject.Point');
|
|
172
|
+
|
|
173
|
+
/** Every element this package names, keyed by its short name. */
|
|
174
|
+
export const ELEMENT_TYPES = {
|
|
175
|
+
Project: 'dawproject.Project',
|
|
176
|
+
Transport: 'dawproject.Transport',
|
|
177
|
+
Track: 'dawproject.Track',
|
|
178
|
+
Channel: 'dawproject.Channel',
|
|
179
|
+
Send: 'dawproject.Send',
|
|
180
|
+
Device: 'dawproject.Device',
|
|
181
|
+
Clip: 'dawproject.Clip',
|
|
182
|
+
Note: 'dawproject.Note',
|
|
183
|
+
Marker: 'dawproject.Marker',
|
|
184
|
+
Points: 'dawproject.Points',
|
|
185
|
+
Point: 'dawproject.Point',
|
|
186
|
+
} as const;
|
|
187
|
+
|
|
188
|
+
export type ElementName = keyof typeof ELEMENT_TYPES;
|
|
189
|
+
|
|
190
|
+
/** The written units' spellings, for code that generates notes (`at={formatAt(beat, 4)}`). */
|
|
191
|
+
export { beatAt, beatsOf, formatAt, formatDuration, formatPitch, midiOf } from './notation';
|
package/src/notation.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE WRITTEN UNITS a piece is authored in: positions as `bar:beat`, pitches as note names,
|
|
3
|
+
* lengths as note values, meter as `n/d`. These are a composer's units and the ones a language
|
|
4
|
+
* model writes with the fewest slips (a format experiment on one brief: first drafts in these
|
|
5
|
+
* units carried about 17 voice-leading faults against 24–27 in beats and MIDI numbers). The
|
|
6
|
+
* reader (`piece.ts`) turns them into beats and MIDI keys; the editor writes them back with
|
|
7
|
+
* `formatAt`, `formatPitch` and `formatDuration`, so a gesture leaves the spelling a person reads.
|
|
8
|
+
*
|
|
9
|
+
* Positions are ABSOLUTE: `9:2.5` is the second half of beat 2 of bar 9 of the piece, wherever
|
|
10
|
+
* the note's clip starts. A clip is a region of the arrangement, not a second bar count.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const LETTER: Record<string, number> = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
|
|
14
|
+
const SHARP_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
|
|
15
|
+
const FLAT_NAMES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
|
|
16
|
+
|
|
17
|
+
/** `C4` = 60 (scientific pitch); accidentals `#`, `b`, `##`, `bb`. */
|
|
18
|
+
export function midiOf(name: string): number {
|
|
19
|
+
const match = /^([A-Ga-g])(##|bb|#|b)?(-?\d)$/.exec(name.trim());
|
|
20
|
+
if (!match) throw new Error(`Not a note name: "${name}" (write it like F#5, Bb3, C4)`);
|
|
21
|
+
const [, letter = 'C', accidental = '', octave = '4'] = match;
|
|
22
|
+
const shift = accidental === '#' ? 1 : accidental === '##' ? 2 : accidental === 'b' ? -1 : accidental === 'bb' ? -2 : 0;
|
|
23
|
+
return (Number(octave) + 1) * 12 + (LETTER[letter.toUpperCase()] ?? 0) + shift;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A MIDI key as a note name, spelled with flats when `flats` (a key on the flat side). */
|
|
27
|
+
export function formatPitch(midi: number, flats = false): string {
|
|
28
|
+
const names = flats ? FLAT_NAMES : SHARP_NAMES;
|
|
29
|
+
return `${names[((midi % 12) + 12) % 12]}${Math.floor(midi / 12) - 1}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Whether a written pitch uses a flat: a gesture keeps the spelling family it found. */
|
|
33
|
+
export function spelledFlat(name: string): boolean {
|
|
34
|
+
return /^[A-Ga-g]b/.test(name.trim());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const VALUE: Record<string, number> = { w: 4, h: 2, q: 1, '8': 0.5, '16': 0.25, '32': 0.125 };
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A note value in quarter-note beats: `w h q 8 16 32`, a dot per `.` (`q.` = 1.5), `t` for a
|
|
41
|
+
* triplet (`8t` = 1/3). A plain positive number is beats (`2.5`, for a tie across values).
|
|
42
|
+
*/
|
|
43
|
+
export function beatsOf(value: string | number): number {
|
|
44
|
+
if (typeof value === 'number') {
|
|
45
|
+
if (value > 0 && Number.isFinite(value)) return value;
|
|
46
|
+
throw new Error(`Not a length: ${value}`);
|
|
47
|
+
}
|
|
48
|
+
const match = /^(w|h|q|8|16|32)(t?)(\.*)$/.exec(value.trim());
|
|
49
|
+
if (!match) {
|
|
50
|
+
const number = Number(value);
|
|
51
|
+
if (Number.isFinite(number) && number > 0) return number;
|
|
52
|
+
throw new Error(`Not a note value: "${value}" (w h q 8 16 32, a dot per ".", t for triplet, or beats)`);
|
|
53
|
+
}
|
|
54
|
+
const [, base = 'q', triplet = '', dots = ''] = match;
|
|
55
|
+
let beats = VALUE[base] ?? 1;
|
|
56
|
+
if (triplet) beats = (beats * 2) / 3;
|
|
57
|
+
let add = beats;
|
|
58
|
+
for (let i = 0; i < dots.length; i++) {
|
|
59
|
+
add /= 2;
|
|
60
|
+
beats += add;
|
|
61
|
+
}
|
|
62
|
+
return beats;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Beats as the plainest note value that spells them exactly, else the number of beats. */
|
|
66
|
+
export function formatDuration(beats: number): string {
|
|
67
|
+
const candidates: [string, number][] = [];
|
|
68
|
+
for (const base of ['w', 'h', 'q', '8', '16', '32']) {
|
|
69
|
+
for (const dots of ['', '.', '..']) {
|
|
70
|
+
candidates.push([`${base}${dots}`, beatsOf(`${base}${dots}`)]);
|
|
71
|
+
}
|
|
72
|
+
candidates.push([`${base}t`, beatsOf(`${base}t`)]);
|
|
73
|
+
}
|
|
74
|
+
const exact = candidates.find(([, value]) => Math.abs(value - beats) < 1e-9);
|
|
75
|
+
return exact ? exact[0] : String(Math.round(beats * 1e6) / 1e6);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Quarter-note beats per bar: `4/4` → 4, `3/4` → 3, `6/8` → 3. */
|
|
79
|
+
export function beatsPerBarOf(meter: string): number {
|
|
80
|
+
const match = /^(\d+)\/(\d+)$/.exec(meter.trim());
|
|
81
|
+
if (!match) throw new Error(`Not a meter: "${meter}" (write it like 3/4)`);
|
|
82
|
+
return (Number(match[1]) * 4) / Number(match[2]);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `bar` or `bar:beat` (1-based; the beat may be fractional) to beats from the piece's start. */
|
|
86
|
+
export function beatAt(position: string | number, beatsPerBar: number): number {
|
|
87
|
+
const text = String(position).trim();
|
|
88
|
+
const match = /^(\d+)(?::(\d+(?:\.\d+)?))?$/.exec(text);
|
|
89
|
+
if (!match) throw new Error(`Not a position: "${text}" (write bar:beat, like 9:2.5)`);
|
|
90
|
+
const bar = Number(match[1]);
|
|
91
|
+
const beat = match[2] === undefined ? 1 : Number(match[2]);
|
|
92
|
+
if (bar < 1 || beat < 1 || beat >= beatsPerBar + 1 - 1e-9) {
|
|
93
|
+
throw new Error(`"${text}" is not in a ${beatsPerBar}-beat bar (bars and beats count from 1)`);
|
|
94
|
+
}
|
|
95
|
+
return (bar - 1) * beatsPerBar + (beat - 1);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Beats from the piece's start as `bar:beat`. A note always spells its beat (`9:1`); a clip or
|
|
100
|
+
* marker on a downbeat is just its bar (`bar: true` → `9`).
|
|
101
|
+
*/
|
|
102
|
+
export function formatAt(beats: number, beatsPerBar: number, options: { readonly bar?: boolean } = {}): string {
|
|
103
|
+
const rounded = Math.round(beats * 1e6) / 1e6;
|
|
104
|
+
const bar = Math.floor(rounded / beatsPerBar + 1e-9) + 1;
|
|
105
|
+
const beat = Math.round((rounded - (bar - 1) * beatsPerBar + 1) * 1e6) / 1e6;
|
|
106
|
+
return options.bar && beat === 1 ? String(bar) : `${bar}:${beat}`;
|
|
107
|
+
}
|
package/src/perform.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE PERFORMANCE: what a piece's written notes become when played. One pure function, read by
|
|
3
|
+
* the editor's engine and by the export alike, so the two can never disagree about what sounds:
|
|
4
|
+
*
|
|
5
|
+
* - the TEMPO MAP (`<Points target="tempo">` in `<Transport>`): beats to seconds, linear ramps
|
|
6
|
+
* between points unless a point holds;
|
|
7
|
+
* - ARTICULATIONS (`artic` on a note): staccato, staccatissimo, tenuto, accent, marcato and
|
|
8
|
+
* legato shape length and velocity; every note keeps its `artic`, so an instrument that
|
|
9
|
+
* records one apart (`articulations` on its device) plays it on that patch;
|
|
10
|
+
* - CONTROLLER LANES (`<Points target="cc11">` in a clip): sampled into controller events;
|
|
11
|
+
* - HUMANISING (`<Device plugin="humanize">` on a channel): seeded, so every render is the same,
|
|
12
|
+
* and CORRELATED (a slow random walk, not independent jitter per note), because a player who is
|
|
13
|
+
* late stays late for a while and listeners prefer that (Hennig et al., PLoS ONE 2011);
|
|
14
|
+
* - the same pitch struck again while it still sounds cuts the earlier note just before, so the
|
|
15
|
+
* second note is not choked by the first one's release (a sampler trap music-engine measured).
|
|
16
|
+
*
|
|
17
|
+
* Nothing here is invented for a piece: every value comes from its source.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { Piece, PiecePoints } from './piece';
|
|
21
|
+
|
|
22
|
+
export interface PerformedNote {
|
|
23
|
+
readonly track: string;
|
|
24
|
+
/** The written start, in beats: which section a note belongs to (`start` may drift across it). */
|
|
25
|
+
readonly beat: number;
|
|
26
|
+
readonly start: number;
|
|
27
|
+
readonly end: number;
|
|
28
|
+
readonly pitch: number;
|
|
29
|
+
readonly velocity: number;
|
|
30
|
+
/** How it is played (`staccato`, `pizzicato`, …), or `null`. */
|
|
31
|
+
readonly artic: string | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface PerformedControl {
|
|
35
|
+
readonly track: string;
|
|
36
|
+
/** MIDI controller number, or `pitchbend`. */
|
|
37
|
+
readonly controller: number | 'pitchbend';
|
|
38
|
+
readonly time: number;
|
|
39
|
+
/** 0–1 for a controller; −1…1 for pitch bend. */
|
|
40
|
+
readonly value: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface Performance {
|
|
44
|
+
readonly notes: readonly PerformedNote[];
|
|
45
|
+
readonly controls: readonly PerformedControl[];
|
|
46
|
+
/** Seconds at a beat (the tempo map). */
|
|
47
|
+
readonly secondsAt: (beat: number) => number;
|
|
48
|
+
/** Beat at a second (its inverse). */
|
|
49
|
+
readonly beatAt: (seconds: number) => number;
|
|
50
|
+
/** Seconds the piece lasts. */
|
|
51
|
+
readonly seconds: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface TempoSegment {
|
|
55
|
+
readonly beat: number;
|
|
56
|
+
readonly bpm: number;
|
|
57
|
+
readonly nextBeat: number;
|
|
58
|
+
readonly nextBpm: number;
|
|
59
|
+
readonly startSeconds: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Seconds from `from` to `from + span` beats over a tempo that moves linearly from `a` to `b` BPM. */
|
|
63
|
+
function segmentSeconds(span: number, a: number, b: number, length: number): number {
|
|
64
|
+
if (span <= 0) return 0;
|
|
65
|
+
if (Math.abs(b - a) < 1e-9 || length <= 0) return (span * 60) / a;
|
|
66
|
+
// bpm(x) = a + (b - a) x / length; seconds = ∫ 60 / bpm dx
|
|
67
|
+
const k = (b - a) / length;
|
|
68
|
+
return (60 / k) * Math.log((a + k * span) / a);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function tempoMap(piece: Piece): { secondsAt(beat: number): number; beatAt(seconds: number): number } {
|
|
72
|
+
const lane = piece.transport.tempoPoints;
|
|
73
|
+
const points = [...(lane?.points ?? [])].sort((x, y) => x.time - y.time);
|
|
74
|
+
if (points.length === 0 || (points[0]?.time ?? 0) > 0) points.unshift({ id: 'tempo:0', oid: null, time: 0, value: piece.transport.tempo, hold: true });
|
|
75
|
+
const segments: TempoSegment[] = [];
|
|
76
|
+
let seconds = 0;
|
|
77
|
+
for (let i = 0; i < points.length; i++) {
|
|
78
|
+
const point = points[i]!;
|
|
79
|
+
const next = points[i + 1];
|
|
80
|
+
const nextBeat = next ? next.time : Number.POSITIVE_INFINITY;
|
|
81
|
+
const nextBpm = next && !point.hold ? next.value : point.value;
|
|
82
|
+
segments.push({ beat: point.time, bpm: point.value, nextBeat, nextBpm, startSeconds: seconds });
|
|
83
|
+
if (next) seconds += segmentSeconds(next.time - point.time, point.value, nextBpm, next.time - point.time);
|
|
84
|
+
}
|
|
85
|
+
const secondsAt = (beat: number): number => {
|
|
86
|
+
let segment = segments[0]!;
|
|
87
|
+
for (const candidate of segments) if (candidate.beat <= beat) segment = candidate;
|
|
88
|
+
const length = Number.isFinite(segment.nextBeat) ? segment.nextBeat - segment.beat : 0;
|
|
89
|
+
return segment.startSeconds + segmentSeconds(beat - segment.beat, segment.bpm, segment.nextBpm, length);
|
|
90
|
+
};
|
|
91
|
+
const beatAt = (target: number): number => {
|
|
92
|
+
let low = 0;
|
|
93
|
+
let high = 1;
|
|
94
|
+
while (secondsAt(high) < target) high *= 2;
|
|
95
|
+
for (let i = 0; i < 60; i++) {
|
|
96
|
+
const middle = (low + high) / 2;
|
|
97
|
+
if (secondsAt(middle) < target) low = middle;
|
|
98
|
+
else high = middle;
|
|
99
|
+
}
|
|
100
|
+
return (low + high) / 2;
|
|
101
|
+
};
|
|
102
|
+
return { secondsAt, beatAt };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Deterministic PRNG (mulberry32): the same seed gives the same performance. */
|
|
106
|
+
function random(seed: number): () => number {
|
|
107
|
+
let state = seed >>> 0;
|
|
108
|
+
return () => {
|
|
109
|
+
state = (state + 0x6d2b79f5) >>> 0;
|
|
110
|
+
let t = state;
|
|
111
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
112
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
113
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A slow, bounded random walk sampled per note: correlated drift, not jitter. */
|
|
118
|
+
function drift(seed: number, count: number, amount: number): number[] {
|
|
119
|
+
const next = random(seed);
|
|
120
|
+
const out: number[] = [];
|
|
121
|
+
let value = 0;
|
|
122
|
+
for (let i = 0; i < count; i++) {
|
|
123
|
+
value = value * 0.8 + (next() * 2 - 1) * 0.45;
|
|
124
|
+
out.push(Math.max(-1, Math.min(1, value)) * amount);
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const ARTICULATION: Record<string, { length: number; velocity: number; overlap?: number }> = {
|
|
130
|
+
staccato: { length: 0.5, velocity: 0.05 },
|
|
131
|
+
staccatissimo: { length: 0.25, velocity: 0.08 },
|
|
132
|
+
tenuto: { length: 1, velocity: 0.03 },
|
|
133
|
+
accent: { length: 0.9, velocity: 0.15 },
|
|
134
|
+
marcato: { length: 0.75, velocity: 0.22 },
|
|
135
|
+
legato: { length: 1, velocity: 0, overlap: 0.06 },
|
|
136
|
+
// Techniques, not shapes: written length and velocity; the patch plays them.
|
|
137
|
+
pizzicato: { length: 1, velocity: 0 },
|
|
138
|
+
tremolo: { length: 1, velocity: 0 },
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** Where every written note and lane of the piece sounds, in seconds. */
|
|
142
|
+
export function perform(piece: Piece): Performance {
|
|
143
|
+
const { secondsAt, beatAt } = tempoMap(piece);
|
|
144
|
+
const notes: PerformedNote[] = [];
|
|
145
|
+
const controls: PerformedControl[] = [];
|
|
146
|
+
for (const track of piece.tracks) {
|
|
147
|
+
const humanize = track.channel?.devices.find((device) => device.plugin === 'humanize');
|
|
148
|
+
const timingMs = typeof humanize?.params['timingMs'] === 'number' ? humanize.params['timingMs'] : 0;
|
|
149
|
+
const velocityAmount = typeof humanize?.params['velocity'] === 'number' ? humanize.params['velocity'] : 0;
|
|
150
|
+
const seed = typeof humanize?.params['seed'] === 'number' ? humanize.params['seed'] : 1;
|
|
151
|
+
const written = track.clips.flatMap((clip) => clip.notes).sort((a, b) => a.start - b.start || a.pitch - b.pitch);
|
|
152
|
+
const timeDrift = drift(seed, written.length, timingMs / 1000);
|
|
153
|
+
const velocityDrift = drift(seed + 7919, written.length, velocityAmount);
|
|
154
|
+
const performed = written.map((note, index) => {
|
|
155
|
+
const shape = note.artic ? ARTICULATION[note.artic] : undefined;
|
|
156
|
+
const start = secondsAt(note.start) + (timeDrift[index] ?? 0);
|
|
157
|
+
const writtenEnd = secondsAt(note.start + note.duration);
|
|
158
|
+
const length = (writtenEnd - secondsAt(note.start)) * (shape?.length ?? 1) + (shape?.overlap ?? 0);
|
|
159
|
+
return {
|
|
160
|
+
track: track.id,
|
|
161
|
+
beat: note.start,
|
|
162
|
+
start: Math.max(0, start),
|
|
163
|
+
end: Math.max(0, start) + Math.max(0.02, length),
|
|
164
|
+
pitch: note.pitch,
|
|
165
|
+
velocity: Math.max(0.01, Math.min(1, note.vel + (shape?.velocity ?? 0) + (velocityDrift[index] ?? 0))),
|
|
166
|
+
artic: note.artic,
|
|
167
|
+
};
|
|
168
|
+
});
|
|
169
|
+
// A pitch struck again while it sounds: end the earlier note 12 ms before the new one.
|
|
170
|
+
for (let i = 0; i < performed.length; i++) {
|
|
171
|
+
for (let j = i + 1; j < performed.length; j++) {
|
|
172
|
+
const earlier = performed[i]!;
|
|
173
|
+
const later = performed[j]!;
|
|
174
|
+
if (later.start >= earlier.end) break;
|
|
175
|
+
if (later.pitch === earlier.pitch && later.start > earlier.start) {
|
|
176
|
+
performed[i] = { ...earlier, end: Math.max(earlier.start + 0.02, later.start - 0.012) };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
notes.push(...performed);
|
|
181
|
+
for (const clip of track.clips) {
|
|
182
|
+
for (const lane of clip.lanes) controls.push(...sampleLane(track.id, lane, secondsAt));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const seconds = secondsAt(piece.length);
|
|
186
|
+
return { notes, controls, secondsAt, beatAt, seconds };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A lane's points as controller events: every point, plus linear steps between them (1/16 beat). */
|
|
190
|
+
function sampleLane(track: string, lane: PiecePoints, secondsAt: (beat: number) => number): PerformedControl[] {
|
|
191
|
+
const controller = lane.target === 'pitchbend' ? 'pitchbend' : Number(/^cc(\d+)$/.exec(lane.target)?.[1] ?? Number.NaN);
|
|
192
|
+
if (controller !== 'pitchbend' && !Number.isInteger(controller)) return [];
|
|
193
|
+
const points = [...lane.points].sort((a, b) => a.time - b.time);
|
|
194
|
+
const out: PerformedControl[] = [];
|
|
195
|
+
for (let i = 0; i < points.length; i++) {
|
|
196
|
+
const point = points[i]!;
|
|
197
|
+
const next = points[i + 1];
|
|
198
|
+
out.push({ track, controller, time: secondsAt(point.time), value: point.value });
|
|
199
|
+
if (!next || point.hold) continue;
|
|
200
|
+
for (let beat = point.time + 0.25; beat < next.time - 1e-9; beat += 0.25) {
|
|
201
|
+
const t = (beat - point.time) / (next.time - point.time);
|
|
202
|
+
out.push({ track, controller, time: secondsAt(beat), value: point.value + (next.value - point.value) * t });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
package/src/piece.ts
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE PIECE, READ: a mounted graph ({@link DawNode}) as the arrangement a DAW shows. Tracks
|
|
3
|
+
* with their channel, devices and clips; clips with their notes; transport and markers. Times
|
|
4
|
+
* stay in beats; a note's `start` is its clip's `time` plus its own.
|
|
5
|
+
*
|
|
6
|
+
* Nothing here decides what may be edited. A node carries the source element it came from
|
|
7
|
+
* (`oid`); whether a given prop of that element is a literal the editor may write is the
|
|
8
|
+
* source's answer, read at the element (the editor's source index), never guessed here. The one
|
|
9
|
+
* fact the graph itself knows is REPETITION: when one source element rendered several nodes
|
|
10
|
+
* (a `.map()`, a loop, a component used twice), those nodes share an oid, and no single one of
|
|
11
|
+
* them is that element's own.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { DeviceParam } from './index';
|
|
15
|
+
import { beatAt, beatsOf, beatsPerBarOf, midiOf } from './notation';
|
|
16
|
+
import type { DawNode } from './render';
|
|
17
|
+
|
|
18
|
+
export interface PieceTransport {
|
|
19
|
+
readonly tempo: number;
|
|
20
|
+
readonly numerator: number;
|
|
21
|
+
readonly denominator: number;
|
|
22
|
+
/** Quarter-note beats per bar (`6/8` → 3). */
|
|
23
|
+
readonly beatsPerBar: number;
|
|
24
|
+
readonly oid: string | null;
|
|
25
|
+
/** The tempo lane (`<Points target="tempo">`), or `null` for one tempo throughout. */
|
|
26
|
+
readonly tempoPoints: PiecePoints | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface PieceNote {
|
|
30
|
+
readonly id: string;
|
|
31
|
+
readonly oid: string | null;
|
|
32
|
+
/** Start in beats from the piece's start. */
|
|
33
|
+
readonly start: number;
|
|
34
|
+
/** Start in beats from its clip's start. */
|
|
35
|
+
readonly time: number;
|
|
36
|
+
readonly duration: number;
|
|
37
|
+
readonly pitch: number;
|
|
38
|
+
readonly vel: number;
|
|
39
|
+
/** How it is played (`staccato`, `legato`, …), or `null`. */
|
|
40
|
+
readonly artic: string | null;
|
|
41
|
+
/** As written: `at`, `pitch` and `dur` exactly as the source spells them. */
|
|
42
|
+
readonly written: { readonly at: string; readonly pitch: string; readonly dur: string };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface PiecePoint {
|
|
46
|
+
readonly id: string;
|
|
47
|
+
readonly oid: string | null;
|
|
48
|
+
/** Beats from the piece's start. */
|
|
49
|
+
readonly time: number;
|
|
50
|
+
readonly value: number;
|
|
51
|
+
readonly hold: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* An automation lane: in a clip a controller (`cc11`) or `pitchbend`; on the transport `tempo`; on
|
|
56
|
+
* a track its mixer (`volume`, `pan`, `send:<bus>`).
|
|
57
|
+
*/
|
|
58
|
+
export interface PiecePoints {
|
|
59
|
+
readonly id: string;
|
|
60
|
+
readonly oid: string | null;
|
|
61
|
+
readonly target: string;
|
|
62
|
+
readonly points: readonly PiecePoint[];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface PieceClip {
|
|
66
|
+
readonly id: string;
|
|
67
|
+
readonly oid: string | null;
|
|
68
|
+
readonly name: string | null;
|
|
69
|
+
readonly time: number;
|
|
70
|
+
readonly duration: number;
|
|
71
|
+
readonly notes: readonly PieceNote[];
|
|
72
|
+
readonly lanes: readonly PiecePoints[];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface PieceDevice {
|
|
76
|
+
readonly id: string;
|
|
77
|
+
readonly oid: string | null;
|
|
78
|
+
readonly plugin: string;
|
|
79
|
+
readonly name: string | null;
|
|
80
|
+
readonly params: Readonly<Record<string, DeviceParam>>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface PieceSend {
|
|
84
|
+
readonly oid: string | null;
|
|
85
|
+
/** The name of the track whose `effect` channel this feeds. */
|
|
86
|
+
readonly to: string;
|
|
87
|
+
readonly level: number;
|
|
88
|
+
readonly pre: boolean;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface PieceChannel {
|
|
92
|
+
readonly oid: string | null;
|
|
93
|
+
/** `submix`: a group track's channel, summing the tracks it contains (DAWproject's role). */
|
|
94
|
+
readonly role: 'regular' | 'effect' | 'master' | 'submix';
|
|
95
|
+
readonly volume: number;
|
|
96
|
+
readonly pan: number;
|
|
97
|
+
readonly mute: boolean;
|
|
98
|
+
readonly solo: boolean;
|
|
99
|
+
readonly devices: readonly PieceDevice[];
|
|
100
|
+
readonly sends: readonly PieceSend[];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface PieceTrack {
|
|
104
|
+
readonly id: string;
|
|
105
|
+
readonly oid: string | null;
|
|
106
|
+
readonly name: string;
|
|
107
|
+
readonly color: string | null;
|
|
108
|
+
readonly channel: PieceChannel | null;
|
|
109
|
+
readonly clips: readonly PieceClip[];
|
|
110
|
+
/**
|
|
111
|
+
* The track's own automation across the arrangement (`<Points>` children of `<Track>`, outside
|
|
112
|
+
* any clip): `volume` and `send:<bus>` in dB, `pan` −1…1. Points in piece time.
|
|
113
|
+
*/
|
|
114
|
+
readonly lanes: readonly PiecePoints[];
|
|
115
|
+
/** The group track this one sits in (its `submix` channel sums this track), or `null`. */
|
|
116
|
+
readonly parent: string | null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface PieceMarker {
|
|
120
|
+
readonly id: string;
|
|
121
|
+
readonly oid: string | null;
|
|
122
|
+
readonly time: number;
|
|
123
|
+
readonly name: string;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface Piece {
|
|
127
|
+
readonly transport: PieceTransport;
|
|
128
|
+
readonly tracks: readonly PieceTrack[];
|
|
129
|
+
readonly markers: readonly PieceMarker[];
|
|
130
|
+
/** The last beat any clip reaches. */
|
|
131
|
+
readonly length: number;
|
|
132
|
+
/** How many nodes each oid rendered; above 1 means the element repeats. */
|
|
133
|
+
readonly oidCounts: ReadonlyMap<string, number>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function num(value: unknown, fallback: number): number {
|
|
137
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function str(value: unknown): string | null {
|
|
141
|
+
return typeof value === 'string' ? value : null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function bool(value: unknown): boolean {
|
|
145
|
+
return value === true;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function countOids(node: DawNode, counts: Map<string, number>): void {
|
|
149
|
+
if (node.oid) counts.set(node.oid, (counts.get(node.oid) ?? 0) + 1);
|
|
150
|
+
for (const child of node.children) countOids(child, counts);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Read a mounted graph as a piece. Refuses a root that is not a `<Project>`. */
|
|
154
|
+
export function readPiece(root: DawNode): Piece {
|
|
155
|
+
if (root.type !== 'Project') throw new Error(`A piece's root is <Project>; this one is <${root.type}>.`);
|
|
156
|
+
const oidCounts = new Map<string, number>();
|
|
157
|
+
countOids(root, oidCounts);
|
|
158
|
+
// The transport first: every position in the piece is read against its meter.
|
|
159
|
+
const transportNode = root.children.find((node) => node.type === 'Transport');
|
|
160
|
+
const meter = str(transportNode?.props['meter']) ?? '4/4';
|
|
161
|
+
const beatsPerBar = beatsPerBarOf(meter);
|
|
162
|
+
const [numerator = 4, denominator = 4] = meter.split('/').map(Number);
|
|
163
|
+
const transport: PieceTransport = {
|
|
164
|
+
tempo: num(transportNode?.props['tempo'], 120),
|
|
165
|
+
numerator,
|
|
166
|
+
denominator,
|
|
167
|
+
beatsPerBar,
|
|
168
|
+
oid: transportNode?.oid ?? null,
|
|
169
|
+
tempoPoints: null,
|
|
170
|
+
};
|
|
171
|
+
const position = (value: unknown, where: string): number => {
|
|
172
|
+
if (typeof value !== 'string' && typeof value !== 'number') throw new Error(`${where} has no \`at\` position.`);
|
|
173
|
+
return beatAt(value, beatsPerBar);
|
|
174
|
+
};
|
|
175
|
+
const readLane = (node: DawNode, id: string, where: string): PiecePoints => ({
|
|
176
|
+
id,
|
|
177
|
+
oid: node.oid,
|
|
178
|
+
target: str(node.props['target']) ?? '',
|
|
179
|
+
points: node.children
|
|
180
|
+
.filter((point) => point.type === 'Point')
|
|
181
|
+
.map((point, index) => ({
|
|
182
|
+
id: `${id}:point:${index}`,
|
|
183
|
+
oid: point.oid,
|
|
184
|
+
time: position(point.props['at'], `A <Point> in ${where}`),
|
|
185
|
+
value: num(point.props['value'], 0),
|
|
186
|
+
hold: bool(point.props['hold']),
|
|
187
|
+
})),
|
|
188
|
+
});
|
|
189
|
+
const tempoNode = transportNode?.children.find((node) => node.type === 'Points' && node.props['target'] === 'tempo');
|
|
190
|
+
const withTempo: PieceTransport = tempoNode ? { ...transport, tempoPoints: readLane(tempoNode, 'transport:tempo', '<Transport>') } : transport;
|
|
191
|
+
const tracks: PieceTrack[] = [];
|
|
192
|
+
const markers: PieceMarker[] = [];
|
|
193
|
+
let length = 0;
|
|
194
|
+
/**
|
|
195
|
+
* A track, and (after it) every track it contains: a group's children sum into its strip, the
|
|
196
|
+
* group's channel `role="submix"`. `parent` is the group track's id.
|
|
197
|
+
*/
|
|
198
|
+
const readTrack = (node: DawNode, trackId: string, parent: string | null): void => {
|
|
199
|
+
const trackName = str(node.props['name']) ?? `Track ${tracks.length + 1}`;
|
|
200
|
+
let channel: PieceChannel | null = null;
|
|
201
|
+
const clips: PieceClip[] = [];
|
|
202
|
+
const trackLanes: PiecePoints[] = [];
|
|
203
|
+
node.children.forEach((child, childIndex) => {
|
|
204
|
+
if (child.type === 'Channel') {
|
|
205
|
+
const role = str(child.props['role']);
|
|
206
|
+
channel = {
|
|
207
|
+
oid: child.oid,
|
|
208
|
+
role: role === 'effect' || role === 'master' || role === 'submix' ? role : 'regular',
|
|
209
|
+
sends: child.children
|
|
210
|
+
.filter((send) => send.type === 'Send')
|
|
211
|
+
.map((send) => ({ oid: send.oid, to: str(send.props['to']) ?? '', level: num(send.props['level'], 0), pre: bool(send.props['pre']) })),
|
|
212
|
+
volume: num(child.props['volume'], 0),
|
|
213
|
+
pan: num(child.props['pan'], 0),
|
|
214
|
+
mute: bool(child.props['mute']),
|
|
215
|
+
solo: bool(child.props['solo']),
|
|
216
|
+
devices: child.children
|
|
217
|
+
.filter((device) => device.type === 'Device')
|
|
218
|
+
.map((device, deviceIndex) => ({
|
|
219
|
+
id: `${trackId}:device:${deviceIndex}`,
|
|
220
|
+
oid: device.oid,
|
|
221
|
+
plugin: str(device.props['plugin']) ?? '',
|
|
222
|
+
name: str(device.props['name']),
|
|
223
|
+
params: (device.props['params'] ?? {}) as Record<string, DeviceParam>,
|
|
224
|
+
})),
|
|
225
|
+
};
|
|
226
|
+
} else if (child.type === 'Clip') {
|
|
227
|
+
const clipId = `${trackId}:clip:${childIndex}`;
|
|
228
|
+
const clipName = str(child.props['name']);
|
|
229
|
+
const where = `<Clip${clipName ? ` "${clipName}"` : ''}> on ${trackName}`;
|
|
230
|
+
const time = position(child.props['at'], where);
|
|
231
|
+
const duration = num(child.props['bars'], 0) * beatsPerBar;
|
|
232
|
+
const notes: PieceNote[] = child.children
|
|
233
|
+
.filter((note) => note.type === 'Note')
|
|
234
|
+
.map((note, noteIndex) => {
|
|
235
|
+
const writtenPitch = String(note.props['pitch'] ?? '');
|
|
236
|
+
const writtenDur = note.props['dur'];
|
|
237
|
+
const start = position(note.props['at'], `A <Note> in ${where}`);
|
|
238
|
+
return {
|
|
239
|
+
id: `${clipId}:note:${noteIndex}`,
|
|
240
|
+
oid: note.oid,
|
|
241
|
+
start,
|
|
242
|
+
time: start - time,
|
|
243
|
+
duration: beatsOf(typeof writtenDur === 'number' ? writtenDur : String(writtenDur ?? '')),
|
|
244
|
+
pitch: midiOf(writtenPitch),
|
|
245
|
+
vel: num(note.props['vel'], 0.7),
|
|
246
|
+
artic: str(note.props['artic']),
|
|
247
|
+
written: { at: String(note.props['at'] ?? ''), pitch: writtenPitch, dur: String(writtenDur ?? '') },
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
const lanes = child.children
|
|
251
|
+
.filter((lane) => lane.type === 'Points')
|
|
252
|
+
.map((lane, laneIndex) => readLane(lane, `${clipId}:lane:${laneIndex}`, where));
|
|
253
|
+
length = Math.max(length, time + duration);
|
|
254
|
+
clips.push({ id: clipId, oid: child.oid, name: clipName, time, duration, notes, lanes });
|
|
255
|
+
} else if (child.type === 'Points') {
|
|
256
|
+
trackLanes.push(readLane(child, `${trackId}:lane:${childIndex}`, `<Track "${trackName}">`));
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
tracks.push({ id: trackId, oid: node.oid, name: trackName, color: str(node.props['color']), channel, clips, lanes: trackLanes, parent });
|
|
260
|
+
for (const [childIndex, child] of node.children.entries()) {
|
|
261
|
+
if (child.type === 'Track') readTrack(child, `${trackId}/track:${childIndex}`, trackId);
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
root.children.forEach((node, index) => {
|
|
265
|
+
if (node.type === 'Marker') {
|
|
266
|
+
markers.push({ id: `marker:${index}`, oid: node.oid, time: position(node.props['at'], 'A <Marker>'), name: str(node.props['name']) ?? '' });
|
|
267
|
+
} else if (node.type === 'Track') {
|
|
268
|
+
readTrack(node, `track:${index}`, null);
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
return { transport: withTempo, tracks, markers, length, oidCounts };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Seconds per beat at the piece's tempo (a constant tempo; tempo automation is not read yet). */
|
|
275
|
+
export function secondsPerBeat(piece: Piece): number {
|
|
276
|
+
return 60 / piece.transport.tempo;
|
|
277
|
+
}
|
package/src/render.ts
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE RENDERER: mounts a piece (a React component of `@volter/dawproject` elements) into a
|
|
3
|
+
* plain graph of {@link DawNode}s, the way `@pixi/react` mounts a world into Pixi containers.
|
|
4
|
+
* The graph is plain data, so it crosses any realm and any worker unchanged.
|
|
5
|
+
*
|
|
6
|
+
* The editor stamps every JSX element of a project module with its source address (`data-oid`,
|
|
7
|
+
* `@volter/editor-react`'s transform, in the editor's served graph only). The stamp arrives here
|
|
8
|
+
* as an ordinary prop; each node keeps it as {@link DawNode.oid} and drops it from `props`, so a
|
|
9
|
+
* node knows the exact source element it came from. A standalone render has no stamps and every
|
|
10
|
+
* `oid` is `null`.
|
|
11
|
+
*
|
|
12
|
+
* The host config is `@pixi/react`'s shape (react-reconciler 0.31 on React 19): mutation mode,
|
|
13
|
+
* no text, no suspense, and every commit publishes a fresh snapshot to the root's listeners.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { ComponentType, ReactNode } from 'react';
|
|
17
|
+
import { createElement } from 'react';
|
|
18
|
+
import Reconciler from 'react-reconciler';
|
|
19
|
+
import { ConcurrentRoot, DefaultEventPriority } from 'react-reconciler/constants.js';
|
|
20
|
+
|
|
21
|
+
export const OID_PROP = 'data-oid';
|
|
22
|
+
const TYPE_PREFIX = 'dawproject.';
|
|
23
|
+
|
|
24
|
+
export interface DawNode {
|
|
25
|
+
/** The element's short name: `Project`, `Track`, `Clip`, `Note`, … */
|
|
26
|
+
readonly type: string;
|
|
27
|
+
readonly props: Readonly<Record<string, unknown>>;
|
|
28
|
+
/** The source element this node was rendered from, or `null` outside the editor. */
|
|
29
|
+
readonly oid: string | null;
|
|
30
|
+
readonly children: readonly DawNode[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface Instance {
|
|
34
|
+
type: string;
|
|
35
|
+
props: Record<string, unknown>;
|
|
36
|
+
oid: string | null;
|
|
37
|
+
children: Instance[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface Container {
|
|
41
|
+
children: Instance[];
|
|
42
|
+
onCommit: () => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function ownProps(props: Record<string, unknown>): { props: Record<string, unknown>; oid: string | null } {
|
|
46
|
+
const out: Record<string, unknown> = {};
|
|
47
|
+
let oid: string | null = null;
|
|
48
|
+
for (const [key, value] of Object.entries(props)) {
|
|
49
|
+
if (key === 'children') continue;
|
|
50
|
+
if (key === OID_PROP) {
|
|
51
|
+
oid = typeof value === 'string' ? value : null;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
out[key] = value;
|
|
55
|
+
}
|
|
56
|
+
return { props: out, oid };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function shortType(type: string): string {
|
|
60
|
+
if (!type.startsWith(TYPE_PREFIX)) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
`<${type}> is not a DAWproject element. A piece renders only @volter/dawproject's elements (Project, Transport, Track, Channel, Device, Clip, Note, Marker) and components made of them.`,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
return type.slice(TYPE_PREFIX.length);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function remove<T>(list: T[], item: T): void {
|
|
69
|
+
const index = list.indexOf(item);
|
|
70
|
+
if (index >= 0) list.splice(index, 1);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function insert<T>(list: T[], item: T, before: T): void {
|
|
74
|
+
remove(list, item);
|
|
75
|
+
const index = list.indexOf(before);
|
|
76
|
+
list.splice(index < 0 ? list.length : index, 0, item);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let currentUpdatePriority = 0;
|
|
80
|
+
|
|
81
|
+
const reconciler = Reconciler({
|
|
82
|
+
isPrimaryRenderer: false,
|
|
83
|
+
noTimeout: -1,
|
|
84
|
+
NotPendingTransition: null,
|
|
85
|
+
supportsHydration: false,
|
|
86
|
+
supportsMutation: true,
|
|
87
|
+
supportsPersistence: false,
|
|
88
|
+
warnsIfNotActing: false,
|
|
89
|
+
createInstance(type: string, props: Record<string, unknown>): Instance {
|
|
90
|
+
const { props: own, oid } = ownProps(props);
|
|
91
|
+
return { type: shortType(type), props: own, oid, children: [] };
|
|
92
|
+
},
|
|
93
|
+
createTextInstance(text: string): never {
|
|
94
|
+
throw new Error(`A piece renders elements, not text ("${text}").`);
|
|
95
|
+
},
|
|
96
|
+
appendInitialChild(parent: Instance, child: Instance) {
|
|
97
|
+
parent.children.push(child);
|
|
98
|
+
},
|
|
99
|
+
appendChild(parent: Instance, child: Instance) {
|
|
100
|
+
remove(parent.children, child);
|
|
101
|
+
parent.children.push(child);
|
|
102
|
+
},
|
|
103
|
+
appendChildToContainer(container: Container, child: Instance) {
|
|
104
|
+
remove(container.children, child);
|
|
105
|
+
container.children.push(child);
|
|
106
|
+
},
|
|
107
|
+
insertBefore(parent: Instance, child: Instance, before: Instance) {
|
|
108
|
+
insert(parent.children, child, before);
|
|
109
|
+
},
|
|
110
|
+
insertInContainerBefore(container: Container, child: Instance, before: Instance) {
|
|
111
|
+
insert(container.children, child, before);
|
|
112
|
+
},
|
|
113
|
+
removeChild(parent: Instance, child: Instance) {
|
|
114
|
+
remove(parent.children, child);
|
|
115
|
+
},
|
|
116
|
+
removeChildFromContainer(container: Container, child: Instance) {
|
|
117
|
+
remove(container.children, child);
|
|
118
|
+
},
|
|
119
|
+
clearContainer(container: Container) {
|
|
120
|
+
container.children.length = 0;
|
|
121
|
+
},
|
|
122
|
+
commitUpdate(instance: Instance, _type: string, _old: Record<string, unknown>, next: Record<string, unknown>) {
|
|
123
|
+
const { props, oid } = ownProps(next);
|
|
124
|
+
instance.props = props;
|
|
125
|
+
instance.oid = oid;
|
|
126
|
+
},
|
|
127
|
+
finalizeInitialChildren: () => false,
|
|
128
|
+
shouldSetTextContent: () => false,
|
|
129
|
+
getRootHostContext: () => ({}),
|
|
130
|
+
getChildHostContext: (parent: object) => parent,
|
|
131
|
+
getPublicInstance: (instance: Instance) => instance,
|
|
132
|
+
prepareForCommit: () => null,
|
|
133
|
+
resetAfterCommit(container: Container) {
|
|
134
|
+
container.onCommit();
|
|
135
|
+
},
|
|
136
|
+
preparePortalMount() {},
|
|
137
|
+
scheduleTimeout: setTimeout,
|
|
138
|
+
cancelTimeout: clearTimeout,
|
|
139
|
+
getCurrentUpdatePriority: () => currentUpdatePriority,
|
|
140
|
+
setCurrentUpdatePriority(priority: number) {
|
|
141
|
+
currentUpdatePriority = priority;
|
|
142
|
+
},
|
|
143
|
+
resolveUpdatePriority: () => currentUpdatePriority || DefaultEventPriority,
|
|
144
|
+
getInstanceFromNode: () => null,
|
|
145
|
+
getInstanceFromScope: () => null,
|
|
146
|
+
beforeActiveInstanceBlur() {},
|
|
147
|
+
afterActiveInstanceBlur() {},
|
|
148
|
+
prepareScopeUpdate() {},
|
|
149
|
+
detachDeletedInstance() {},
|
|
150
|
+
hideInstance() {},
|
|
151
|
+
unhideInstance() {},
|
|
152
|
+
hideTextInstance() {},
|
|
153
|
+
unhideTextInstance() {},
|
|
154
|
+
maySuspendCommit: () => false,
|
|
155
|
+
preloadInstance: () => true,
|
|
156
|
+
startSuspendingCommit() {},
|
|
157
|
+
suspendInstance() {},
|
|
158
|
+
waitForCommitToBeReady: () => null,
|
|
159
|
+
resetFormInstance() {},
|
|
160
|
+
requestPostPaintCallback() {},
|
|
161
|
+
shouldAttemptEagerTransition: () => false,
|
|
162
|
+
trackSchedulerEvent() {},
|
|
163
|
+
resolveEventType: () => null,
|
|
164
|
+
resolveEventTimeStamp: () => -1.1,
|
|
165
|
+
rendererPackageName: '@volter/dawproject',
|
|
166
|
+
rendererVersion: '0.5.67',
|
|
167
|
+
} as never);
|
|
168
|
+
|
|
169
|
+
function snapshot(instance: Instance): DawNode {
|
|
170
|
+
return {
|
|
171
|
+
type: instance.type,
|
|
172
|
+
props: { ...instance.props },
|
|
173
|
+
oid: instance.oid,
|
|
174
|
+
children: instance.children.map(snapshot),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export interface PieceRoot {
|
|
179
|
+
/** The latest committed graph: the piece's single root element, or `null` before the first commit. */
|
|
180
|
+
readonly current: () => DawNode | null;
|
|
181
|
+
/** Re-render with a new component (the same module re-imported after an edit). */
|
|
182
|
+
readonly render: (piece: ComponentType) => Promise<DawNode>;
|
|
183
|
+
/** Called after every commit, including updates the piece makes itself (state, effects). */
|
|
184
|
+
readonly subscribe: (listener: (graph: DawNode | null) => void) => () => void;
|
|
185
|
+
readonly unmount: () => void;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Mount a piece. Resolves once the first commit has produced its graph. */
|
|
189
|
+
export function createPieceRoot(onError: (error: unknown) => void = console.error): PieceRoot {
|
|
190
|
+
const listeners = new Set<(graph: DawNode | null) => void>();
|
|
191
|
+
let latest: DawNode | null = null;
|
|
192
|
+
const container: Container = {
|
|
193
|
+
children: [],
|
|
194
|
+
onCommit() {
|
|
195
|
+
const roots = container.children;
|
|
196
|
+
if (roots.length > 1) {
|
|
197
|
+
onError(new Error(`A piece renders one <Project>; this one rendered ${roots.length} root elements.`));
|
|
198
|
+
}
|
|
199
|
+
latest = roots[0] ? snapshot(roots[0]) : null;
|
|
200
|
+
for (const listener of listeners) listener(latest);
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
// react-reconciler 0.31's runtime takes ten arguments (the three error callbacks are new in
|
|
204
|
+
// React 19); the installed `@types/react-reconciler` still declares the older eight.
|
|
205
|
+
const createContainer = reconciler.createContainer as unknown as (
|
|
206
|
+
...args: unknown[]
|
|
207
|
+
) => ReturnType<typeof reconciler.createContainer>;
|
|
208
|
+
const fiberRoot = createContainer(
|
|
209
|
+
container,
|
|
210
|
+
ConcurrentRoot,
|
|
211
|
+
null,
|
|
212
|
+
false,
|
|
213
|
+
null,
|
|
214
|
+
'',
|
|
215
|
+
onError,
|
|
216
|
+
onError,
|
|
217
|
+
onError,
|
|
218
|
+
null,
|
|
219
|
+
);
|
|
220
|
+
const render = (piece: ComponentType): Promise<DawNode> =>
|
|
221
|
+
new Promise((resolve, reject) => {
|
|
222
|
+
const element: ReactNode = createElement(piece);
|
|
223
|
+
reconciler.updateContainer(element, fiberRoot, null, () => {
|
|
224
|
+
if (latest) resolve(latest);
|
|
225
|
+
else reject(new Error('The piece rendered nothing; its default export returns a <Project>.'));
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
return {
|
|
229
|
+
current: () => latest,
|
|
230
|
+
render,
|
|
231
|
+
subscribe(listener) {
|
|
232
|
+
listeners.add(listener);
|
|
233
|
+
return () => listeners.delete(listener);
|
|
234
|
+
},
|
|
235
|
+
unmount() {
|
|
236
|
+
reconciler.updateContainer(null, fiberRoot, null, () => undefined);
|
|
237
|
+
listeners.clear();
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|