├── .eslintrc.js
├── .gitignore
├── LICENSE
├── README.md
├── babel.config.js
├── index.js
├── jest.config.js
├── lib
├── constants
│ ├── accidentals.js
│ ├── index.js
│ └── tunings.js
├── js-utils
│ └── combine-merge.js
├── main
│ ├── draw-to-context.js
│ ├── fill-empty-space.js
│ ├── generate-vex-objects.js
│ ├── get-tune.js
│ ├── parse-tune-structure.js
│ ├── remove-empty-bars.js
│ ├── set-bar-positions.js
│ └── tests
│ │ ├── fill-empty-space.test.js
│ │ ├── generate-vex-objects.test.js
│ │ └── set-bar-positions.test.js
├── models
│ ├── bar-region.js
│ ├── bar.js
│ ├── part-region.js
│ ├── part.js
│ └── tune.js
├── test-data
│ ├── abc-key-signatures.js
│ ├── abcjs-objects.js
│ ├── bar-regions.js
│ ├── bars.js
│ ├── part-regions.js
│ ├── parts.js
│ ├── render-options.js
│ ├── stave-notes.js
│ └── tune-attrs-jig-a.js
└── utils
│ ├── add-decorations.js
│ ├── generate-beams-compound.js
│ ├── get-curves.js
│ ├── get-keys.js
│ ├── get-tab-position.js
│ ├── index.js
│ ├── tests
│ ├── generate-beams-compound.test.js
│ ├── get-curves.test.js
│ ├── get-keys.test.js
│ ├── get-tab-position.test.js
│ └── utils.test.js
│ └── utils.js
├── package.json
├── public
└── .gitkeep
├── screenshot.png
├── visual-tool
├── index.css
├── index.html
├── scripts
│ └── index.js
├── tunes.txt
└── visual-test-cases
│ ├── clefs.abc
│ ├── curves.abc
│ ├── decorations.abc
│ ├── durations.abc
│ ├── grace.abc
│ ├── keysignatures.abc
│ └── voices.abc
└── webpack
└── webpack.config.js
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: 'airbnb-bundle',
3 | parser: 'babel-eslint',
4 | env: {
5 | jest: true,
6 | browser: true
7 | },
8 | rules: {
9 | 'no-use-before-define': 'off',
10 | 'react/jsx-filename-extension': 'off',
11 | 'react/prop-types': 'off',
12 | 'comma-dangle': 'off',
13 | 'max-len': 'off',
14 | 'object-curly-newline': 'off',
15 | 'import/prefer-default-export': 'off',
16 | 'no-param-reassign': 'off'
17 | },
18 | globals: {
19 | fetch: false
20 | }
21 | };
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 |
78 | # next.js build output
79 | .next
80 |
81 | # nuxt.js build output
82 | .nuxt
83 |
84 | # gatsby files
85 | .cache/
86 | public
87 |
88 | # vuepress build output
89 | .vuepress/dist
90 |
91 | # Serverless directories
92 | .serverless/
93 |
94 | # FuseBox cache
95 | .fusebox/
96 |
97 | # DynamoDB Local files
98 | .dynamodb/
99 |
100 | # TernJS port file
101 | .tern-port
102 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # abcjs-vexflow-renderer
2 | 
3 |
4 | ### VexFlow renderer for abcjs. Usage:
5 |
6 | ```
7 | import { AbcjsVexFlowRenderer, Vex } from 'abcjs-vexflow-renderer';
8 | import abcText from './abc_tune.txt';
9 |
10 | const whereToRender = document.getElementById('musicDiv');
11 |
12 | // generate a VexFlow renderer & context
13 | const renderer = new Vex.Flow.Renderer(whereToRender, Vex.Flow.Renderer.Backends.SVG);
14 | renderer.resize(500, 500);
15 | const context = renderer.getContext();
16 |
17 | // set up rendering options
18 | const renderOptions = {
19 | xOffset: 3,
20 | widthFactor: 1.7,
21 | lineHeight: 185,
22 | clefWidth: 60,
23 | meterWidth: 25,
24 | repeatWidthModifier: 35,
25 | keySigAccidentalWidth: 10,
26 | tabsVisibility: 1,
27 | voltaHeight: 25,
28 | renderWidth: 500,
29 | tuning: AbcjsVexFlowRenderer.TUNINGS.GUITAR_STANDARD // see tunings.js for all tunings and instruments
30 | };
31 |
32 | // generate the tune object
33 | const tune = AbcjsVexFlowRenderer.getTune(abcText, renderOptions);
34 |
35 | // draw to the vexflow context
36 | AbcjsVexFlowRenderer.drawToContext(context, tune);
37 | ```
38 |
39 | #### Testing and Development
40 |
41 | `git clone https://github.com/MatthewDorner/abcjs-vexflow-renderer`
42 |
43 | `cd abcjs-vexflow-renderer`
44 |
45 | `yarn`
46 |
47 |
48 | Once environment is ready, `npm run-script start` will launch an HTML visual comparison tool that shows ABC tunes rendered via abcjs' built-in renderer in comparison to this library. To supply a custom set of tunes, place the file at visual-tool/tunes.txt. The `jest` command will run the test suite, and will produce an HTML test coverage report in the `coverage` folder.
49 |
50 | #### About
51 | I created this library for my React Native app, [React Native Songbook](https://github.com/matthewdorner/react-native-songbook). I decided to write this code because I wanted to include guitar tab, because VexFlow works in React Native, and because I wanted precise control over positioning and spacing to make the content usable on phones and tablets. This library is able to automatically generate tablature for most ABC tunes. "Most" currently means a single voice set to chords. More complex music may not render correctly, and not all ABC features are implemented.
52 |
53 | Features currently supported:
54 | - Repeat signs
55 | - Multiple endings
56 | - Chord symbols
57 | - Grace Notes
58 | - Tuplets
59 | - Ties
60 | - Slurs
61 | - Some ornamentation
62 | - Tabs for multiple fretted instruments, fiddle fingerings, tin whistle and harmonica
63 |
64 | Features not supported, TODO:
65 | - Multiple voices
66 | - Lyrics
67 | - Non-treble clef
68 | - Transposition
69 |
70 | Harmonica tabs legend:
71 | - b = blow bend (b = half step, bb = whole step, etc.)
72 | - d = draw bend
73 | - ob = overblow
74 | - od = overdraw
75 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: [
3 | [
4 | '@babel/preset-env',
5 | {
6 |
7 | },
8 | ],
9 | ],
10 | plugins: [
11 | [
12 | 'inline-import',
13 | {
14 | extensions: ['.abc']
15 | }
16 | ]
17 | ]
18 | };
19 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | import Vex from 'vexflow';
2 | import ABCJS from 'abcjs';
3 | import getTune from './lib/main/get-tune';
4 | import drawToContext from './lib/main/draw-to-context';
5 | import { TUNINGS } from './lib/constants';
6 |
7 | const AbcjsVexFlowRenderer = {
8 | getTune,
9 | drawToContext,
10 | TUNINGS
11 | };
12 |
13 | export { AbcjsVexFlowRenderer, Vex, ABCJS };
14 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | // For a detailed explanation regarding each configuration property, visit:
2 | // https://jestjs.io/docs/en/configuration.html
3 |
4 | module.exports = {
5 | // All imported modules in your tests should be mocked automatically
6 | // automock: false,
7 |
8 | // Stop running tests after `n` failures
9 | // bail: 0,
10 |
11 | // Respect "browser" field in package.json when resolving modules
12 | // browser: false,
13 |
14 | // The directory where Jest should store its cached dependency information
15 | // cacheDirectory: "/tmp/jest_rs",
16 |
17 | // Automatically clear mock calls and instances between every test
18 | clearMocks: true,
19 |
20 | // Indicates whether the coverage information should be collected while executing the test
21 | collectCoverage: true,
22 |
23 | // An array of glob patterns indicating a set of files for which coverage information should be collected
24 | collectCoverageFrom: ['lib/**/*.js'],
25 |
26 | // The directory where Jest should output its coverage files
27 | coverageDirectory: 'coverage',
28 |
29 | // An array of regexp pattern strings used to skip coverage collection
30 | // coveragePathIgnorePatterns: [
31 | // "/node_modules/"
32 | // ],
33 |
34 | // A list of reporter names that Jest uses when writing coverage reports
35 | // coverageReporters: [
36 | // "json",
37 | // "text",
38 | // "lcov",
39 | // "clover"
40 | // ],
41 |
42 | // An object that configures minimum threshold enforcement for coverage results
43 | // coverageThreshold: null,
44 |
45 | // A path to a custom dependency extractor
46 | // dependencyExtractor: null,
47 |
48 | // Make calling deprecated APIs throw helpful error messages
49 | // errorOnDeprecated: false,
50 |
51 | // Force coverage collection from ignored files using an array of glob patterns
52 | // forceCoverageMatch: [],
53 |
54 | // A path to a module which exports an async function that is triggered once before all test suites
55 | // globalSetup: null,
56 |
57 | // A path to a module which exports an async function that is triggered once after all test suites
58 | // globalTeardown: null,
59 |
60 | // A set of global variables that need to be available in all test environments
61 | // globals: {},
62 |
63 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
64 | // maxWorkers: "50%",
65 |
66 | // An array of directory names to be searched recursively up from the requiring module's location
67 | // moduleDirectories: [
68 | // "node_modules"
69 | // ],
70 |
71 | // An array of file extensions your modules use
72 | // moduleFileExtensions: [
73 | // "js",
74 | // "json",
75 | // "jsx",
76 | // "ts",
77 | // "tsx",
78 | // "node"
79 | // ],
80 |
81 | // A map from regular expressions to module names that allow to stub out resources with a single module
82 | // moduleNameMapper: {},
83 |
84 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
85 | // modulePathIgnorePatterns: [],
86 |
87 | // Activates notifications for test results
88 | // notify: false,
89 |
90 | // An enum that specifies notification mode. Requires { notify: true }
91 | // notifyMode: "failure-change",
92 |
93 | // A preset that is used as a base for Jest's configuration
94 | // preset: null,
95 |
96 | // Run tests from one or more projects
97 | // projects: null,
98 |
99 | // Use this configuration option to add custom reporters to Jest
100 | // reporters: undefined,
101 |
102 | // Automatically reset mock state between every test
103 | // resetMocks: false,
104 |
105 | // Reset the module registry before running each individual test
106 | // resetModules: false,
107 |
108 | // A path to a custom resolver
109 | // resolver: null,
110 |
111 | // Automatically restore mock state between every test
112 | // restoreMocks: false,
113 |
114 | // The root directory that Jest should scan for tests and modules within
115 | // rootDir: null,
116 |
117 | // A list of paths to directories that Jest should use to search for files in
118 | // roots: [
119 | // ""
120 | // ],
121 |
122 | // Allows you to use a custom runner instead of Jest's default test runner
123 | // runner: "jest-runner",
124 |
125 | // The paths to modules that run some code to configure or set up the testing environment before each test
126 | // setupFiles: [],
127 |
128 | // A list of paths to modules that run some code to configure or set up the testing framework before each test
129 | // setupFilesAfterEnv: [],
130 |
131 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing
132 | // snapshotSerializers: [],
133 |
134 | // The test environment that will be used for testing
135 | // testEnvironment: "jest-environment-jsdom",
136 |
137 | // Options that will be passed to the testEnvironment
138 | // testEnvironmentOptions: {},
139 |
140 | // Adds a location field to test results
141 | // testLocationInResults: false,
142 |
143 | // The glob patterns Jest uses to detect test files
144 | // testMatch: [
145 | // "**/__tests__/**/*.[jt]s?(x)",
146 | // "**/?(*.)+(spec|test).[tj]s?(x)"
147 | // ],
148 |
149 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
150 | // testPathIgnorePatterns: [
151 | // "/node_modules/"
152 | // ],
153 |
154 | // The regexp pattern or array of patterns that Jest uses to detect test files
155 | // testRegex: [],
156 |
157 | // This option allows the use of a custom results processor
158 | // testResultsProcessor: null,
159 |
160 | // This option allows use of a custom test runner
161 | // testRunner: "jasmine2",
162 |
163 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
164 | // testURL: "http://localhost",
165 |
166 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
167 | // timers: "real",
168 |
169 | // A map from regular expressions to paths to transformers
170 | // transform: null,
171 |
172 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
173 | transformIgnorePatterns: [
174 | '/node_modules/(?!vexflow).+\\.js$'
175 | ],
176 |
177 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
178 | // unmockedModulePathPatterns: undefined,
179 |
180 | // Indicates whether each individual test should be reported during the run
181 | // verbose: null,
182 |
183 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
184 | // watchPathIgnorePatterns: [],
185 |
186 | // Whether to use watchman for file crawling
187 | // watchman: true,
188 | };
189 |
--------------------------------------------------------------------------------
/lib/constants/accidentals.js:
--------------------------------------------------------------------------------
1 | export const VEX_ACCIDENTAL_FROM_ABCJS = {
2 | sharp: '#',
3 | flat: 'b',
4 | dblsharp: '##',
5 | dblflat: 'bb',
6 | natural: 'n'
7 | };
8 |
9 | export const SEMITONES_FROM_ACCIDENTAL = {
10 | '#': 1,
11 | b: -1,
12 | '##': 2,
13 | bb: -2,
14 | n: 0
15 | };
16 |
--------------------------------------------------------------------------------
/lib/constants/index.js:
--------------------------------------------------------------------------------
1 | export * from './accidentals';
2 | export * from './tunings';
3 |
--------------------------------------------------------------------------------
/lib/constants/tunings.js:
--------------------------------------------------------------------------------
1 | export const TUNING_TYPES = {
2 | STRINGS_FRETTED: 'strings_fretted',
3 | STRINGS_FIDDLE_FINGERINGS: 'strings_fiddle_fingerings',
4 | WHISTLE: 'whistle',
5 | HARMONICA: 'harmonica'
6 | };
7 |
8 | export const TUNINGS = {
9 | GUITAR_STANDARD: {
10 | displayName: 'Guitar (EADGBE)',
11 | strings: ['e/3', 'a/3', 'd/4', 'g/4', 'b/4', 'e/5'],
12 | type: TUNING_TYPES.STRINGS_FRETTED
13 | },
14 | GUITAR_OPEN_D: {
15 | displayName: 'Guitar (DADF#AD)',
16 | strings: ['d/3', 'a/3', 'd/4', 'f/4#', 'a/4', 'd/5'],
17 | type: TUNING_TYPES.STRINGS_FRETTED
18 | },
19 | BANJO: {
20 | displayName: 'Banjo (GDGBD)',
21 | strings: ['d/4', 'g/4', 'b/4', 'd/5'],
22 | type: TUNING_TYPES.STRINGS_FRETTED
23 | },
24 | TENOR_BANJO: {
25 | displayName: 'Tenor Banjo (CGDA)',
26 | strings: ['c/4', 'g/4', 'd/5', 'a/5'],
27 | type: TUNING_TYPES.STRINGS_FRETTED
28 | },
29 | FIDDLE_STANDARD: {
30 | displayName: 'Fiddle/Mandolin (GDAE)',
31 | strings: ['g/3', 'd/4', 'a/4', 'e/5'],
32 | type: TUNING_TYPES.STRINGS_FRETTED
33 | },
34 | FIDDLE_STANDARD_FINGERINGS: {
35 | displayName: 'Fiddle Fingerings (GDAE)',
36 | strings: ['g/3', 'd/4', 'a/4', 'e/5'],
37 | type: TUNING_TYPES.STRINGS_FIDDLE_FINGERINGS
38 | },
39 | FIDDLE_CROSS: {
40 | displayName: 'Cross Fiddle (AEAE)',
41 | strings: ['a/3', 'e/4', 'a/4', 'e/5'],
42 | type: TUNING_TYPES.STRINGS_FRETTED
43 | },
44 | FIDDLE_CROSS_FINGERINGS: {
45 | displayName: 'Fiddle Fingerings (AEAE)',
46 | strings: ['a/3', 'e/4', 'a/4', 'e/5'],
47 | type: TUNING_TYPES.STRINGS_FIDDLE_FINGERINGS
48 | },
49 | TIN_WHISTLE_D: {
50 | displayName: 'Tin Whistle (D)',
51 | type: TUNING_TYPES.WHISTLE,
52 | pitchOffset: 0 // offset relative to D whistle
53 | },
54 | TIN_WHISTLE_C: {
55 | displayName: 'Tin Whistle (C)',
56 | type: TUNING_TYPES.WHISTLE,
57 | pitchOffset: -2
58 | },
59 | TIN_WHISTLE_B_FLAT: {
60 | displayName: 'Tin Whistle (Bb)',
61 | type: TUNING_TYPES.WHISTLE,
62 | pitchOffset: -4
63 | },
64 | HARMONICA_C: {
65 | displayName: 'Harmonica (C)',
66 | type: TUNING_TYPES.HARMONICA,
67 | pitchOffset: 0 // offset relative to C harmonica
68 | },
69 | HARMONICA_A: {
70 | displayName: 'Harmonica (A)',
71 | type: TUNING_TYPES.HARMONICA,
72 | pitchOffset: -3
73 | },
74 | HARMONICA_G: {
75 | displayName: 'Harmonica (G)',
76 | type: TUNING_TYPES.HARMONICA,
77 | pitchOffset: -5
78 | },
79 | HARMONICA_C_OCTAVE: {
80 | displayName: 'Harmonica (C) +OCTAVE',
81 | type: TUNING_TYPES.HARMONICA,
82 | pitchOffset: -12 // offset relative to C harmonica
83 | },
84 | HARMONICA_A_OCTAVE: {
85 | displayName: 'Harmonica (A) +OCTAVE',
86 | type: TUNING_TYPES.HARMONICA,
87 | pitchOffset: -15
88 | },
89 | HARMONICA_G_OCTAVE: {
90 | displayName: 'Harmonica (G) +OCTAVE',
91 | type: TUNING_TYPES.HARMONICA,
92 | pitchOffset: -17
93 | }
94 | };
95 |
--------------------------------------------------------------------------------
/lib/js-utils/combine-merge.js:
--------------------------------------------------------------------------------
1 | import deepMerge from 'deepmerge';
2 |
3 | // https://github.com/TehShrike/deepmerge
4 | // wrapper using combineMerge so that arrays will be merged instead of concatenated
5 |
6 | function combineMerge(target, source, options) {
7 | const destination = target.slice();
8 |
9 | source.forEach((item, index) => {
10 | if (typeof destination[index] === 'undefined') {
11 | destination[index] = options.cloneUnlessOtherwiseSpecified(item, options);
12 | } else if (options.isMergeableObject(item)) {
13 | destination[index] = deepMerge(target[index], item, options);
14 | } else if (target.indexOf(item) === -1) {
15 | destination.push(item);
16 | }
17 | });
18 | return destination;
19 | }
20 |
21 | export function merge(A, B) {
22 | return deepMerge(A, B, { arrayMerge: combineMerge });
23 | }
24 |
--------------------------------------------------------------------------------
/lib/main/draw-to-context.js:
--------------------------------------------------------------------------------
1 | import Vex from 'vexflow';
2 | import { Stave } from 'vexflow/src/stave';
3 | import { TabStave } from 'vexflow/src/tabstave';
4 | import { Formatter } from 'vexflow/src/formatter';
5 | import { Curve } from 'vexflow/src/curve';
6 | import { convertKeySignature } from '../utils';
7 |
8 | /**
9 | * Uses VexFlow API to draw the data in Tune object to the supplied VexFlow context.
10 | * @param {Object} context The VexFlow context
11 | * @param {Object} tune The Tune object returned from getTune function
12 | */
13 | export default function drawToContext(context, tune) {
14 | if (tune.parts.length === 0) {
15 | return;
16 | }
17 |
18 | let stave; let tabStave;
19 | const { tuning, tabsVisibility, staveVisibility } = tune.renderOptions;
20 | const tabNumberOfLines = tuning.strings ? tuning.strings.length : 1;
21 |
22 | tune.parts.forEach((part) => {
23 | part.bars.forEach((bar) => {
24 | let tabsPositionY;
25 | if (tune.renderOptions.staveVisibility) {
26 | tabsPositionY = bar.position.y + 60;
27 | } else {
28 | tabsPositionY = bar.position.y;
29 | }
30 |
31 | if (bar.position.clefSigMeterWidth > 0) {
32 | const clefsStave = new Stave(bar.position.x, bar.position.y, bar.position.clefSigMeterWidth, { right_bar: false });
33 | const clefsTabStave = new TabStave(bar.position.x, tabsPositionY, bar.position.clefSigMeterWidth, { right_bar: false });
34 |
35 | clefsTabStave.setNumLines(tabNumberOfLines);
36 | clefsStave.setContext(context);
37 | clefsTabStave.setContext(context);
38 |
39 | if (bar.clef) { clefsStave.setClef(bar.clef); }
40 | if (bar.abcKeySignature) {
41 | if (bar.cancelKeySig) {
42 | clefsStave.setKeySignature(convertKeySignature(bar.abcKeySignature), convertKeySignature(bar.cancelKeySig));
43 | } else {
44 | clefsStave.setKeySignature(convertKeySignature(bar.abcKeySignature));
45 | }
46 | }
47 | if (bar.meter) { clefsStave.setTimeSignature(bar.meter); }
48 |
49 | if (staveVisibility) {
50 | clefsStave.draw();
51 | }
52 | if (tabsVisibility) {
53 | clefsTabStave.draw();
54 | }
55 |
56 | const notesX = bar.position.x + bar.position.clefSigMeterWidth;
57 | const notesWidth = bar.position.width - bar.position.clefSigMeterWidth;
58 |
59 | stave = new Stave(notesX, bar.position.y, notesWidth, { left_bar: false });
60 | stave.setContext(context);
61 | tabStave = new TabStave(notesX, tabsPositionY, notesWidth, { left_bar: false });
62 | tabStave.setNumLines(tabNumberOfLines);
63 | tabStave.setContext(context);
64 | } else {
65 | stave = new Stave(bar.position.x, bar.position.y, bar.position.width);
66 | stave.setContext(context);
67 | tabStave = new TabStave(bar.position.x, tabsPositionY, bar.position.width);
68 | tabStave.setNumLines(tabNumberOfLines);
69 | tabStave.setContext(context);
70 | }
71 |
72 | if (bar.volta) {
73 | stave.setVoltaType(bar.volta.type, bar.volta.number.toString(), tune.renderOptions.voltaHeight);
74 | }
75 |
76 | if (bar.repeats.includes(Vex.Flow.Barline.type.REPEAT_BEGIN)) {
77 | stave.setBegBarType(Vex.Flow.Barline.type.REPEAT_BEGIN);
78 | }
79 | if (bar.repeats.includes(Vex.Flow.Barline.type.REPEAT_END)) {
80 | stave.setEndBarType(Vex.Flow.Barline.type.REPEAT_END);
81 | }
82 |
83 | // DRAW
84 | if (tabsVisibility) {
85 | tabStave.draw(); // drawing this first fixes the artifact w/ beams overlapping tab stave lines
86 | Formatter.FormatAndDraw(context, tabStave, bar.tabNotes);
87 | }
88 | if (staveVisibility) {
89 | stave.draw();
90 | Formatter.FormatAndDraw(context, stave, bar.notes);
91 | bar.beams.forEach((b) => { b.setContext(context).draw(); });
92 | bar.tuplets.forEach((tuplet) => {
93 | tuplet.setContext(context).draw();
94 | });
95 | }
96 | });
97 |
98 | // DRAW CURVES
99 | if (staveVisibility) {
100 | part.curves.forEach((partCurve) => {
101 | const vexCurve = new Curve(partCurve.startNote, partCurve.endNote, {
102 | thickness: 2,
103 | cps: [{ x: -5, y: 7 }, { x: 0, y: 7 }],
104 | x_shift: -10
105 | });
106 | vexCurve.setContext(context).draw();
107 | });
108 | }
109 | });
110 | }
111 |
--------------------------------------------------------------------------------
/lib/main/fill-empty-space.js:
--------------------------------------------------------------------------------
1 | import Vex from 'vexflow';
2 |
3 | /**
4 | * After setBarPositions sets each bar to its minimum acceptable width, there will be extra space
5 | * at the end of most lines. This function will add (amount of extra space on the line) / (number
6 | * of bars) space to each bar. This is a separate function as it relies on having the width
7 | * and position of each bar already known, else it would require backtracking and mutating of
8 | * already set values in the setBarPositions loop.
9 | * @param {Object} tune
10 | *
11 | * @returns {Object} The Tune after empty space has been filled
12 | */
13 | export default function fillEmptySpace(tune) {
14 | const newTune = Object.assign({}, tune);
15 | newTune.parts = tune.parts.map((part) => {
16 | const newPart = Object.assign({}, part);
17 | let cursor = 0; let outputBars = [];
18 |
19 | for (let line = getLine(part.bars, cursor); line.length > 0; line = getLine(part.bars, cursor)) {
20 | // test whether it's a single bar on the last line (tested by object identity)
21 | if (line[0] !== part.bars[part.bars.length - 1]) {
22 | const expandedLine = expandBars(line, tune.renderOptions);
23 | cursor += line.length;
24 | outputBars = outputBars.concat(expandedLine);
25 | } else {
26 | cursor += 1; // it's the very last bar of part on a new line so don't expand
27 | outputBars = outputBars.concat(line);
28 | }
29 | }
30 |
31 | newPart.bars = outputBars;
32 | return newPart;
33 | });
34 | return newTune;
35 | }
36 |
37 | function getLine(bars, cursor) {
38 | const line = [];
39 | for (let i = cursor; bars[i] && bars[i].position.y === bars[cursor].position.y; i += 1) {
40 | line.push(bars[i]);
41 | }
42 | return line;
43 | }
44 |
45 | function expandBars(line, renderOptions) {
46 | let extraSpace = renderOptions.renderWidth - (line[line.length - 1].position.x + line[line.length - 1].position.width);
47 | let spaceAdded = 0;
48 |
49 | const expandedBars = line.map((bar, i) => {
50 | const newBar = Object.assign({}, bar);
51 |
52 | let spaceToAdd;
53 | if ((bar.isFirst || (bar.repeats.includes(Vex.Flow.Barline.type.REPEAT_BEGIN) && bar !== line[line.length - 1])) && bar.notes.length < 3) {
54 | spaceToAdd = 0;
55 | } else {
56 | spaceToAdd = Math.floor(extraSpace / (line.length - i));
57 | }
58 |
59 | newBar.position.x += spaceAdded;
60 | newBar.position.width += spaceToAdd;
61 | extraSpace -= spaceToAdd;
62 | spaceAdded += spaceToAdd;
63 |
64 | return newBar;
65 | });
66 |
67 | return expandedBars;
68 | }
69 |
--------------------------------------------------------------------------------
/lib/main/generate-vex-objects.js:
--------------------------------------------------------------------------------
1 | import Vex from 'vexflow';
2 | import { StaveNote } from 'vexflow/src/stavenote';
3 | import { TabNote } from 'vexflow/src/tabnote';
4 | import { GraceNote } from 'vexflow/src/gracenote';
5 | import { GraceTabNote } from 'vexflow/src/gracetabnote';
6 | import { GraceNoteGroup } from 'vexflow/src/gracenotegroup';
7 | import { Beam } from 'vexflow/src/beam';
8 | import { Voice } from 'vexflow/src/voice';
9 | import { Tuplet } from 'vexflow/src/tuplet';
10 |
11 | // parts of the Tune data structure that will be created
12 | import Bar from '../models/bar';
13 | import Part from '../models/part';
14 | import Tune from '../models/tune';
15 |
16 | import { getKeys, getVexDuration, addDecorations, getTabPosition, generateBeamsCompound, getCurves } from '../utils';
17 | import { VEX_ACCIDENTAL_FROM_ABCJS } from '../constants';
18 |
19 | /**
20 | * Takes the array of PartRegions (each of which contains an array of BarRegions), and
21 | * generates the Tune object, which is similarly structured but with VexFlow StaveNote
22 | * and TabNote objects, instead of the abcjs output objects representing notes, rests, etc.
23 | * Tune also contains the tuneAttrs and renderOptions, so the Tune will contain all data
24 | * about the tune as it passes through the rest of processing stages. Uses the Tune, Part and Bar
25 | * classes defined in this library.
26 | * @param {Array} partRegions The output of parseTuneStructure
27 | * @param {Object} tuneAttrs Pieces of info about the tune as a whole
28 | * @param {Object} renderOptions Options, should be documented more
29 | *
30 | * @returns {Object} The Tune object, containing arrays of Part and Bar objects
31 | */
32 | export default function generateVexObjects(partRegions, tuneAttrs, renderOptions) {
33 | const tune = new Tune(tuneAttrs, renderOptions);
34 |
35 | let currentAbcKeySignature = tuneAttrs.abcKeySignature;
36 | let inVolta = false;
37 |
38 | partRegions.forEach((partRegion, partIndex) => {
39 | const currentPart = new Part(partRegion.title);
40 | tune.parts.push(currentPart);
41 |
42 | partRegion.barRegions.forEach((barRegion, barIndex) => {
43 | const currentBar = new Bar();
44 | currentPart.bars.push(currentBar);
45 | let inTriplet = null;
46 |
47 | if (barIndex === 0) { currentBar.isFirst = true; }
48 | if (partIndex === 0 && barIndex === 0) {
49 | currentBar.clef = tuneAttrs.clef;
50 | currentBar.meter = tuneAttrs.meter;
51 | if (!currentBar.abcKeySignature) {
52 | currentBar.abcKeySignature = tuneAttrs.abcKeySignature;
53 | }
54 | }
55 | if (['bar_right_repeat', 'bar_dbl_repeat'].includes(barRegion.endBarLine.type)) {
56 | currentBar.repeats.push(Vex.Flow.Barline.type.REPEAT_END);
57 | }
58 | if (['bar_left_repeat', 'bar_dbl_repeat'].includes(barRegion.startBarLine.type)) {
59 | currentBar.repeats.push(Vex.Flow.Barline.type.REPEAT_BEGIN);
60 | }
61 |
62 | if (barRegion.startBarLine.startEnding && barRegion.endBarLine.endEnding) {
63 | inVolta = false;
64 | currentBar.volta = {
65 | number: barRegion.startBarLine.startEnding,
66 | type: Vex.Flow.Volta.type.BEGIN_END
67 | };
68 | } else if (barRegion.startBarLine.startEnding) {
69 | inVolta = true;
70 | currentBar.volta = {
71 | number: barRegion.startBarLine.startEnding,
72 | type: Vex.Flow.Volta.type.BEGIN
73 | };
74 | } else if (barRegion.endBarLine.endEnding) {
75 | inVolta = false;
76 | currentBar.volta = {
77 | number: 0,
78 | type: Vex.Flow.Volta.type.END
79 | };
80 | } else if (inVolta) {
81 | currentBar.volta = {
82 | number: 0,
83 | type: Vex.Flow.Volta.type.MID
84 | };
85 | }
86 |
87 | barRegion.contents.forEach((obj, objIndex) => {
88 | if (obj.el_type === 'key') {
89 | currentBar.cancelKeySig = currentAbcKeySignature;
90 | currentAbcKeySignature = obj;
91 | currentBar.abcKeySignature = currentAbcKeySignature;
92 | return;
93 | }
94 | if (obj.el_type !== 'note') {
95 | return; // what else could it be?
96 | }
97 |
98 | if (obj.startTriplet) {
99 | inTriplet = {
100 | num_notes: obj.startTriplet,
101 | notes_occupied: Math.round(obj.startTriplet * obj.tripletMultiplier),
102 | notes: [],
103 | tabNotes: []
104 | };
105 | }
106 |
107 | const { duration, isDotted } = getVexDuration(obj.duration);
108 | let noteToAdd;
109 |
110 | // CREATE AND ADD MODIFIERS TO STAVE NOTE / REST
111 | if (!obj.rest) {
112 | const keys = getKeys(obj.pitches);
113 | const accidentals = obj.pitches.map(pitch => VEX_ACCIDENTAL_FROM_ABCJS[pitch.accidental]);
114 |
115 | noteToAdd = new StaveNote({
116 | clef: tuneAttrs.clef, keys, duration, auto_stem: true
117 | });
118 | addDecorations(noteToAdd, obj.decoration);
119 | accidentals.forEach((accidental, i) => {
120 | if (accidental) { noteToAdd.addAccidental(i, new Vex.Flow.Accidental(accidental)); }
121 | });
122 |
123 | currentPart.curves = getCurves(currentPart.curves, obj, noteToAdd);
124 |
125 | // this is mostly duplicated with below. maybe can be put in a separate function
126 | if (obj.gracenotes) {
127 | const graceNotesArray = [];
128 | obj.gracenotes.forEach((graceNote) => {
129 | const graceKey = getKeys([graceNote])[0];
130 | const graceAccidental = VEX_ACCIDENTAL_FROM_ABCJS[graceNote.accidental];
131 | const vexDuration = getVexDuration(graceNote.duration);
132 | const graceNoteToAdd = new GraceNote({ keys: [graceKey], duration: vexDuration.duration });
133 | if (graceAccidental) { graceNoteToAdd.addAccidental(0, new Vex.Flow.Accidental(graceAccidental)); }
134 | if (vexDuration.isDotted) { graceNoteToAdd.addDotToAll(); }
135 | graceNotesArray.push(graceNoteToAdd);
136 | });
137 |
138 | const graceNoteGroup = new GraceNoteGroup(graceNotesArray, true);
139 | noteToAdd.addModifier(0, graceNoteGroup.beamNotes());
140 | }
141 |
142 | // CREATE AND ADD MODIFIERS TO TAB NOTE
143 | const tabNoteToAdd = new TabNote({
144 | positions: getTabPosition(keys, currentAbcKeySignature, barRegion.contents, objIndex, renderOptions.tuning, false),
145 | duration,
146 | stem_direction: -1
147 | }, renderOptions.tabStemsVisibility);
148 | if (isDotted) { tabNoteToAdd.addDot(); } // do double dotted notes work?
149 | if (inTriplet) { inTriplet.tabNotes.push(tabNoteToAdd); }
150 |
151 | if (obj.gracenotes) {
152 | const tabGraceNotesArray = [];
153 | obj.gracenotes.forEach((graceNote) => {
154 | const graceKey = getKeys([graceNote])[0];
155 | const vexDuration = getVexDuration(graceNote.duration);
156 | const graceNoteToAdd = new GraceTabNote({
157 | positions: getTabPosition([graceKey], currentAbcKeySignature, barRegion.contents, objIndex, renderOptions.tuning, true),
158 | duration: vexDuration.duration,
159 | stem_direction: -1
160 | }, renderOptions.tabStemsVisibility);
161 | if (vexDuration.isDotted) { graceNoteToAdd.addDotToAll(); }
162 | tabGraceNotesArray.push(graceNoteToAdd);
163 | });
164 | const tabGraceNoteGroup = new GraceNoteGroup(tabGraceNotesArray, false);
165 | tabNoteToAdd.addModifier(tabGraceNoteGroup);
166 | }
167 | currentBar.tabNotes.push(tabNoteToAdd);
168 | } else { // IS a rest
169 | noteToAdd = new StaveNote({
170 | clef: tuneAttrs.clef, keys: ['b/4'], duration: `${duration}r`,
171 | });
172 |
173 | const tabNoteToAdd = new TabNote({
174 | positions: [{ str: 0, fret: '' }],
175 | duration,
176 | stem_direction: -1
177 | }, renderOptions.tabStemsVisibility);
178 |
179 | if (isDotted) { tabNoteToAdd.addDotToAll(); }
180 | currentBar.tabNotes.push(tabNoteToAdd);
181 | }
182 |
183 | // these parts happen whether it's a rest or not
184 | if (isDotted) { noteToAdd.addDotToAll(); }
185 | if (obj.chord) {
186 | let chordName = obj.chord[0].name;
187 | if (chordName.includes('♭')) {
188 | chordName = chordName.replace('♭', 'b');
189 | } // sharps don't cause a problem, the '♭' symbol wont' be displayed though
190 |
191 | noteToAdd.addModifier(0, new Vex.Flow.Annotation(chordName)
192 | .setVerticalJustification(Vex.Flow.Annotation.VerticalJustify.TOP));
193 | }
194 | if (inTriplet) { inTriplet.notes.push(noteToAdd); }
195 | currentBar.notes.push(noteToAdd);
196 | // check for inTriplet because triplets can technically cross over barlines in abcjs
197 | // but I don't think it's necessary to support this. in the case I found, it
198 | // didn't appear to be intentional
199 | if (obj.endTriplet && inTriplet) {
200 | currentBar.tuplets.push(new Tuplet(inTriplet.notes, {
201 | num_notes: inTriplet.num_notes,
202 | notes_occupied: inTriplet.notes_occupied
203 | }));
204 | // I think still need to create tuplets for the tabNotes so they align correctly,
205 | // but don't want to draw them because it's already drawn in the regular stave
206 | currentBar.tabTuplets.push(new Tuplet(inTriplet.tabNotes, {
207 | num_notes: inTriplet.num_notes,
208 | notes_occupied: inTriplet.notes_occupied,
209 | }));
210 | inTriplet = null;
211 | }
212 | }); // end of barRegion.contents.forEach
213 |
214 | const { meter } = tune.tuneAttrs;
215 |
216 | // set the voice so setBarPositions can use it to have VexFlow Formatter figure out the space needed
217 | const meterArray = meter.split('/');
218 | const voice = new Voice({ num_beats: meterArray[0], beat_value: meterArray[1] });
219 | voice.setStrict(false);
220 | voice.addTickables(currentBar.notes);
221 | currentBar.voice = voice;
222 |
223 | if (meter === '4/4') {
224 | currentBar.beams = Beam.generateBeams(currentBar.notes, { groups: [new Vex.Flow.Fraction(2, 4)] });
225 | } else if (meter === '3/8' || meter === '6/8' || meter === '9/8' || meter === '12/8') {
226 | // 3/8 isn't technically a compound time signature, maybe should call the function something else.
227 | // I believe this is handling beams correctly for all time signatures though, need a visual test suite
228 | // & compare to VexFlow visual tests https://www.vexflow.com/tests/
229 | currentBar.beams = generateBeamsCompound(currentBar.notes);
230 | } else {
231 | currentBar.beams = Beam.generateBeams(currentBar.notes, { groups: Beam.getDefaultBeamGroups(meter) });
232 | }
233 | });
234 | });
235 | return tune;
236 | }
237 |
--------------------------------------------------------------------------------
/lib/main/get-tune.js:
--------------------------------------------------------------------------------
1 | import ABCJS from 'abcjs';
2 |
3 | import generateVexObjects from './generate-vex-objects';
4 | import removeEmptyBars from './remove-empty-bars';
5 | import setBarPositions from './set-bar-positions';
6 | import fillEmptySpace from './fill-empty-space';
7 | import parseTuneStructure from './parse-tune-structure';
8 |
9 | /**
10 | * Takes the ABC notation text, calls abcjs parseOnly method on it, and then returns a converted
11 | * Tune object that can be easily drawn using the drawToContext method.
12 | * @param {string} abcString The ABC tune string
13 | * @param {Object} renderOptions Options, should be documented more
14 | *
15 | * @returns {Object} the Tune object, ready to be drawn via drawToContext
16 | */
17 | export default function getTune(abcString, renderOptions) {
18 | // GET THE PARSED OBJECT AND PROPERTIES
19 |
20 | // there is another method in abcjs, the regular render method can be used if you pass in "*" for the HTML element,
21 | // and the resulting object will have more info than if you use parseOnly? I haven't tried this.
22 | const parsedObject = ABCJS.parseOnly(abcString);
23 | while (parsedObject[0].lines[0].subtitle) {
24 | parsedObject[0].lines.shift();
25 | }
26 |
27 | const tuneObjArray = parsedObject[0].lines
28 | .map(line => line.staff[0].voices[0])
29 | .reduce((acc, val) => acc.concat(val), []);
30 |
31 | if (!parsedObject[0].lines[0]) {
32 | return null;
33 | }
34 |
35 | let meter = '';
36 | const meterLine = abcString.split('\n').filter(line => line.charAt(0) === 'M')[0];
37 | if (meterLine) {
38 | const meterCleaned = meterLine.replace(' ', '');
39 | meter = meterCleaned.slice(2, meterCleaned.length);
40 | }
41 |
42 | if (meter === 'C') { meter = '4/4'; }
43 | if (meter === 'C|') { meter = '2/2'; }
44 | if (meter === '') { throw new Error('Meter (M:) was not found'); }
45 | const meterArray = meter.split('/');
46 |
47 | // are there any valid meters that are not formatted as a fraction and also not 'C' and 'C|'?
48 | if (isNaN(meterArray[0]) || isNaN(meterArray[0])) {
49 | throw new Error(`(M:) incorrectly formatted, meter provided was: ${meter}`);
50 | }
51 |
52 | const clef = parsedObject[0].lines[0].staff[0].clef.type;
53 | if (clef !== 'treble') {
54 | throw new Error('Cant handle non-treble clefs at this time');
55 | }
56 |
57 | // GET THE TUNE ATTRIBUTES. it's not really right to set global attributes
58 | // like this because they can change during the tune
59 | const tuneAttrs = {
60 | meter,
61 | clef,
62 | abcKeySignature: parsedObject[0].lines[0].staff[0].key
63 | };
64 |
65 | // PROCESS and return a Tune object ready to draw with drawToContext
66 | return fillEmptySpace(
67 | setBarPositions(
68 | removeEmptyBars(
69 | generateVexObjects(
70 | parseTuneStructure(tuneObjArray), tuneAttrs, renderOptions
71 | )
72 | )
73 | )
74 | );
75 | }
76 |
--------------------------------------------------------------------------------
/lib/main/parse-tune-structure.js:
--------------------------------------------------------------------------------
1 | import BarRegion from '../models/bar-region';
2 | import PartRegion from '../models/part-region';
3 |
4 | /**
5 | * Takes the abcjs parser output array representing the entire tune, and return
6 | * an array of PartRegions, each of which contains the portion of that array
7 | * representing a single part.
8 | * @param {Array} tuneObjArray The array representing the tune
9 | *
10 | * @returns {Array} The array of PartRegions
11 | */
12 | export default function parseTuneStructure(tuneObjArray) {
13 | const partRegions = []; // array of PartRegion objects to return
14 |
15 | // variables that hold parser state + initialization of those
16 | let currentPart = new PartRegion('default');
17 | let currentPartObjects = [];
18 |
19 | tuneObjArray.forEach((obj) => {
20 | switch (obj.el_type) {
21 | case 'part':
22 | if (currentPartObjects.length === 0) {
23 | // if the current part is still empty, just rename the current part
24 | currentPart.title = obj.title;
25 | } else {
26 | // convert and apply bars to part, push to partRegions[]
27 | currentPart.barRegions = parsePartStructure(currentPartObjects);
28 | partRegions.push(currentPart);
29 | // reset the state variables
30 | currentPart = new PartRegion(obj.title);
31 | currentPartObjects = [];
32 | }
33 | break;
34 | default:
35 | currentPartObjects.push(obj);
36 | break;
37 | }
38 | });
39 |
40 | // deal with the final part also ignore final part if it's empty
41 | if (currentPartObjects.length > 0) {
42 | currentPart.barRegions = parsePartStructure(currentPartObjects);
43 | partRegions.push(currentPart);
44 | }
45 | return partRegions;
46 | }
47 |
48 | /**
49 | * Takes the abcjs parser output array segment representing a single part, and return
50 | * an array of BarRegions, each of which contains the portion of that array
51 | * representing a single bar.
52 | * @param {Array} partObjArray The array representing the part
53 | *
54 | * @returns {Array} The array of BarRegions
55 | */
56 | function parsePartStructure(partObjArray) {
57 | const barRegions = []; // array of BarRegion objects to return
58 |
59 | // variables that hold parser state + initialization of those
60 | let currentBar = new BarRegion();
61 | let currentBarObjects = [];
62 |
63 | partObjArray.forEach((obj, i) => {
64 | switch (obj.el_type) {
65 | case 'bar':
66 | if (i === 0) { // if it's the very first obj, just apply it to the (empty) currentBar
67 | currentBar.startBarLine = obj;
68 | } else { // apply the current bar and push
69 | currentBar.endBarLine = obj;
70 | currentBar.contents = currentBarObjects;
71 | barRegions.push(currentBar);
72 | }
73 | if (i !== obj.length) { // reset the state 2 prepare for next bar
74 | currentBar = new BarRegion();
75 | currentBarObjects = [];
76 | currentBar.startBarLine = obj;
77 | }
78 | break;
79 | default:
80 | currentBarObjects.push(obj);
81 | break;
82 | }
83 | });
84 |
85 | // deal with the last bar (if the last object was a barline, this shouldn't execute)
86 | if (currentBarObjects.length > 0) {
87 | currentBar.contents = currentBarObjects;
88 | barRegions.push(currentBar);
89 | }
90 | return barRegions;
91 | }
92 |
--------------------------------------------------------------------------------
/lib/main/remove-empty-bars.js:
--------------------------------------------------------------------------------
1 | import Vex from 'vexflow';
2 |
3 | /**
4 | * Takes the tune data and removes empty bars, shifting any important markers (repeat signs, etc)
5 | * to the nearest bar with notes in it. The empty bars mostly occur due to the fact that I merge
6 | * 'line breaks' from the parsed object, so there's a bar at the end of one line, and a bar at the
7 | * beginning of the next line, but I see it as two barlines. This entire method should be gotten
8 | * rid of and instead, should have tuneArrayParser handle the lines and assemble them correctly
9 | * into parts to begin with.
10 | * @param {Array} tuneData The array of Part objects
11 | *
12 | * @returns {Array} The same array after map and filter operations that removes empty bars.
13 | */
14 | export default function removeEmptyBars(tune) {
15 | const newTune = Object.assign({}, tune);
16 | newTune.parts = newTune.parts.map((part, partIndex) => {
17 | const newPart = Object.assign({}, part);
18 | newPart.bars = part.bars.filter((bar, i) => {
19 | const newBar = Object.assign({}, bar);
20 | if (newBar.notes.length === 0) {
21 | // key signature needs to be applied to the next bar
22 | if (newBar.abcKeySignature) {
23 | if (i + 1 < newPart.bars.length) {
24 | newPart.bars[i + 1].abcKeySignature = newBar.abcKeySignature;
25 | newPart.bars[i + 1].cancelKeySig = newBar.cancelKeySig;
26 | } else if (partIndex < (newTune.parts.length - 1) && newTune.parts[partIndex + 1].bars.length > 0) {
27 | newTune.parts[partIndex + 1].bars[0].abcKeySignature = newBar.abcKeySignature;
28 | newTune.parts[partIndex + 1].bars[0].cancelKeySig = newBar.cancelKeySig;
29 | } else {
30 | // key signature gets lost?
31 | }
32 | }
33 |
34 | // REPEAT_END needs to be applied to the previous bar
35 | if (newBar.repeats.includes(Vex.Flow.Barline.type.REPEAT_END)) {
36 | if (i > 0) {
37 | newPart.bars[i - 1].repeats.push(Vex.Flow.Barline.type.REPEAT_END);
38 | } else {
39 | // console.log('LOST A REPEAT_END');
40 | }
41 | }
42 |
43 | // REPEAT_BEGIN needs to be applied to the next bar
44 | if (newBar.repeats.includes(Vex.Flow.Barline.type.REPEAT_BEGIN)) {
45 | if (i + 1 < newPart.bars.length) {
46 | newPart.bars[i + 1].repeats.push(Vex.Flow.Barline.type.REPEAT_BEGIN);
47 | } else {
48 | // console.log('LOST A REPEAT_BEGIN');
49 | }
50 | }
51 |
52 | // BEGIN volta needs to be applied to next bar, END volta needs to be
53 | // applied to previous bar. if there is no next / previous bar, the volta will
54 | // be lost... but that wouldn't make sense anyway if it's a BEGIN or END volta,
55 | // there should always be a next / previous bar. Otherwise it would be a BEGIN_END volta
56 | if (newBar.volta) {
57 | if (newBar.volta.type === Vex.Flow.Volta.type.BEGIN && i + 1 < newPart.bars.length) {
58 | const nextBar = newPart.bars[i + 1];
59 | if (nextBar.volta && nextBar.volta.type === Vex.Flow.Volta.type.MID) {
60 | nextBar.volta = {
61 | number: newBar.volta.number,
62 | type: Vex.Flow.Volta.type.BEGIN
63 | };
64 | } else if (nextBar.volta && nextBar.volta.type === Vex.Flow.Volta.type.END) {
65 | nextBar.volta = {
66 | number: newBar.volta.number,
67 | type: Vex.Flow.Volta.type.BEGIN_END
68 | };
69 | }
70 | } else if (newBar.volta.type === Vex.Flow.Volta.type.END && i > 0) {
71 | const prevBar = newPart.bars[i - 1];
72 | if (prevBar.volta && prevBar.volta.type === Vex.Flow.Volta.type.MID) {
73 | prevBar.volta = {
74 | number: 0,
75 | type: Vex.Flow.Volta.type.END
76 | };
77 | } else if (prevBar.volta && prevBar.volta.type === Vex.Flow.Volta.type.BEGIN) {
78 | prevBar.volta = {
79 | number: prevBar.volta.number,
80 | type: Vex.Flow.Volta.type.BEGIN_END
81 | };
82 | }
83 | }
84 | }
85 | return false;
86 | }
87 | return true;
88 | });
89 | return newPart;
90 | });
91 | return newTune;
92 | }
93 |
--------------------------------------------------------------------------------
/lib/main/set-bar-positions.js:
--------------------------------------------------------------------------------
1 | import Vex from 'vexflow';
2 | import { Formatter } from 'vexflow/src/formatter';
3 |
4 | const NEW_PART_MULTIPLIER = 1.25;
5 |
6 | /**
7 | * Takes the Tune and sets the .position properties of each Bar object contained there.
8 | * Sets width of each Bar according to the renderOptions and based on the contents of
9 | * that Bar, as determined by VexFlow preCalculateMinTotalWidth method.
10 | * Determines when new line is necessary and places a newline and a slightly larger
11 | * vertical gap to mark the beginning of a new Part.
12 | * @param {Object} tuneData The array of Part objects
13 | *
14 | * @returns {Object} Array of Part objects
15 | */
16 | export default function setBarPositions(tune) {
17 | const {
18 | renderWidth, xOffset, widthFactor, lineHeight, clefWidth, meterWidth, repeatWidthModifier, keySigAccidentalWidth, tuning, tabsVisibility, staveVisibility
19 | } = tune.renderOptions;
20 |
21 | let yCursor = (0 - (lineHeight * 1.25));
22 | const newTune = Object.assign({}, tune);
23 | const tabNumberOfLines = tuning.strings ? tuning.strings.length : 1;
24 |
25 | newTune.parts = tune.parts.map((part, partIndex) => {
26 | const newPart = Object.assign({}, part);
27 | newPart.bars = newPart.bars.map((bar, barIndex) => {
28 | const newBar = Object.assign({}, bar);
29 |
30 | // calculate space needed for clefSigMeterWidth
31 | if (newBar.clef) { newBar.position.clefSigMeterWidth += clefWidth; }
32 | if (newBar.meter) { newBar.position.clefSigMeterWidth += meterWidth; }
33 | if (newBar.abcKeySignature) { // even if it's a cancelled key sig to C, should still include the natural accidentals here
34 | newBar.position.clefSigMeterWidth += newBar.abcKeySignature.accidentals.length * keySigAccidentalWidth;
35 | }
36 |
37 | // get vexFlow to tell me how much space the notes need
38 | const formatter = new Formatter();
39 | formatter.createTickContexts([newBar.voice]);
40 | let notesWidth = formatter.preCalculateMinTotalWidth([newBar.voice]) * widthFactor;
41 |
42 | // it still doesn't give enough space, so add more if there are few notes in the bar
43 | notesWidth *= 1 + 3 / ((newBar.notes.length + 1) * (newBar.notes.length + 1));
44 |
45 | // extra space for accidentals (sharp and flat signs)
46 | const notesWithAccidentals = newBar.notes.reduce((acc, note) => {
47 | if (note.modifiers) {
48 | note.modifiers.forEach((modifier) => {
49 | if (modifier.accidental) {
50 | acc += 1;
51 | }
52 | });
53 | }
54 | return acc;
55 | }, 0);
56 | notesWidth += notesWithAccidentals * keySigAccidentalWidth;
57 |
58 | // determine total min width of the bar including clefSigMeterWidth
59 | let minWidth = notesWidth + newBar.position.clefSigMeterWidth;
60 | if (newBar.repeats.includes(Vex.Flow.Barline.type.REPEAT_END)) {
61 | minWidth += repeatWidthModifier;
62 | }
63 | if (minWidth > renderWidth) { minWidth = renderWidth; }
64 |
65 | const spaceForStave = lineHeight * 0.5;
66 | const spaceForTabs = lineHeight * ((14 - (6 - tabNumberOfLines)) / 14) - spaceForStave;
67 |
68 | if (barIndex === 0) { // first bar of part
69 | newBar.position.x = xOffset;
70 |
71 | if (partIndex === 0) { // first part
72 | yCursor += (lineHeight * NEW_PART_MULTIPLIER); // very top of tune
73 | } else {
74 | if (tabsVisibility) {
75 | yCursor += spaceForTabs * NEW_PART_MULTIPLIER;
76 | }
77 | if (staveVisibility) {
78 | yCursor += spaceForStave * NEW_PART_MULTIPLIER;
79 | }
80 | }
81 | } else if (newPart.bars[barIndex - 1].position.x + newPart.bars[barIndex - 1].position.width + minWidth > renderWidth) { // first bar of a new line
82 | newBar.position.x = xOffset;
83 | if (tabsVisibility) {
84 | yCursor += spaceForTabs;
85 | }
86 | if (staveVisibility) {
87 | yCursor += spaceForStave;
88 | }
89 | } else { // bar on an incomplete line
90 | newBar.position.x = newPart.bars[barIndex - 1].position.x + newPart.bars[barIndex - 1].position.width;
91 | }
92 | newBar.position.y = yCursor;
93 | newBar.position.width = minWidth;
94 |
95 | return newBar;
96 | });
97 |
98 | let firstBarY;
99 | newPart.curves.forEach((curve) => {
100 | newPart.bars.forEach((bar) => {
101 | bar.notes.forEach((note) => {
102 | if (note === curve.startNote) {
103 | firstBarY = bar.position.y;
104 | }
105 | if (note === curve.endNote) {
106 | if (firstBarY !== bar.position.y) {
107 | newPart.curves.push({ endNote: curve.endNote });
108 | curve.endNote = null;
109 | }
110 | }
111 | });
112 | });
113 | });
114 |
115 | return newPart;
116 | });
117 | return newTune;
118 | }
119 |
--------------------------------------------------------------------------------
/lib/main/tests/fill-empty-space.test.js:
--------------------------------------------------------------------------------
1 | import { merge } from '../../js-utils/combine-merge';
2 | import fillEmptySpace from '../fill-empty-space';
3 | import Parts from '../../test-data/parts';
4 | import RenderOptions from '../../test-data/render-options';
5 | import TuneAttrsJigA from '../../test-data/tune-attrs-jig-a';
6 |
7 | // TODO: MULTI LINE PARTS, MORE THAN 2 BARS PER PART
8 |
9 | test('should extend last bar to end of renderWidth', () => {
10 | const tune = {
11 | renderOptions: RenderOptions,
12 | tuneAttrs: TuneAttrsJigA,
13 | parts: [
14 | Parts.TwoEmptyBars,
15 | Parts.TwoEmptyBars
16 | ]
17 | };
18 |
19 | const customTune = merge(tune, {
20 | parts: [{
21 | bars: [{
22 | position: {
23 | x: 0,
24 | y: 100,
25 | width: 100
26 | }
27 | }, {
28 | position: {
29 | x: 100,
30 | y: 100,
31 | width: 12
32 | }
33 | }]
34 | }, { // next part
35 | bars: [{
36 | position: {
37 | x: 0,
38 | y: 200,
39 | width: 50
40 | }
41 | }, {
42 | position: {
43 | x: 50,
44 | y: 200,
45 | width: 150
46 | }
47 | }]
48 | }]
49 | });
50 |
51 | const output = fillEmptySpace(customTune);
52 | expect(output.parts[0].bars[0].position.width + output.parts[0].bars[1].position.width).toBe(RenderOptions.renderWidth);
53 | expect(output.parts[1].bars[0].position.width + output.parts[1].bars[1].position.width).toBe(RenderOptions.renderWidth);
54 | });
55 |
56 | test('sum of bar widths should be renderWidth', () => {
57 | const tune = {
58 | renderOptions: RenderOptions,
59 | tuneAttrs: TuneAttrsJigA,
60 | parts: [
61 | Parts.TwoEmptyBars,
62 | Parts.TwoEmptyBars
63 | ]
64 | };
65 |
66 | const customTune = merge(tune, {
67 | parts: [{
68 | bars: [{
69 | position: {
70 | x: 0,
71 | y: 100,
72 | width: 130
73 | }
74 | }, {
75 | position: {
76 | x: 130,
77 | y: 100,
78 | width: 12
79 | }
80 | }]
81 | }, { // next part
82 | bars: [{
83 | position: {
84 | x: 0,
85 | y: 200,
86 | width: 331
87 | }
88 | }, {
89 | position: {
90 | x: 331,
91 | y: 200,
92 | width: 150
93 | }
94 | }]
95 | }]
96 | });
97 |
98 | const output = fillEmptySpace(customTune);
99 | expect(output.parts[0].bars[0].position.width + output.parts[0].bars[1].position.width).toBe(RenderOptions.renderWidth);
100 | expect(output.parts[1].bars[0].position.width + output.parts[1].bars[1].position.width).toBe(RenderOptions.renderWidth);
101 | });
102 |
--------------------------------------------------------------------------------
/lib/main/tests/generate-vex-objects.test.js:
--------------------------------------------------------------------------------
1 | // VexFlow methods to mock
2 | import { StaveNote } from 'vexflow/src/stavenote';
3 | import { TabNote } from 'vexflow/src/tabnote';
4 | import { Voice } from 'vexflow/src/voice';
5 | import { Beam } from 'vexflow/src/beam';
6 |
7 | // Function being tested
8 | import generateVexObjects from '../generate-vex-objects';
9 |
10 | // My own methods to mock
11 | import { getVexDuration } from '../../utils';
12 |
13 | // test data
14 | import TuneAttrsJigA from '../../test-data/tune-attrs-jig-a';
15 | import RenderOptions from '../../test-data/render-options';
16 | import PartRegions from '../../test-data/part-regions';
17 |
18 | jest.mock('../../utils');
19 | getVexDuration.mockReturnValue({ duration: '8', isDotted: false });
20 |
21 | jest.mock('vexflow/src/stavenote');
22 | jest.mock('vexflow/src/tabnote');
23 | jest.mock('vexflow/src/voice');
24 | jest.mock('vexflow/src/beam');
25 |
26 | StaveNote.mockReturnValue({});
27 | TabNote.mockReturnValue({});
28 | Voice.mockReturnValue({
29 | setStrict: jest.fn(),
30 | addTickables: jest.fn(),
31 | });
32 | Beam.getDefaultBeamGroups.mockReturnValue({});
33 |
34 | // TODO: assert calls to mocked functions?
35 |
36 | test('should generate 2 parts with 2 bars each', () => {
37 | const partRegions = [
38 | PartRegions.TwoEmptyBars,
39 | PartRegions.TwoEmptyBars
40 | ];
41 |
42 | const output = generateVexObjects(partRegions, TuneAttrsJigA, RenderOptions);
43 | expect(output.parts[0].bars.length).toBe(2);
44 | expect(output.parts[1].bars.length).toBe(2);
45 | });
46 |
47 | test('should generate 2 parts with 2 bars each with 2 notes each', () => {
48 | const partRegions = [
49 | PartRegions.TwoBarsTwoNotesEach,
50 | PartRegions.TwoBarsTwoNotesEach
51 | ];
52 |
53 | const output = generateVexObjects(partRegions, TuneAttrsJigA, RenderOptions);
54 | expect(output.parts[0].bars[0].notes.length).toBe(2);
55 | expect(output.parts[0].bars[1].notes.length).toBe(2);
56 | expect(output.parts[1].bars[0].notes.length).toBe(2);
57 | expect(output.parts[1].bars[1].notes.length).toBe(2);
58 | });
59 |
--------------------------------------------------------------------------------
/lib/main/tests/set-bar-positions.test.js:
--------------------------------------------------------------------------------
1 | import { Formatter } from 'vexflow/src/formatter';
2 | import { merge } from '../../js-utils/combine-merge';
3 | import setBarPositions from '../set-bar-positions';
4 | import Parts from '../../test-data/parts';
5 | import RenderOptions from '../../test-data/render-options';
6 | import TuneAttrsJigA from '../../test-data/tune-attrs-jig-a';
7 | import StaveNotes from '../../test-data/stave-notes';
8 |
9 | jest.mock('vexflow/src/formatter');
10 | Formatter.mockReturnValue({
11 | createTickContexts: jest.fn(),
12 | preCalculateMinTotalWidth: jest.fn(),
13 | });
14 |
15 | /*
16 | Still need to figure out what to assert
17 | */
18 | test('two parts two empty bars each', () => {
19 | const tune = {
20 | renderOptions: RenderOptions,
21 | tuneAttrs: TuneAttrsJigA,
22 | parts: [
23 | Parts.TwoEmptyBars,
24 | Parts.TwoEmptyBars
25 | ]
26 | };
27 |
28 | const output = setBarPositions(tune);
29 | // expect(output.parts[0].bars[0].position.width + output.parts[0].bars[1].position.width).toBe(RenderOptions.renderWidth)
30 | // expect(output.parts[1].bars[0].position.width + output.parts[0].bars[1].position.width).toBe(RenderOptions.renderWidth)
31 | });
32 |
33 | test('two parts two bars each two notes each', () => {
34 | const tune = {
35 | renderOptions: RenderOptions,
36 | tuneAttrs: TuneAttrsJigA,
37 | parts: [
38 | Parts.TwoEmptyBars,
39 | Parts.TwoEmptyBars
40 | ]
41 | };
42 |
43 | const customTune = merge(tune, {
44 | parts: [{
45 | bars: [{
46 | notes: StaveNotes.FakeStaveNoteArrayFactory(2, 2, 0, ['f/5'], 1)
47 | }, {
48 | notes: StaveNotes.FakeStaveNoteArrayFactory(2, 2, 0, ['f/5'], 1)
49 | }]
50 | }, { // next part
51 | bars: [{
52 | notes: StaveNotes.FakeStaveNoteArrayFactory(2, 2, 0, ['f/5'], 1)
53 | }, {
54 | notes: StaveNotes.FakeStaveNoteArrayFactory(2, 2, 0, ['f/5'], 1)
55 | }]
56 | }]
57 | });
58 |
59 | const output = setBarPositions(customTune);
60 | // expect(output.parts[0].bars[0].position.width + output.parts[0].bars[1].position.width).toBe(RenderOptions.renderWidth);
61 | // expect(output.parts[1].bars[0].position.width + output.parts[1].bars[1].position.width).toBe(RenderOptions.renderWidth);
62 | });
63 |
--------------------------------------------------------------------------------
/lib/models/bar-region.js:
--------------------------------------------------------------------------------
1 | export default function BarRegion() {
2 | this.startBarLine = {};
3 | this.endBarLine = {};
4 | this.contents = [];
5 | Object.seal(this);
6 | }
7 |
--------------------------------------------------------------------------------
/lib/models/bar.js:
--------------------------------------------------------------------------------
1 | export default class Bar {
2 | constructor() {
3 | this.notes = []; // includes rests
4 | this.tabNotes = [];
5 | this.beams = [];
6 | this.decorations = [];
7 | this.repeats = [];
8 | this.isFirst = false; // to identify what will usually be the lead-in bar
9 | this.abcKeySignature = null;
10 | this.cancelKeySig = null;
11 | this.clef = '';
12 | this.meter = '';
13 | this.voice = null;
14 | this.tuplets = [];
15 | this.tabTuplets = [];
16 | this.volta = null;
17 | this.position = {
18 | x: 0,
19 | y: 0,
20 | width: 0,
21 | // width of the 'invisible' extra bar to be drawn if necessary due to the fact that i couldn't get
22 | // spacing to match up when I was drawing things like Clef, Time Signature, Key Signature, in the
23 | // top (music) staff but not in the bottom (tab) staff, the tab notes wouldn't align with the
24 | // music notes
25 | clefSigMeterWidth: 0
26 | };
27 | Object.seal(this);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/lib/models/part-region.js:
--------------------------------------------------------------------------------
1 | export default function PartRegion(title) {
2 | this.title = title;
3 | this.barRegions = [];
4 | Object.seal(this);
5 | }
6 |
--------------------------------------------------------------------------------
/lib/models/part.js:
--------------------------------------------------------------------------------
1 | export default class Part {
2 | constructor(title) {
3 | this.title = title; // i don't really use this...
4 | this.bars = []; // the Bar class from bar.js
5 | this.curves = [];
6 | Object.seal(this);
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/lib/models/tune.js:
--------------------------------------------------------------------------------
1 | export default class Tune {
2 | constructor(tuneAttrs, renderOptions) {
3 | this.tuneAttrs = tuneAttrs;
4 | this.renderOptions = renderOptions;
5 | this.parts = []; // the Part class from part.js
6 | Object.seal(this);
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/lib/test-data/abc-key-signatures.js:
--------------------------------------------------------------------------------
1 | const GMajor = {
2 | accidentals: [
3 | {
4 | note: 'f',
5 | acc: 'sharp'
6 | }
7 | ]
8 | };
9 |
10 | const CMajor = {
11 | accidentals: []
12 | };
13 |
14 | const BFlatMajor = {
15 | accidentals: [
16 | {
17 | acc: 'flat',
18 | note: 'B' // 'B' is actually how it comes from the abcjs parser
19 | },
20 | {
21 | acc: 'flat',
22 | note: 'e'
23 | }
24 | ]
25 | };
26 |
27 | const DMajor = {
28 | accidentals: [
29 | {
30 | acc: 'sharp',
31 | note: 'c'
32 | },
33 | {
34 | acc: 'sharp',
35 | note: 'f'
36 | }
37 |
38 | ]
39 |
40 | };
41 |
42 | const AbcKeySignatures = { CMajor, DMajor, GMajor, BFlatMajor };
43 | export default AbcKeySignatures;
44 |
--------------------------------------------------------------------------------
/lib/test-data/abcjs-objects.js:
--------------------------------------------------------------------------------
1 | // middle B in treble clef (b/5) is abc pitch number 6
2 |
3 | const Notes = {
4 | Eighths: {
5 | F: {
6 | pitches: [
7 | {
8 | pitch: 10,
9 | verticalPos: 10
10 | }
11 | ],
12 | duration: 0.125,
13 | el_type: 'note',
14 | startChar: 313,
15 | endChar: 318,
16 | // endBeam: true // will need to test beaming sometime
17 | },
18 | FSharp: {
19 | pitches: [
20 | {
21 | pitch: 10,
22 | verticalPos: 10,
23 | accidental: 'sharp'
24 | }
25 | ],
26 | duration: 0.125,
27 | el_type: 'note',
28 | startChar: 313,
29 | endChar: 318,
30 | // endBeam: true
31 | },
32 | FNatural: {
33 | pitches: [
34 | {
35 | pitch: 10,
36 | verticalPos: 10,
37 | accidental: 'natural'
38 | }
39 | ],
40 | duration: 0.125,
41 | el_type: 'note',
42 | startChar: 313,
43 | endChar: 318,
44 | // endBeam: true
45 | },
46 | B: {
47 | pitches: [
48 | {
49 | pitch: 6,
50 | verticalPos: 6
51 | // accidental: 'sharp'
52 | }
53 | ],
54 | duration: 0.125,
55 | el_type: 'note',
56 | startChar: 313,
57 | endChar: 318,
58 | // endBeam: true
59 | },
60 | CWithFGraceNote: {
61 | pitches: [
62 | {
63 | pitch: 7,
64 | verticalPos: 7
65 | }
66 | ],
67 | gracenotes: [
68 | {
69 | pitch: 10,
70 | verticalPos: 10
71 | }
72 | ],
73 | duration: 0.125,
74 | el_type: 'note',
75 | startChar: 313,
76 | endChar: 318,
77 | // endBeam: true // will need to test beaming sometime
78 | },
79 | CWithFSharpGraceNote: {
80 | pitches: [
81 | {
82 | pitch: 7,
83 | verticalPos: 7,
84 | }
85 | ],
86 | gracenotes: [
87 | {
88 | pitch: 10,
89 | verticalPos: 10,
90 | accidental: 'sharp'
91 | }
92 | ],
93 | duration: 0.125,
94 | el_type: 'note',
95 | startChar: 313,
96 | endChar: 318,
97 | // endBeam: true
98 | },
99 | CWithFNaturalGraceNote: {
100 | pitches: [
101 | {
102 | pitch: 7,
103 | verticalPos: 7,
104 | }
105 | ],
106 | gracenotes: [
107 | {
108 | pitch: 10,
109 | verticalPos: 10,
110 | accidental: 'natural'
111 | }
112 | ],
113 | duration: 0.125,
114 | el_type: 'note',
115 | startChar: 313,
116 | endChar: 318,
117 | // endBeam: true
118 | },
119 | FWithFSharpGraceNote: {
120 | pitches: [
121 | {
122 | pitch: 10,
123 | verticalPos: 10,
124 | }
125 | ],
126 | gracenotes: [
127 | {
128 | pitch: 10,
129 | verticalPos: 10,
130 | accidental: 'sharp'
131 | }
132 | ],
133 | duration: 0.125,
134 | el_type: 'note',
135 | startChar: 313,
136 | endChar: 318,
137 | // endBeam: true
138 | },
139 | FSharpWithFGraceNote: {
140 | pitches: [
141 | {
142 | pitch: 10,
143 | verticalPos: 10,
144 | accidental: 'sharp'
145 | }
146 | ],
147 | gracenotes: [
148 | {
149 | pitch: 10,
150 | verticalPos: 10,
151 | }
152 | ],
153 | duration: 0.125,
154 | el_type: 'note',
155 | startChar: 313,
156 | endChar: 318,
157 | // endBeam: true
158 | },
159 | FSharpWithFFlatGraceNote: {
160 | pitches: [
161 | {
162 | pitch: 10,
163 | verticalPos: 10,
164 | accidental: 'sharp'
165 | }
166 | ],
167 | gracenotes: [
168 | {
169 | pitch: 10,
170 | verticalPos: 10,
171 | accidental: 'flat'
172 | }
173 | ],
174 | duration: 0.125,
175 | el_type: 'note',
176 | startChar: 313,
177 | endChar: 318,
178 | // endBeam: true
179 | },
180 | },
181 | };
182 | const AbcjsObjects = { Notes };
183 | export default AbcjsObjects;
184 |
--------------------------------------------------------------------------------
/lib/test-data/bar-regions.js:
--------------------------------------------------------------------------------
1 | import AbcjsObjects from './abcjs-objects';
2 |
3 | const Empty = {
4 | startBarLine: {},
5 | endBarLine: {},
6 | contents: []
7 | };
8 |
9 | const TwoNotes = {
10 | startBarLine: {},
11 | endBarLine: {},
12 | contents: [
13 | AbcjsObjects.Notes.Eighths.F,
14 | AbcjsObjects.Notes.Eighths.F
15 | ]
16 | };
17 |
18 | const BarRegions = { Empty, TwoNotes };
19 | export default BarRegions;
20 |
--------------------------------------------------------------------------------
/lib/test-data/bars.js:
--------------------------------------------------------------------------------
1 | import StaveNotes from './stave-notes';
2 | import Bar from '../models/bar';
3 |
4 | const EmptyBar = new Bar();
5 |
6 | const TwoNotes = new Bar();
7 | TwoNotes.notes = StaveNotes.FakeStaveNoteArrayFactory(2, 4, 0, ['f/5'], 1);
8 |
9 | const Bars = { EmptyBar, TwoNotes };
10 |
11 | export default Bars;
12 |
--------------------------------------------------------------------------------
/lib/test-data/part-regions.js:
--------------------------------------------------------------------------------
1 | import BarRegions from './bar-regions';
2 |
3 | const TwoEmptyBars = {
4 | barRegions: [
5 | BarRegions.Empty,
6 | BarRegions.Empty
7 | ]
8 | };
9 |
10 | const TwoBarsTwoNotesEach = {
11 | barRegions: [
12 | BarRegions.TwoNotes,
13 | BarRegions.TwoNotes
14 | ]
15 | };
16 |
17 | const PartRegions = { TwoEmptyBars, TwoBarsTwoNotesEach };
18 | export default PartRegions;
19 |
--------------------------------------------------------------------------------
/lib/test-data/parts.js:
--------------------------------------------------------------------------------
1 | import Bars from './bars';
2 |
3 | const TwoEmptyBars = {
4 | bars: [
5 | Bars.EmptyBar,
6 | Bars.EmptyBar
7 | ],
8 | curves: []
9 | };
10 |
11 | const FourEmptyBars = {
12 | bars: [
13 | Bars.EmptyBar,
14 | Bars.EmptyBar,
15 | Bars.EmptyBar,
16 | Bars.EmptyBar
17 | ],
18 | curves: []
19 | };
20 |
21 | const TwoBarsTwoNotesEach = {
22 | bars: [
23 | Bars.TwoNotes,
24 | Bars.TwoNotes
25 | ],
26 | curves: []
27 | };
28 |
29 | const Parts = { TwoEmptyBars, FourEmptyBars, TwoBarsTwoNotesEach };
30 | export default Parts;
31 |
--------------------------------------------------------------------------------
/lib/test-data/render-options.js:
--------------------------------------------------------------------------------
1 |
2 | const RenderOptions = {
3 | xOffset: 3,
4 | widthFactor: 1.5,
5 | lineHeight: 185,
6 | clefWidth: 40,
7 | meterWidth: 30,
8 | repeatWidthModifier: 35,
9 | keySigAccidentalWidth: 20,
10 | tabsVisibility: 1,
11 | voltaHeight: 25,
12 | renderWidth: 650,
13 | tuning: {
14 | displayName: 'Guitar (EADGBE)',
15 | strings: ['e/3', 'a/3', 'd/4', 'g/4', 'b/4', 'e/5'],
16 | type: 'strings_fretted'
17 | },
18 | };
19 |
20 | export default RenderOptions;
21 |
--------------------------------------------------------------------------------
/lib/test-data/stave-notes.js:
--------------------------------------------------------------------------------
1 | class FakeStaveNote {
2 | constructor(duration, dots, keys, stemDirection) {
3 | this.duration = duration;
4 | this.dots = dots;
5 | this.keys = keys;
6 | this.stem_direction = stemDirection;
7 | }
8 |
9 | getStemDirection() {
10 | return this.stem_direction;
11 | }
12 |
13 | setStemDirection(direction) {
14 | this.stem_direction = direction;
15 | }
16 | }
17 |
18 | /**
19 | * Returns an array of fake StaveNote objects to use in testing
20 | * @param {number} howMany how many to create
21 | * @param {number} duration duration such as '8'
22 | * @param {number} for dotted note durations, how many dots
23 | * @param {array} keys such as ['f/5']
24 | * @param stemDirection 'alternate_stems' to alternate, otherwise numeric -1 or 1 (the values VexFlow actually uses)
25 | *
26 | * @returns {Array} the array of fake StaveNotes
27 | */
28 |
29 | function FakeStaveNoteArrayFactory(howMany, duration, dots, keys, stemDirection) {
30 | const notesArray = [];
31 |
32 | for (let i = 0; i < howMany; i += 1) {
33 | const alternatingDirection = i % 2 ? -1 : 1;
34 | const direction = stemDirection === 'alternate_stems' ? alternatingDirection : stemDirection;
35 | const note = new FakeStaveNote(duration, dots, keys, direction);
36 | notesArray.push(note);
37 | }
38 |
39 | return notesArray;
40 | }
41 |
42 | export default { FakeStaveNoteArrayFactory, FakeStaveNote };
43 |
--------------------------------------------------------------------------------
/lib/test-data/tune-attrs-jig-a.js:
--------------------------------------------------------------------------------
1 | const TuneAttrs = {
2 | meter: '6/8',
3 | clef: 'treble',
4 | abcKeySignature: {
5 | accidentals: [
6 | {
7 | acc: 'sharp',
8 | note: 'f',
9 | verticalPos: 10
10 | },
11 | {
12 | acc: 'sharp',
13 | note: 'c',
14 | verticalPos: 7
15 | },
16 | {
17 | acc: 'sharp',
18 | note: 'g',
19 | verticalPos: 11
20 | }
21 | ],
22 | root: 'A',
23 | acc: '',
24 | mode: ''
25 | }
26 | };
27 |
28 | export default TuneAttrs;
29 |
--------------------------------------------------------------------------------
/lib/utils/add-decorations.js:
--------------------------------------------------------------------------------
1 | import { Articulation } from 'vexflow/src/articulation';
2 | import { Ornament } from 'vexflow/src/ornament';
3 | import Vex from 'vexflow';
4 |
5 | export function addDecorations(noteToAdd, decorations) {
6 | if (decorations && decorations.length > 0) {
7 | decorations.forEach((decoration) => {
8 | switch (decoration) {
9 | case 'staccato':
10 | noteToAdd.addArticulation(0, new Articulation('a.').setPosition(3));
11 | break;
12 | case 'irishroll':
13 | noteToAdd.addModifier(0, new Vex.Flow.Annotation('~')
14 | .setVerticalJustification(Vex.Flow.Annotation.VerticalJustify.TOP)
15 | .setFont('serif', 20, undefined));
16 | break;
17 | case 'fermata':
18 | noteToAdd.addArticulation(0, new Articulation('a@a').setPosition(3));
19 | break;
20 | case 'accent':
21 | noteToAdd.addArticulation(0, new Articulation('a>').setPosition(3));
22 | break;
23 | case 'upbow':
24 | noteToAdd.addArticulation(0, new Articulation('a|').setPosition(3));
25 | break;
26 | case 'downbow':
27 | noteToAdd.addArticulation(0, new Articulation('am').setPosition(3));
28 | break;
29 | case 'trill':
30 | noteToAdd.addModifier(0, new Ornament('tr'));
31 | break;
32 | case 'mordent':
33 | noteToAdd.addModifier(0, new Ornament('mordent_inverted'));
34 | break;
35 | case 'pralltriller':
36 | noteToAdd.addModifier(0, new Ornament('mordent'));
37 | break;
38 | case 'coda':
39 | case 'segno':
40 | default:
41 | break;
42 | }
43 | });
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/lib/utils/generate-beams-compound.js:
--------------------------------------------------------------------------------
1 | import { Beam } from 'vexflow/src/beam';
2 |
3 | /**
4 | * Takes an array of the StaveNotes in a measure, and returns an array
5 | * of Beams. This is only for compound time signatures (3/8, 6/8,
6 | * 9/8, 12/8) as VexFlow's built-in beaming code hasn't worked for this.
7 | * This method doesn't need to know exactly what the time signature is,
8 | * just that it's compound something/8.
9 | * @param {Array} notes the StaveNotes in this bar
10 | *
11 | * @returns {Array} the Beams for this bar
12 | */
13 | export function generateBeamsCompound(notes) {
14 | let timeLeft = 0.375;
15 | let notesToBeam = [];
16 | const beams = [];
17 |
18 | notes.forEach((note) => {
19 | let duration; let isRest;
20 |
21 | if (note.duration.includes('r')) {
22 | duration = 1 / (note.duration.slice(0, note.duration.indexOf('r')));
23 | isRest = true;
24 | } else {
25 | duration = 1 / note.duration;
26 | isRest = false;
27 | }
28 |
29 | if (note.tuplet) { duration *= (note.tuplet.notes_occupied / note.tuplet.num_notes); }
30 |
31 | switch (note.dots) {
32 | case 0:
33 | break;
34 | case 1:
35 | duration *= 1.5;
36 | break;
37 | case 2:
38 | duration *= 1.75;
39 | break;
40 | case 3:
41 | duration *= 1.875;
42 | break;
43 | default:
44 | break;
45 | }
46 |
47 | if (duration >= 0.250 || timeLeft <= 0) { // purge existing beams
48 | if (notesToBeam.length > 1) {
49 | beams.push(setStemDirectionandGenerateBeam(notesToBeam));
50 | }
51 | if (timeLeft <= 0) {
52 | timeLeft += 0.375;
53 | }
54 | notesToBeam = [];
55 | }
56 |
57 | if (duration < 0.250 && timeLeft >= duration && !isRest) {
58 | notesToBeam.push(note);
59 | }
60 | timeLeft -= duration;
61 | });
62 |
63 | // deal w/ notes left over at end of iterations
64 | if (notesToBeam.length > 1) {
65 | beams.push(setStemDirectionandGenerateBeam(notesToBeam));
66 | }
67 |
68 | return beams;
69 | }
70 |
71 | /**
72 | * Takes an array of the StaveNotes to be beamed, sets
73 | * the stem_direction of each note to be the same as the
74 | * first note, and returns a Beam of those notes.
75 | * @param {Array} notes the StaveNotes to beam, should have
76 | * length greater than 1, otherwise there's no point.
77 | *
78 | * @returns {Array} the Beam of the notes.
79 | */
80 | function setStemDirectionandGenerateBeam(notesToBeam) {
81 | const direction = notesToBeam[0].getStemDirection();
82 | notesToBeam.forEach((noteToBeam) => {
83 | noteToBeam.setStemDirection(direction);
84 | });
85 | return new Beam(notesToBeam);
86 | }
87 |
--------------------------------------------------------------------------------
/lib/utils/get-curves.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Takes an ABCJS parser output obj to extract the start/end curve (tie/slur)
3 | * markers that are attached to the obj or individual pitches in the obj. The .curves[] array
4 | * will be used later on to create the VexFlow Curve objects. Can't create them here because we
5 | * need to position the bars first before we can create the Curves, in order to be able to handle curves
6 | * that go across line breaks.
7 | *
8 | * @param {Array} curves the Part.curves[] array as it exists so far
9 | * @param {object} obj the obj element from the abcjs parser output array
10 | * @param {StaveNote} noteToAdd the VexFlow note that was created earlier in the GenerateVexObjects loop iteration
11 | *
12 | * @returns {Array} updated curves[] with the relevant curve markers added with a reference to noteToAdd
13 | */
14 | export function getCurves(curves, obj, noteToAdd) {
15 | const newCurves = [...curves];
16 |
17 | if (obj.startSlur) {
18 | obj.startSlur.forEach(() => {
19 | newCurves.push({
20 | startNote: noteToAdd
21 | });
22 | });
23 | }
24 | if (obj.endSlur) {
25 | obj.endSlur.forEach(() => {
26 | let i = newCurves.length - 1;
27 | while (i >= 0) {
28 | if (!newCurves[i].endNote) {
29 | newCurves[i].endNote = noteToAdd;
30 | break;
31 | }
32 | i -= 1;
33 | }
34 | });
35 | }
36 |
37 | // handle curves on pitch
38 | obj.pitches.forEach((pitch) => {
39 | if (pitch.startTie) {
40 | newCurves.push({
41 | startNote: noteToAdd
42 | });
43 | }
44 | if (pitch.endTie) {
45 | // conditional check added for cases with multiple endings where last note of body ties into the ending section
46 | // such as "Debbie's Jig" from Nottingham Dataset. here, we don't want to close the curve in ending 2 (or 3, etc)
47 | // if it's already been closed in ending 1 since we'd just overwrite it
48 | if (!newCurves[newCurves.length - 1].endNote) {
49 | newCurves[newCurves.length - 1].endNote = noteToAdd;
50 | }
51 | let i = newCurves.length - 1;
52 | while (i >= 0) {
53 | if (!newCurves[i].endNote) {
54 | newCurves[i].endNote = noteToAdd;
55 | break;
56 | }
57 | i -= 1;
58 | }
59 | }
60 | if (pitch.startSlur) {
61 | pitch.startSlur.forEach(() => {
62 | newCurves.push({
63 | startNote: noteToAdd
64 | });
65 | });
66 | }
67 | if (pitch.endSlur) {
68 | pitch.endSlur.forEach(() => {
69 | let i = newCurves.length - 1;
70 | while (i >= 0) {
71 | if (!newCurves[i].endNote) {
72 | newCurves[i].endNote = noteToAdd;
73 | break;
74 | }
75 | i -= 1;
76 | }
77 | });
78 | }
79 | });
80 |
81 | return newCurves;
82 | }
83 |
--------------------------------------------------------------------------------
/lib/utils/get-keys.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Converts an array of pitches (from abcjs parsed object) into an array of
3 | * keys that can be used by VexFlow. For example, middle in the treble clef
4 | * is abc pitch number 6.
5 | * @param {Array} abcPitches such as [ { pitch: 6, verticalPos: 6 } ]
6 | *
7 | * @returns {Array} such as [ 'b/4' ]
8 | */
9 | export function getKeys(abcPitches) {
10 | return abcPitches.map((pitch) => {
11 | const notes = ['c', 'd', 'e', 'f', 'g', 'a', 'b'];
12 | const octave = (Math.floor(pitch.pitch / 7));
13 | const vexOctave = octave + 4;
14 | const note = pitch.pitch - (octave * 7);
15 | return `${notes[note]}/${vexOctave.toString()}`;
16 | });
17 | }
18 |
--------------------------------------------------------------------------------
/lib/utils/get-tab-position.js:
--------------------------------------------------------------------------------
1 | import { getKeys } from './get-keys';
2 | import { VEX_ACCIDENTAL_FROM_ABCJS, SEMITONES_FROM_ACCIDENTAL, TUNING_TYPES } from '../constants';
3 | import { getDiatonicFromLetter, getChromaticFromLetter } from './utils';
4 |
5 | /**
6 | * Converts an array of VexFlow keys into array of guitar note positions.
7 | * TODO: handle tab for multiple stacked notes instead of just keys[0]... this isn't really that hard,
8 | * just step through keys[] using the same code, only have to ensure the tab positions aren't on the same string.
9 | *
10 | * @param {Array} keys the notes in VexFlow format such as ['e/3'];
11 | * @param {Object} abcKeySignature key signature in abcjs format
12 | * @param {Array} barContents the previous abcjs note objects in this bar
13 | * @param {number} index the position of the current note in barContents
14 | * @param {Array} tuning object with: array of tuning from lowest string to highest in VexFlow format
15 | * such as ['e/3', 'a/3', 'd/4', 'g/4', 'b/4', 'e/5'], and optionally a showFingerings flag which instructs
16 | * the function to output violin fingerings like finger "1" instead of tab position 2, low finger "v2"
17 | * instead of tab position 3, etc.
18 | * @param {bool} isGraceNote did the keys represent the regular note or grace notes attached
19 | * to note at this barContents index?
20 | *
21 | * @returns {Array} the tab positions such as [{str: 6, fret: 0}]
22 | */
23 | export function getTabPosition(keys, abcKeySignature, barContents, index, tuning, isGraceNote) {
24 | if (isGraceNote === undefined) {
25 | throw new Error('getTabPosition: isGraceNote argument must be supplied');
26 | }
27 |
28 | const diatonic = getDiatonicFromLetter(keys[0]);
29 | const absoluteChromatic = getAbsoluteChromatic(keys[0]);
30 |
31 | // this will hold the chromatic pitch after taking into account previous accidentals in the bar
32 | let adjustedAbsoluteChromatic = absoluteChromatic;
33 |
34 | // apply accidentals in key signature to the note
35 | abcKeySignature.accidentals.forEach((accidental) => {
36 | if (diatonic === getDiatonicFromLetter(accidental.note.toLowerCase())) {
37 | switch (accidental.acc) {
38 | case 'sharp':
39 | adjustedAbsoluteChromatic = absoluteChromatic + 1;
40 | break;
41 | case 'flat':
42 | adjustedAbsoluteChromatic = absoluteChromatic - 1;
43 | break;
44 | default:
45 | break;
46 | }
47 | }
48 | });
49 |
50 | /* apply accidentals from previous notes in the bar to the current note if appropriate (will
51 | overwrite, not add to the changes made above with key signature). when accidental occurs
52 | at the SAME barContents index as the note whose position is being calculated, it needs
53 | to be like this:
54 |
55 | accidental on a regular note at index n:
56 | - position being calculated for a regular note at n: apply accidental
57 | - position being calculated for a grace note at n: do not apply
58 |
59 | accidental on a grace note at index n:
60 | - position being calculated for a regular note at n: apply
61 | - position being calculated for a grace note at n: apply
62 |
63 | or in other words, the precedence should be:
64 | - this is a regular note n:
65 | - apply acc from regular n
66 | - apply acc from grace n
67 | - apply acc from regular n-1
68 | - apply acc from grace n-1
69 | - this is a grace note n:
70 | - apply acc from grace note n
71 | - apply acc from regular n-1
72 | - apply acc from grace n-1
73 |
74 | This is why the previousAppliesToCurrent checks for isGraceNote on the second if block
75 | This is also why the if block that checks for accidentals on grace notes must come
76 | before the if block that checks for accidentals on regular notes, so regular n-1
77 | can have the opportunity to overwrite grace n-1, or in the case of note n and it's not
78 | a grace note, so regular n can overwrite grace n
79 |
80 | Just modified the code to actually step through the arrays of pitches and grace notes
81 | and consider the accidentals of each note in array, instead of just [0]. Haven't considered
82 | what tests are necessary for this. Understand it's not doing the same thing in each case.
83 | With pitches[] it's an array of pitches arranged vertically at one single index in
84 | barContents. with gracenotes[] it's an array of gracenotes arranged horizontally
85 | preceding the regular notes at that index
86 | */
87 | barContents.forEach((previousObj, j) => {
88 | if (previousObj.gracenotes && index >= j) {
89 | const previousKeys = getKeys(previousObj.gracenotes);
90 | previousObj.gracenotes.forEach((graceNote, k) => {
91 | const accidental = VEX_ACCIDENTAL_FROM_ABCJS[graceNote.accidental];
92 | if (accidental && diatonic === getDiatonicFromLetter(previousKeys[k])) {
93 | adjustedAbsoluteChromatic = absoluteChromatic + SEMITONES_FROM_ACCIDENTAL[accidental];
94 | }
95 | });
96 | }
97 |
98 | const previousAppliesToCurrent = (index >= j && !isGraceNote) || (index > j);
99 | if (previousAppliesToCurrent && previousObj.el_type === 'note' && !previousObj.rest) {
100 | const previousKeys = getKeys(previousObj.pitches);
101 | previousObj.pitches.forEach((pitch, k) => {
102 | const accidental = VEX_ACCIDENTAL_FROM_ABCJS[pitch.accidental];
103 | if (accidental && diatonic === getDiatonicFromLetter(previousKeys[k])) {
104 | adjustedAbsoluteChromatic = absoluteChromatic + SEMITONES_FROM_ACCIDENTAL[accidental];
105 | }
106 | });
107 | }
108 | });
109 |
110 | if (tuning.type === TUNING_TYPES.WHISTLE) {
111 | return getTinWhistlePosition(adjustedAbsoluteChromatic, tuning.pitchOffset);
112 | } if (tuning.type === TUNING_TYPES.HARMONICA) {
113 | return getHarmonicaPosition(adjustedAbsoluteChromatic, tuning.pitchOffset);
114 | }
115 |
116 | const stringChromaticPitches = tuning.strings.map(string => getAbsoluteChromatic(string));
117 | let left;
118 | let top;
119 |
120 | if (adjustedAbsoluteChromatic < stringChromaticPitches[0]) {
121 | return [{ str: 1, fret: '?' }];
122 | }
123 |
124 | for (let i = 0; i < stringChromaticPitches.length; i += 1) {
125 | if (!(stringChromaticPitches[i + 1] && adjustedAbsoluteChromatic >= stringChromaticPitches[i + 1])) {
126 | top = stringChromaticPitches.length - i;
127 | left = adjustedAbsoluteChromatic - stringChromaticPitches[i];
128 | break;
129 | }
130 | }
131 |
132 | if (tuning.type === TUNING_TYPES.STRINGS_FIDDLE_FINGERINGS) {
133 | left = convertToFingering(left);
134 | }
135 |
136 | return [{ str: top, fret: left }];
137 | }
138 |
139 | /**
140 | * Converts a VexFlow key into a chromatic note number starting from 0 at (C0 or C1 I think)
141 | * @param {string} key the note in VexFlow format such as 'e/3';
142 | *
143 | * @returns {Array} the note number such as 28 ??? or is that E2??
144 | */
145 | function getAbsoluteChromatic(key) {
146 | const chromaticNote = getChromaticFromLetter(key);
147 | const octave = key.charAt(2);
148 | let noteNumber = octave * 12 + chromaticNote;
149 | if (key.charAt(3) === '#') {
150 | noteNumber += 1;
151 | } else if (key.charAt(3) === 'b') {
152 | noteNumber -= 1;
153 | }
154 | return noteNumber;
155 | }
156 |
157 | /**
158 | * Converts a fret position (for a given string) to a violin fingering. Works for first position,
159 | * any notes beyond first position finger 4 will be displayed as '?'
160 | * @param {number} fret the fret such as 2
161 | *
162 | * @returns {string} the violin fingering such as '1'. VexFlow accepts a string or a number
163 | * parameter, so it's not a problem that I'm taking a number and returning string
164 | */
165 | function convertToFingering(fret) {
166 | switch (fret) {
167 | case 0:
168 | return '0';
169 | case 1:
170 | return 'v1';
171 | case 2:
172 | return '1';
173 | case 3:
174 | return 'v2';
175 | case 4:
176 | return '2';
177 | case 5:
178 | return '3';
179 | case 6:
180 | return 'v4';
181 | case 7:
182 | return '4';
183 | default:
184 | return '?';
185 | }
186 | }
187 |
188 | /**
189 | * Converts a chromatic pitch value (should be same as MIDI note number, c3 == 48) to a diatonic harmonica position.
190 | * Supports harmonica in c, a, and g though would be trivial to support every pitch of harmonica.
191 | * @param {number} adjustedAbsoluteChromatic the pitch such as 48 for c3
192 | * @param {string} pitchOffset The pitch offset from 'c' harmonica positions
193 | *
194 | * @returns {Array} the tab positions for VexFlow. VexFlow thinks this is guitar tab, so we still specify string and
195 | * fret, but we can enter any string for fret, so we just write the positions in string form on the first line of tablature
196 | */
197 | function getHarmonicaPosition(adjustedAbsoluteChromatic, pitchOffset) {
198 | // 'd' = draw bend, 'b' = blow bend, 'ob' = overblow, 'od' = overdraw
199 | const harmonicaPositions = [
200 | '^1', // c
201 | 'v1d',
202 | 'v1', // d
203 | '^1ob',
204 | '^2', // e
205 | 'v2dd', // f
206 | 'v2d',
207 | 'v2', // g
208 | 'v3ddd',
209 | 'v3dd', // a
210 | 'v3d',
211 | 'v3', // b
212 | '^4', // c
213 | 'v4d',
214 | 'v4', // d
215 | '^4ob',
216 | '^5', // e
217 | 'v5', // f
218 | '^5ob',
219 | '^6', // g
220 | 'v6d',
221 | 'v6', // a
222 | '^6ob',
223 | 'v7', // b
224 | '^7', // c
225 | 'v7od',
226 | 'v8', // d
227 | '^8b',
228 | '^8', // e
229 | 'v9', // f
230 | '^9b',
231 | '^9', // g
232 | 'v9od',
233 | 'v10', // a
234 | '^10bb',
235 | '^10bb', // b
236 | '^10', // c
237 | 'v10od'
238 | ];
239 |
240 | const startPitch = 48 + pitchOffset;
241 |
242 | if (adjustedAbsoluteChromatic - startPitch >= 0 && adjustedAbsoluteChromatic - startPitch < harmonicaPositions.length) {
243 | return [{ str: 1, fret: harmonicaPositions[adjustedAbsoluteChromatic - startPitch] }];
244 | }
245 | return [{ str: 1, fret: '?' }];
246 | }
247 |
248 | /**
249 | * Converts a chromatic pitch value (should be same as MIDI note number, c3 == 48) to a tin whistle position.
250 | * Supports whistle in d, c, and b flat though would be trivial to support every pitch of whistle.
251 | * @param {number} adjustedAbsoluteChromatic the pitch such as 48 for c3
252 | * @param {string} key The pitch offset from 'd' whistle
253 | *
254 | * @returns {Array} the tab positions for VexFlow. VexFlow thinks this is guitar tab, so we still specify string and
255 | * fret, but we can enter any string for fret, so we just write the positions in string form on the first line of tablature
256 | */
257 | function getTinWhistlePosition(adjustedAbsoluteChromatic, pitchOffset) {
258 | const whistlePositions = [
259 | '6', // D, 1
260 | '5½',
261 | '5', // E, M2
262 | '4½', // F
263 | '4', // M3
264 | '3', // G, P4
265 | '2½',
266 | '2', // A, P5
267 | '1½',
268 | '1', // B, M6
269 | '½', // C
270 | '0', // M7
271 | '6+', // D, P8
272 | '5½+',
273 | '5+', // E, M2
274 | '4½+', // F
275 | '4+', // M3
276 | '3+', // G, P4
277 | '2½+',
278 | '2+', // A, P5
279 | '1½+',
280 | '1+', // B, M6
281 | '½+', // C
282 | '0+' // M7
283 | ];
284 |
285 | // pitch offset for C is -2...
286 | const startPitch = 50 + pitchOffset;
287 |
288 | if (adjustedAbsoluteChromatic - startPitch >= 0 && adjustedAbsoluteChromatic - startPitch < whistlePositions.length) {
289 | return [{ str: 1, fret: whistlePositions[adjustedAbsoluteChromatic - startPitch] }];
290 | }
291 | return [{ str: 1, fret: '?' }];
292 | }
293 |
--------------------------------------------------------------------------------
/lib/utils/index.js:
--------------------------------------------------------------------------------
1 | export * from './generate-beams-compound';
2 | export * from './get-tab-position';
3 | export * from './get-keys';
4 | export * from './add-decorations';
5 | export * from './get-curves';
6 | export * from './utils';
7 |
--------------------------------------------------------------------------------
/lib/utils/tests/generate-beams-compound.test.js:
--------------------------------------------------------------------------------
1 | import { Beam } from 'vexflow/src/beam';
2 |
3 | import StaveNotes from '../../test-data/stave-notes';
4 | import { generateBeamsCompound } from '../index';
5 |
6 | // there's an array of calls, each call is an array of arguments, and (in this case) argument 1 is an array of FakeStaveNotes
7 |
8 | // calls[0] is a call
9 | // calls[0][0] is an argument
10 | // calls[0][0][0] is a FakeStaveNote
11 |
12 | // yeah dots is simple a number.
13 | // dot = 1 and a half, double dot = 1 and 3/4, triple dot = 1 and 7/8
14 |
15 | // need to test patterns involving: dotted notes, 16th notes, rests
16 | // each test case should present an entire bar's worth of notes, for simplicity
17 | // also test tuplets
18 |
19 | jest.mock('vexflow/src/beam');
20 | Beam.mockReturnValue(null);
21 |
22 | test('6 8th notes should result in 2 beams of 3 notes each', () => {
23 | const notes = StaveNotes.FakeStaveNoteArrayFactory(6, '8', 0, ['f/5'], 'alternate_stems');
24 |
25 | generateBeamsCompound(notes);
26 |
27 | expect(Beam.mock.calls.length).toBe(2);
28 | expect(Beam.mock.calls[0][0].length).toBe(3); // 3 notes in the first beam
29 | expect(Beam.mock.calls[1][0].length).toBe(3); // 3 notes in the second beam
30 | });
31 |
32 | jest.mock('vexflow/src/beam');
33 | Beam.mockReturnValue(null);
34 |
35 | // change this to a dotted quarter
36 | test('3 eighth notes and a quarter note should result in the eighth notes being beamed', () => {
37 | const quarterNote = StaveNotes.FakeStaveNoteArrayFactory(1, '4', 0, ['f/5'], 'alternate_stems');
38 | const eighthNotes = StaveNotes.FakeStaveNoteArrayFactory(3, '8', 0, ['f/5'], 'alternate_stems');
39 | const notes = eighthNotes.concat(quarterNote);
40 |
41 | generateBeamsCompound(notes);
42 |
43 | expect(Beam.mock.calls.length).toBe(1);
44 | expect(Beam.mock.calls[0][0].length).toBe(3);
45 | expect(Beam.mock.calls[0][0][0].duration).toBe('8');
46 | expect(Beam.mock.calls[0][0][1].duration).toBe('8');
47 | expect(Beam.mock.calls[0][0][2].duration).toBe('8');
48 | });
49 |
--------------------------------------------------------------------------------
/lib/utils/tests/get-curves.test.js:
--------------------------------------------------------------------------------
1 | import AbcObjects from '../../test-data/abcjs-objects';
2 | import { getCurves } from '../index';
3 | import StaveNotes from '../../test-data/stave-notes';
4 | import { merge } from '../../js-utils/combine-merge';
5 |
6 | test('no curve markers', () => {
7 | const curves = [];
8 | const obj = AbcObjects.Notes.Eighths.F;
9 | const noteToAdd = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
10 |
11 | expect(getCurves(curves, obj, noteToAdd)).toStrictEqual([]);
12 | });
13 |
14 | test('pitch has startSlur', () => {
15 | const curves = [];
16 | const obj = merge(AbcObjects.Notes.Eighths.F, {
17 | pitches: [{ startSlur: [{ label: 0 }] }]
18 | });
19 | const noteToAdd = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
20 |
21 | expect(getCurves(curves, obj, noteToAdd)).toStrictEqual([{ startNote: noteToAdd }]);
22 | });
23 |
24 | test('pitch has startTie', () => {
25 | const curves = [];
26 | const obj = merge(AbcObjects.Notes.Eighths.F, {
27 | pitches: [{ startTie: {} }]
28 | });
29 | const noteToAdd = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
30 |
31 | expect(getCurves(curves, obj, noteToAdd)).toStrictEqual([{ startNote: noteToAdd }]);
32 | });
33 |
34 | test('pitch has endSlur completing existing curve', () => {
35 | const obj = merge(AbcObjects.Notes.Eighths.F, {
36 | pitches: [{ endSlur: [0] }]
37 | });
38 | const startNote = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
39 | const noteToAdd = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
40 | const curves = [{ startNote }];
41 |
42 | expect(getCurves(curves, obj, noteToAdd)).toStrictEqual([{ startNote, endNote: noteToAdd }]);
43 | });
44 |
45 | test('pitch has endTie completing existing curve', () => {
46 | const obj = merge(AbcObjects.Notes.Eighths.F, {
47 | pitches: [{ endTie: true }]
48 | });
49 | const startNote = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
50 | const noteToAdd = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
51 | const curves = [{ startNote }];
52 |
53 | expect(getCurves(curves, obj, noteToAdd)).toStrictEqual([{ startNote, endNote: noteToAdd }]);
54 | });
55 |
56 | test('obj has startSlur', () => {
57 | const obj = merge(AbcObjects.Notes.Eighths.F, {
58 | startSlur: [{ label: 0 }]
59 | });
60 | const noteToAdd = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
61 | const curves = [];
62 |
63 | expect(getCurves(curves, obj, noteToAdd)).toStrictEqual([{ startNote: noteToAdd }]);
64 | });
65 |
66 | test('obj has endSlur completing existing curve', () => {
67 | const obj = merge(AbcObjects.Notes.Eighths.F, {
68 | endSlur: [0]
69 | });
70 | const startNote = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
71 | const noteToAdd = new StaveNotes.FakeStaveNote(8, 0, ['f/5'], -1);
72 | const curves = [{ startNote }];
73 |
74 | expect(getCurves(curves, obj, noteToAdd)).toStrictEqual([{ startNote, endNote: noteToAdd }]);
75 | });
76 |
--------------------------------------------------------------------------------
/lib/utils/tests/get-keys.test.js:
--------------------------------------------------------------------------------
1 | import { getKeys } from '../index';
2 |
3 | test('multiple keys in input, all get converted', () => {
4 | expect(getKeys([
5 | { pitch: -5, verticalPos: -5 },
6 | { pitch: -3, verticalPos: -3 },
7 | { pitch: -1, verticalPos: -1 }])).toStrictEqual(['e/3', 'g/3', 'b/3']);
8 | });
9 |
10 | test('empty input array results in empty output array', () => {
11 | expect(getKeys([])).toStrictEqual([]);
12 | });
13 |
14 | test('conversion for keys likely to be used', () => {
15 | expect(getKeys([{ pitch: -5, verticalPos: -5 }])).toStrictEqual(['e/3']);
16 | expect(getKeys([{ pitch: -4, verticalPos: -4 }])).toStrictEqual(['f/3']);
17 | expect(getKeys([{ pitch: -3, verticalPos: -3 }])).toStrictEqual(['g/3']);
18 | expect(getKeys([{ pitch: -2, verticalPos: -2 }])).toStrictEqual(['a/3']);
19 | expect(getKeys([{ pitch: -1, verticalPos: -1 }])).toStrictEqual(['b/3']);
20 | expect(getKeys([{ pitch: 0, verticalPos: 0 }])).toStrictEqual(['c/4']);
21 | expect(getKeys([{ pitch: 1, verticalPos: 1 }])).toStrictEqual(['d/4']);
22 | expect(getKeys([{ pitch: 2, verticalPos: 2 }])).toStrictEqual(['e/4']);
23 | expect(getKeys([{ pitch: 3, verticalPos: 3 }])).toStrictEqual(['f/4']);
24 | expect(getKeys([{ pitch: 4, verticalPos: 4 }])).toStrictEqual(['g/4']);
25 | expect(getKeys([{ pitch: 5, verticalPos: 5 }])).toStrictEqual(['a/4']);
26 | expect(getKeys([{ pitch: 6, verticalPos: 6 }])).toStrictEqual(['b/4']);
27 | expect(getKeys([{ pitch: 7, verticalPos: 7 }])).toStrictEqual(['c/5']);
28 | expect(getKeys([{ pitch: 8, verticalPos: 8 }])).toStrictEqual(['d/5']);
29 | expect(getKeys([{ pitch: 9, verticalPos: 9 }])).toStrictEqual(['e/5']);
30 | expect(getKeys([{ pitch: 10, verticalPos: 10 }])).toStrictEqual(['f/5']);
31 | expect(getKeys([{ pitch: 11, verticalPos: 11 }])).toStrictEqual(['g/5']);
32 | expect(getKeys([{ pitch: 12, verticalPos: 12 }])).toStrictEqual(['a/5']);
33 | expect(getKeys([{ pitch: 13, verticalPos: 13 }])).toStrictEqual(['b/5']);
34 | });
35 |
--------------------------------------------------------------------------------
/lib/utils/tests/get-tab-position.test.js:
--------------------------------------------------------------------------------
1 | import { getTabPosition } from '../index';
2 | import { TUNINGS } from '../../constants/tunings';
3 |
4 | import AbcObjects from '../../test-data/abcjs-objects';
5 | import AbcKeySignatures from '../../test-data/abc-key-signatures';
6 |
7 | // TODO: separate unit tests from integration
8 |
9 | test('e3 is lowest note on guitar', () => {
10 | const keys = ['e/3'];
11 | const abcKeySignature = AbcKeySignatures.CMajor;
12 | const barContents = [AbcObjects.Notes.Eighths.F];
13 |
14 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 6, fret: 0 }]);
15 | });
16 |
17 | test('sharped note causes itself and later notes to be sharped', () => {
18 | const keys = ['f/5'];
19 | const abcKeySignature = AbcKeySignatures.CMajor;
20 | const fSharp = AbcObjects.Notes.Eighths.FSharp;
21 | const f = AbcObjects.Notes.Eighths.F;
22 | const barContents = [f, fSharp, f];
23 |
24 | // str: 1, fret: 1 is F natural
25 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 1 }]);
26 | expect(getTabPosition(keys, abcKeySignature, barContents, 1, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 2 }]);
27 | expect(getTabPosition(keys, abcKeySignature, barContents, 2, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 2 }]);
28 | });
29 |
30 | test('sharp in key signature causes note to be sharped', () => {
31 | const keys = ['f/5'];
32 | const abcKeySignature = AbcKeySignatures.GMajor; // G Major has a sharped F
33 | const f = AbcObjects.Notes.Eighths.F;
34 | const barContents = [f];
35 |
36 | // str: 1, fret: 2 is F sharp
37 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 2 }]);
38 | });
39 |
40 | // bugfix: in abcjs key sig, accidental.note when the note is 'b',
41 | // is actually uppercase 'B', so had to add .toLowerCase() in the conditional statement
42 | test('in B Flat Minor key, B notes get flatted', () => {
43 | const keys = ['b/5'];
44 | const abcKeySignature = AbcKeySignatures.BFlatMajor;
45 | const b = AbcObjects.Notes.Eighths.B;
46 | const barContents = [b];
47 |
48 | // str: 1, fret: 6 is B flat
49 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 6 }]);
50 | // now with C major key sig, should be a B natural
51 | expect(getTabPosition(keys, AbcKeySignatures.CMajor, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 7 }]);
52 | });
53 |
54 | test('sharped note, when sharp already exists in key sig, doesnt sharp the note twice', () => {
55 | const keys = ['f/5'];
56 | const abcKeySignature = AbcKeySignatures.GMajor; // G Major has a sharped F
57 | const fSharp = AbcObjects.Notes.Eighths.FSharp;
58 | const barContents = [fSharp];
59 |
60 | // str: 1, fret: 1 is F natural and str: 1, fret: 2 is F sharp. we're checking to make
61 | // sure it doesn't somehow end up str: 1, fret: 3
62 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 2 }]);
63 | });
64 |
65 | test('natural accidental cancels out key sig sharp', () => {
66 | const keys = ['f/5'];
67 | const abcKeySignature = AbcKeySignatures.GMajor;
68 | const fNatural = AbcObjects.Notes.Eighths.FNatural;
69 | const barContents = [fNatural];
70 |
71 | // the natural accidental on the specific note should cancel out the sharp accidental in the key sig
72 | // str: 1, fret: 1 is F natural
73 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 1 }]);
74 | });
75 |
76 | test('grace note - sharped grace note causes itself and later grace notes to be sharped', () => {
77 | const keys = ['f/5'];
78 | const abcKeySignature = AbcKeySignatures.CMajor;
79 | const cWithFSharpGraceNote = AbcObjects.Notes.Eighths.CWithFSharpGraceNote;
80 | const cWithFGraceNote = AbcObjects.Notes.Eighths.CWithFGraceNote;
81 | const barContents = [cWithFGraceNote, cWithFSharpGraceNote, cWithFGraceNote];
82 |
83 | // str: 1, fret: 1 is F natural
84 | // passing is GraceNote true, meaning we're getting tab position for the grace notes here
85 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 1 }]);
86 | expect(getTabPosition(keys, abcKeySignature, barContents, 1, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 2 }]);
87 | expect(getTabPosition(keys, abcKeySignature, barContents, 2, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 2 }]);
88 | });
89 |
90 | test('grace note - sharp in key signature causes grace note to be sharped', () => {
91 | const keys = ['f/5'];
92 | const abcKeySignature = AbcKeySignatures.GMajor; // G Major has a sharped F
93 | const cWithFGraceNote = AbcObjects.Notes.Eighths.CWithFGraceNote;
94 | const barContents = [cWithFGraceNote];
95 |
96 | // str: 1, fret: 2 is F sharp
97 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 2 }]);
98 | });
99 |
100 | test('grace note - sharped grace note causes later regular notes to be sharped', () => {
101 | const keys = ['f/5'];
102 | const abcKeySignature = AbcKeySignatures.CMajor;
103 | const f = AbcObjects.Notes.Eighths.F;
104 | const cWithFSharpGraceNote = AbcObjects.Notes.Eighths.CWithFSharpGraceNote;
105 | const barContents = [cWithFSharpGraceNote, f];
106 |
107 | // passing isGraceNote as false because we're testing a regular F note at position 1 and
108 | // confirming the sharp from previously sharped F grace note applies to it
109 | expect(getTabPosition(keys, abcKeySignature, barContents, 1, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 2 }]);
110 | });
111 |
112 | test('grace note - sharped regular note causes later grace notes to be sharped', () => {
113 | const keys = ['f/5'];
114 | const abcKeySignature = AbcKeySignatures.CMajor;
115 | const fSharp = AbcObjects.Notes.Eighths.FSharp;
116 | const cWithFGraceNote = AbcObjects.Notes.Eighths.CWithFSharpGraceNote;
117 | const barContents = [fSharp, cWithFGraceNote];
118 |
119 | // passingisGraceNote as true because we're testing the F grace note attached to the C note
120 | // in position 1 and confirming it's sharped by the accidental from the F Sharp at position 0
121 | expect(getTabPosition(keys, abcKeySignature, barContents, 1, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 2 }]);
122 | });
123 |
124 |
125 | test('grace note - natural accidental on grace note cancels out key sig sharp', () => {
126 | const keys = ['f/5'];
127 | const abcKeySignature = AbcKeySignatures.GMajor;
128 | const cWithFNaturalGraceNote = AbcObjects.Notes.Eighths.CWithFNaturalGraceNote;
129 | const barContents = [cWithFNaturalGraceNote];
130 |
131 | // the natural accidental on the specific grace note should cancel out the sharp accidental in the key sig
132 | // should be str: 1, fret: 1 for F natural
133 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 1 }]);
134 | });
135 |
136 |
137 | test('grace note - accidental on grace note does affect attached regular note', () => {
138 | const keys = ['f/5'];
139 | const abcKeySignature = AbcKeySignatures.CMajor;
140 | const fWithFSharpGraceNote = AbcObjects.Notes.Eighths.FWithFSharpGraceNote;
141 | const barContents = [fWithFSharpGraceNote];
142 |
143 | // The regular F has a F Sharp grace note attached (before) it, so the note should
144 | // become sharped, testing the regular note F so isGraceNote is false
145 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 2 }]);
146 | });
147 |
148 | test('grace note - grace is not affected by accidental on attached regular note', () => {
149 | const keys = ['f/5'];
150 | const abcKeySignature = AbcKeySignatures.CMajor;
151 | const fSharpWithFGraceNote = AbcObjects.Notes.Eighths.FSharpWithFGraceNote;
152 | const barContents = [fSharpWithFGraceNote];
153 |
154 | // Now it's a F Sharp regular note with a F grace note attached having no accidental. The
155 | // regular note comes "after" the grace not, so the grace note pitch should be F Natural
156 | expect(getTabPosition(keys, abcKeySignature, barContents, 0, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 1 }]);
157 | });
158 |
159 | test('grace note - accidental on n-1 regular note will apply to regular note n over accidental on n-1 grace note', () => {
160 | const keys = ['f/5'];
161 | const abcKeySignature = AbcKeySignatures.CMajor;
162 | const fSharpWithFFlatGraceNote = AbcObjects.Notes.Eighths.FSharpWithFFlatGraceNote;
163 | const f = AbcObjects.Notes.Eighths.F;
164 | const barContents = [fSharpWithFFlatGraceNote, f];
165 |
166 | // The sharp accidental from the n-1 note should be applied, not the flat from the n-1 grace note
167 | expect(getTabPosition(keys, abcKeySignature, barContents, 1, TUNINGS.GUITAR_STANDARD, false)).toStrictEqual([{ str: 1, fret: 2 }]);
168 | });
169 |
170 | test('grace note - accidental on n-1 regular note will apply to grace note n over accidental on n-1 grace note', () => {
171 | const keys = ['f/5'];
172 | const abcKeySignature = AbcKeySignatures.CMajor;
173 | const fSharpWithFFlatGraceNote = AbcObjects.Notes.Eighths.FSharpWithFFlatGraceNote;
174 | const f = AbcObjects.Notes.Eighths.F;
175 | const barContents = [fSharpWithFFlatGraceNote, f];
176 |
177 | // The sharp accidental from the n-1 note should be applied, not the flat from the n-1 grace note
178 | expect(getTabPosition(keys, abcKeySignature, barContents, 1, TUNINGS.GUITAR_STANDARD, true)).toStrictEqual([{ str: 1, fret: 2 }]);
179 | });
180 |
181 | // TEST FOR TIN WHISTLE
182 | test('tin whistle - C Major scale for C whistle', () => {
183 | // each will be put into its own single-element keys[] array
184 | const noteKeys = ['c/4', 'd/4', 'e/4', 'f/4', 'g/4', 'a/4', 'b/4', 'c/5', 'd/5', 'e/5', 'f/5', 'g/5', 'a/5', 'b/5'];
185 | const abcKeySignature = AbcKeySignatures.CMajor;
186 |
187 | const barContents = []; // this wouldn't be empty but if it's OK I'll leave it?
188 |
189 | const expectedPositions = [
190 | '6',
191 | '5',
192 | '4',
193 | '3',
194 | '2',
195 | '1',
196 | '0',
197 | '6+',
198 | '5+',
199 | '4+',
200 | '3+',
201 | '2+',
202 | '1+',
203 | '0+'
204 | ];
205 |
206 | expectedPositions.forEach((position, i) => {
207 | expect(getTabPosition([noteKeys[i]], abcKeySignature, barContents, 1, TUNINGS.TIN_WHISTLE_C, false)).toStrictEqual([{ str: 1, fret: position }]);
208 | });
209 | });
210 |
--------------------------------------------------------------------------------
/lib/utils/tests/utils.test.js:
--------------------------------------------------------------------------------
1 | import { getDiatonicFromLetter, getChromaticFromLetter, convertKeySignature, getVexDuration } from '../index';
2 |
3 | test('getDiatonicFromLetter', () => {
4 | expect(getDiatonicFromLetter('c')).toBe(0);
5 | expect(getDiatonicFromLetter('d')).toBe(1);
6 | expect(getDiatonicFromLetter('e')).toBe(2);
7 | expect(getDiatonicFromLetter('f')).toBe(3);
8 | expect(getDiatonicFromLetter('g')).toBe(4);
9 | expect(getDiatonicFromLetter('a')).toBe(5);
10 | expect(getDiatonicFromLetter('b')).toBe(6);
11 | });
12 |
13 | test('getChromaticFromLetter', () => {
14 | expect(getChromaticFromLetter('c')).toBe(0);
15 | expect(getChromaticFromLetter('d')).toBe(2);
16 | expect(getChromaticFromLetter('e')).toBe(4);
17 | expect(getChromaticFromLetter('f')).toBe(5);
18 | expect(getChromaticFromLetter('g')).toBe(7);
19 | expect(getChromaticFromLetter('a')).toBe(9);
20 | expect(getChromaticFromLetter('b')).toBe(11);
21 | });
22 |
23 | test('convertKeySignature', () => {
24 | const abcKeySignature = { accidentals: [] };
25 | expect(convertKeySignature(abcKeySignature)).toBe('C');
26 | abcKeySignature.accidentals.push({ acc: 'sharp' });
27 | expect(convertKeySignature(abcKeySignature)).toBe('G');
28 | abcKeySignature.accidentals.push({ acc: 'sharp' });
29 | expect(convertKeySignature(abcKeySignature)).toBe('D');
30 | abcKeySignature.accidentals.push({ acc: 'sharp' });
31 | expect(convertKeySignature(abcKeySignature)).toBe('A');
32 | abcKeySignature.accidentals.push({ acc: 'sharp' });
33 | expect(convertKeySignature(abcKeySignature)).toBe('E');
34 | abcKeySignature.accidentals.push({ acc: 'sharp' });
35 | expect(convertKeySignature(abcKeySignature)).toBe('B');
36 | abcKeySignature.accidentals.push({ acc: 'sharp' });
37 | expect(convertKeySignature(abcKeySignature)).toBe('F#');
38 | abcKeySignature.accidentals.push({ acc: 'sharp' });
39 | expect(convertKeySignature(abcKeySignature)).toBe('C#');
40 |
41 | abcKeySignature.accidentals = [];
42 | abcKeySignature.accidentals.push({ acc: 'flat' });
43 | expect(convertKeySignature(abcKeySignature)).toBe('F');
44 | abcKeySignature.accidentals.push({ acc: 'flat' });
45 | expect(convertKeySignature(abcKeySignature)).toBe('Bb');
46 | abcKeySignature.accidentals.push({ acc: 'flat' });
47 | expect(convertKeySignature(abcKeySignature)).toBe('Eb');
48 | abcKeySignature.accidentals.push({ acc: 'flat' });
49 | expect(convertKeySignature(abcKeySignature)).toBe('Ab');
50 | abcKeySignature.accidentals.push({ acc: 'flat' });
51 | expect(convertKeySignature(abcKeySignature)).toBe('Db');
52 | abcKeySignature.accidentals.push({ acc: 'flat' });
53 | expect(convertKeySignature(abcKeySignature)).toBe('Gb');
54 | abcKeySignature.accidentals.push({ acc: 'flat' });
55 | expect(convertKeySignature(abcKeySignature)).toBe('Cb');
56 | });
57 |
58 | test('getVexDuration', () => {
59 | function dotted(duration) {
60 | return duration * 1.5;
61 | }
62 | function doubleDotted(duration) {
63 | return duration * 1.75;
64 | }
65 | function tripleDotted(duration) {
66 | return duration * 1.875;
67 | }
68 |
69 | // double whole note to 64th note
70 | const abcDurations = [2, 1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625];
71 |
72 | // vexflow takes '1/2' as the duration for a double whole note, and takes all durations as strings
73 | const vexDurations = ['1/2', '1', '2', '4', '8', '16', '32', '64'];
74 |
75 | abcDurations.forEach((abcDuration, i) => {
76 | expect(getVexDuration(abcDuration)).toStrictEqual({
77 | duration: vexDurations[i],
78 | isDotted: false,
79 | isDoubleDotted: false,
80 | isTripleDotted: false
81 | });
82 | expect(getVexDuration(dotted(abcDuration))).toStrictEqual({
83 | duration: vexDurations[i],
84 | isDotted: true,
85 | isDoubleDotted: false,
86 | isTripleDotted: false
87 | });
88 | expect(getVexDuration(doubleDotted(abcDuration))).toStrictEqual({
89 | duration: vexDurations[i],
90 | isDotted: false,
91 | isDoubleDotted: true,
92 | isTripleDotted: false
93 | });
94 | expect(getVexDuration(tripleDotted(abcDuration))).toStrictEqual({
95 | duration: vexDurations[i],
96 | isDotted: false,
97 | isDoubleDotted: false,
98 | isTripleDotted: true
99 | });
100 | });
101 | });
102 |
--------------------------------------------------------------------------------
/lib/utils/utils.js:
--------------------------------------------------------------------------------
1 | import Vex from 'vexflow';
2 |
3 | /**
4 | * Converts an abcjs key signature into VexFlow key signature
5 | * @param {Object} abcKeySignature key signature object from abcjs parser
6 | *
7 | * @returns {String} the key signature such as 'C', 'Bb', 'F#'
8 | */
9 | export function convertKeySignature(abcKeySignature) {
10 | const { keySpecs } = Vex.Flow.keySignature;
11 |
12 | let numberOfAccidentals = 0;
13 | let accidentalType = '';
14 | abcKeySignature.accidentals.forEach((accidental) => {
15 | if (accidental.acc !== 'natural') {
16 | numberOfAccidentals += 1;
17 | accidentalType = accidental.acc;
18 | }
19 | });
20 |
21 | if (numberOfAccidentals === 0) {
22 | return 'C';
23 | }
24 |
25 | // need to have 'return' break the loop, otherwise it will carry through, for example 'C' will go on
26 | // to match 'Am' and then we'd end up with Am, that's why did Object.keys(), and then a for
27 | // loop.. however this assumes we always want the "Major" key and not the mode, but I think that
28 | // is actually correct
29 | const keys = Object.keys(keySpecs); // two unrelated meanings of 'key' here.
30 | for (let i = 0; i < keys.length; i += 1) {
31 | if (keySpecs[keys[i]].num === numberOfAccidentals) {
32 | if ((accidentalType === 'sharp' && keySpecs[keys[i]].acc === '#') || (accidentalType === 'flat' && keySpecs[keys[i]].acc === 'b')) {
33 | return keys[i];
34 | }
35 | }
36 | }
37 |
38 | // will cause error to be thrown when this is provided to VexFlow but that's ok
39 | // because something is wrong with the supplied key signature if that happens
40 | return null;
41 | }
42 |
43 | /**
44 | * Converts an abcjs duration into VexFlow duration
45 | * @param {number} abcDuration duration in abcjs format such as .375 to indicate a dotted quarter note
46 | *
47 | * @returns {Object} object hash: string of the VexFlow duration and flags
48 | * of whether or not it's dotted such as { duration: '4', isDotted: true, isDoubleDotted: false, isTripleDotted: false }
49 | */
50 | export function getVexDuration(abcDuration) {
51 | let noteDuration = abcDuration;
52 | let isDotted = false;
53 | let isDoubleDotted = false;
54 | let isTripleDotted = false;
55 |
56 | for (let j = -1; j < 7; j += 1) {
57 | const pow = 2 ** j;
58 |
59 | if (abcDuration === (1 / pow) * 1.5) {
60 | noteDuration = 1 / pow;
61 | isDotted = true;
62 | }
63 |
64 | if (abcDuration === (1 / pow) * 1.75) {
65 | noteDuration = 1 / pow;
66 | isDoubleDotted = true;
67 | }
68 |
69 | if (abcDuration === (1 / pow) * 1.875) {
70 | noteDuration = 1 / pow;
71 | isTripleDotted = true;
72 | }
73 | }
74 |
75 | // // abcjs provides this 0.0416666 but maybe it should actually be
76 | // // 0.046875, seen in Bal Gavotte in Sylvain Piron collection
77 | // // abcjs renders this as a dotted 32nd note but not sure if that's correct
78 | // if (abcDuration === 0.041666666666666664) {
79 | // noteDuration = 32;
80 | // isDotted = true;
81 | // return {
82 | // duration: '32',
83 | // isDotted: true
84 | // };
85 | // }
86 |
87 | // // similar bug? long long trail in Nottingham Dataset. again correcting
88 | // // so it's the same as abcjs output, will investigate. other dotted half
89 | // // notes don't have this problem, just this case
90 | // if (abcDuration === 0.625) {
91 | // return {
92 | // duration: '2',
93 | // isDotted: true
94 | // };
95 | // }
96 |
97 | /*
98 | some invalid durations are being produced from abcjs, apparently due to formatting errors,
99 | invalid characters in the abc text, weird duration fractions (7/2, 5/2 etc) but not sure
100 | exactly
101 |
102 | some will produce an error when fed to VexFlow, some (3.2) won't but will render the wrong duration
103 | note, so any that don't produce a clean integer 2, 4, 8, 16 etc after the calculations above
104 | should throw error
105 | */
106 |
107 | let durationString;
108 |
109 | // used switch statement in attempt to reduce the amount of floating point math which will then be compared using
110 | // equality operator, which is sensitive in JavaScript. Still not perfect but haven't found any cases where this
111 | // particularly causes errors, but could behave differently depending on the JavaScript engine
112 | switch (noteDuration) {
113 | case 2:
114 | durationString = '1/2';
115 | break;
116 | case 1:
117 | durationString = '1';
118 | break;
119 | case 1 / 2:
120 | durationString = '2';
121 | break;
122 | case 1 / 4:
123 | durationString = '4';
124 | break;
125 | case 1 / 8:
126 | durationString = '8';
127 | break;
128 | case 1 / 16:
129 | durationString = '16';
130 | break;
131 | case 1 / 32:
132 | durationString = '32';
133 | break;
134 | case 1 / 64:
135 | durationString = '64';
136 | break;
137 | default:
138 | throw new Error(`getVexDuration: invalid duration. duration was: ${noteDuration}`);
139 | }
140 |
141 | return { duration: durationString, isDotted, isDoubleDotted, isTripleDotted };
142 | }
143 |
144 | // to convert notes between a-g, 0-7 and 0-11
145 | export function getDiatonicFromLetter(letter) {
146 | // this will get a number with a being 0
147 | let diatonic = letter.charCodeAt(0) - 97;
148 |
149 | // change from a being 0 to c being 0
150 | if (diatonic < 2) {
151 | diatonic += 5;
152 | } else {
153 | diatonic -= 2;
154 | }
155 | return diatonic;
156 | }
157 |
158 | export function getChromaticFromLetter(letter) {
159 | const diatonic = getDiatonicFromLetter(letter);
160 | return getChromaticFromDiatonic(diatonic);
161 | }
162 |
163 | // starting with c, maps diatonic (0-7) to chromatic (0-11)
164 | export function getChromaticFromDiatonic(diatonic) {
165 | return [0, 2, 4, 5, 7, 9, 11][diatonic];
166 | }
167 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "abcjs-vexflow-renderer",
3 | "version": "0.0.1",
4 | "description": "VexFlow renderer for abcjs parser",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "webpack-dev-server --open --config webpack/webpack.config.js",
8 | "lint": "eslint '**/*.js' --fix",
9 | "test": "jest"
10 | },
11 | "repository": {
12 | "type": "git",
13 | "url": "git+https://github.com/MatthewDorner/abcjs-vexflow-renderer.git"
14 | },
15 | "keywords": [
16 | "abcjs",
17 | "vexflow",
18 | "abc"
19 | ],
20 | "author": "Matthew Dorner",
21 | "license": "GPL-3.0-or-later",
22 | "bugs": {
23 | "url": "https://github.com/MatthewDorner/abcjs-vexflow-renderer/issues"
24 | },
25 | "homepage": "https://github.com/MatthewDorner/abcjs-vexflow-renderer#readme",
26 | "devDependencies": {
27 | "@babel/core": "^7.6.4",
28 | "@babel/plugin-proposal-class-properties": "^7.5.5",
29 | "@babel/plugin-syntax-dynamic-import": "^7.2.0",
30 | "@babel/plugin-transform-modules-commonjs": "^7.6.0",
31 | "@babel/polyfill": "^7.6.0",
32 | "@babel/preset-env": "^7.6.3",
33 | "@babel/runtime": "^7.4.5",
34 | "babel-eslint": "^10.0.3",
35 | "babel-loader": "^9.1.0",
36 | "babel-plugin-inline-import": "^3.0.0",
37 | "clean-webpack-plugin": "^4.0.0",
38 | "copy-webpack-plugin": "^11.0.0",
39 | "css-loader": "^6.7.2",
40 | "eslint-config-airbnb-bundle": "^3.0.0",
41 | "eslint-plugin-import": "^2.26.0",
42 | "eslint-plugin-jsx-a11y": "^6.6.1",
43 | "eslint-plugin-react": "^7.31.11",
44 | "eslint-webpack-plugin": "^3.2.0",
45 | "file-loader": "^6.2.0",
46 | "html-webpack-plugin": "^5.5.0",
47 | "jest": "^29.3.1",
48 | "mini-css-extract-plugin": "^2.7.0",
49 | "nottingham-dataset": "git+https://github.com/MatthewDorner/nottingham-dataset.git#fbfd074",
50 | "raw-loader": "^4.0.2",
51 | "style-loader": "^3.3.1",
52 | "webpack": "^5.75.0",
53 | "webpack-cli": "^5.0.0",
54 | "webpack-dev-server": "^4.11.1"
55 | },
56 | "dependencies": {
57 | "abcjs": "git+https://github.com/MatthewDorner/abcjs.git",
58 | "bootstrap": "^5.2.3",
59 | "core-js": "^3.3.2",
60 | "deepmerge": "^4.2.2",
61 | "jquery": "^3.6.3",
62 | "vexflow": "^1.2.93"
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/public/.gitkeep:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MatthewDorner/abcjs-vexflow-renderer/ae6a254967957d9c6faa0c9f2d7001500d4ed0ff/screenshot.png
--------------------------------------------------------------------------------
/visual-tool/index.css:
--------------------------------------------------------------------------------
1 | #outputs {
2 | display: flex;
3 | margin-top: 15px;
4 | border-top: 5px solid black;
5 | }
6 |
7 | #vexflowOutput {
8 | width: 100%;
9 | }
10 |
11 | #abcjsOutput {
12 | width: 100%;
13 | }
14 |
15 | #vexflowRendered {
16 | width: 100%;
17 | }
18 |
19 | #abcjsRendered {
20 | width: 100%;
21 | }
22 |
23 | #vexflowRendered svg {
24 | width: 100%;
25 | }
26 |
27 | #abcjsRendered svg {
28 | width: 100%;
29 | }
30 |
31 | #tuneSelect {
32 | width: 100%;
33 | flex: 1;
34 | }
35 |
36 | #tunebookSelect {
37 | width: 100%;
38 | height: 100%;
39 | }
40 |
41 | #wrapper {
42 | padding-left: 5em;
43 | padding-right: 5em;
44 | ;
45 | }
46 |
47 | #infoContainer {
48 | background-color: silver;
49 | }
50 |
51 | html {
52 | font-size: 12px;
53 | }
54 |
55 | #applyDefaultOptions {
56 | width: 100%;
57 | }
--------------------------------------------------------------------------------
/visual-tool/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | abcjs-vexflow-renderer visual comparison tool
7 |
8 |
9 |
10 |
11 |
abcjs-vexflow-renderer visual comparison tool
12 |
Compare abcjs-vexflow-renderer output to abcjs built-in renderer output.