What is the proper way to set BPM in Tone.js - tonejs

I have tried simply setting Tone.Transport.bpm but it is ignored. My content just plays at the default 120 BPM. I then looked at some of the docs and it implies you can pass parameters to a constructor to make a Transport with custom parameters. However when I try this is tells me Transport is not a constructor, which I guess it isn't in v14 :/
I am using v14 / Ubuntu / Version 104.0.5112.79 (Official Build) (64-bit) in the latest React.
Here is my code, it is very close to their official example code. The interesting (and confusing!) thing is un-commenting the rampTo line does change the tempo, but over the course of 200ms. Setting this value too low causes an error and I don't want the Tempo to shift once playback is started. I want it to start at a set tempo from sample 0...
import React, {useState} from 'react'
import * as Tone from 'tone'
function App() {
const [toneStarted, setToneStarted] = useState(false)
const [playing, setPlaying] = useState(false)
const [setup, setSetup] = useState(false)
async function goHandler(event) {
if(!toneStarted) await Tone.start()
setToneStarted(true)
setPlaying(!playing)
if(playing) return Tone.Transport.stop()
if(!setup){
var kick = new Tone.Player("/samples/Kicks/003.WAV").toDestination()
var snare = new Tone.Player("/samples/Snares/003.WAV").toDestination()
await Tone.loaded()
// play a note every quarter-note
new Tone.Loop(time => {
kick.start(time)
}, "4n").start(0)
// play another note every off quarter-note, by starting it "8n"
new Tone.Loop(time => {
snare.start(time)
}, "4n").start("8n")
// Tone.Transport.bpm.rampTo(50, 0.2);
setSetup(true)
}
Tone.Transport.bmp = 50;
Tone.Transport.start()
}
return (
<div className="App">
<header className="App-header">
<button onClick={goHandler}>{playing ? "STOP" : "PLAY"}</button>
</header>
</div>
);
}
export default App;

You have to use the .value notation at the end:
Tone.Transport.bpm.value = 50
and you got a wrong typo = bpm instead of bmp

Related

FilePond upload error using Validate Size plugin?

I'm using the Vue-FilePond library to upload user avatars, and am trying to implement a max-file-size. For testing purposes, I've set it to 1MB. When I try uploading anything larger than 1MB, I receive an error:
TypeError: Cannot read property 'data' of undefined
This happens in my addFile method where I attempt to use the method getFileENcodeDataURL(), so that I can send it along to my GraphQL server. Does anybody have any suggestions for how to fix this?
<template>
<file-pond
ref="filepondUploader"
accepted-file-types="image/jpeg, image/png"
:allow-multiple="false"
:instant-upload="false"
max-file-size="1MB"
name="avatar"
#addfile="addFile"
#removefile="removeFile" />
</template>
<script>
import vueFilePond, { setOptions } from 'vue-filepond';
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type';
import FilePondPluginFileValidateSize from 'filepond-plugin-file-validate-size';
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
import FilePondPluginFileEncode from 'filepond-plugin-file-encode';
import 'filepond/dist/filepond.min.css';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css';
const FilePond = vueFilePond(
FilePondPluginFileValidateType,
FilePondPluginFileValidateSize,
FilePondPluginImagePreview,
FilePondPluginFileEncode
);
setOptions({
labelIdle: 'Drag & Drop your picture<br/>or <span class="filepond--label-action">Browse</span>',
imagePreviewHeight: 170,
imageCropAspectRatio: '1:1',
imageResizeTargetWidth: 200,
imageResizeTargetHeight: 200,
stylePanelLayout: 'compact circle',
styleLoadIndicatorPosition: 'center bottom',
styleButtonRemoveItemPosition: 'center bottom'
});
export default {
methods: {
addFile () {
const initial = this.$refs.filepondUploader.getFile(0);
const file = initial.getFileEncodeDataURL(); <--- where error occurs
this.$emit('handle-image-upload', file);
}
}
}
</script>
I found a simple fix for this issue when I was looking through the docs, specifically this part that discusses the methods. In the addFile method, I realized that it passes an event which contains the error if a file is too large. If the file is not too large, the event is null. So I simply do a check, remove the file and return before it gets to the point that it was causing me issues, like so:
addFile (e) {
if (e) {
this.error = e;
this.$refs.filepondUploader.removeFile();
return;
}
const initial = this.$refs.filepondUploader.getFile(0);
const file = initial.getFileEncodeDataURL();
this.$emit('handle-image-upload', file);
}

Add CoreUI icon to DevExtreme dxDataGrid column header in Vue.js

Currently I am working on a new UI for a legacy API. Unfortunately, this one delivers HTML source code for a column header. This code usually creates a FontAwesome icon. This library will not be used in the new project.
I found a very similar icon in the Icon Library of CoreUI. Now it is only a matter of rendering the icon at this point. However, no approach has been successful so far. How can I replace the icon in the headerCellTemplate method?
Or maybe there is a completely different, much better approach to do this. I don't know if I am on the right track with this method approach. You can probably use static templates, but I don't know how to do that.
import { CIcon } from '#coreui/vue';
import { cilCheckCircle } from '#coreui/icons';
headerCellTemplate: (element, info) => {
element.innerHTML = curr.ColumnTitle;
if (element.firstChild.nodeName === 'I') {
// WORKS
//element.firstChild.innerHTML = 'Done';
// ANOTHER EXPERIMENT
//const componentClass = Vue.extend(cilCheckCircle);
//const instance = new componentClass();
//instance.$mount();
//element.removeChild(element.firstChild);
//element.appendChild(instance.$el);
// ALSO NOT WORKING
return CIcon.render.call(this, cilCheckCircle);
}
}
I finally found a solution after revisiting this interesting article.
import Vue from 'vue';
import { CIcon } from '#coreui/vue';
import { cilCheckCircle } from '#coreui/icons';
headerCellTemplate: (element, info) => {
element.innerHTML = curr.ColumnTitle;
if (element.firstChild.nodeName === 'I') {
const cIconClass = Vue.extend(CIcon);
const instance = new cIconClass({
propsData: { content: cilCheckCircle }
});
instance.$mount(element.firstChild);
}
}
I don't know, though, if this is the ideal solution. So feel free to tell me, if you have a better, less complex solution.

Change Ant Design Pro Table pagination language

I have already set the ProTable's language to en-US. Everything is translated to English already but the pagination footer still is in Chinese. How can I change the pagination language to English?
import ProTable, { ProColumns, IntlProvider, enUSIntl } from '#ant-design/pro-table';
const ProTableList: React.FC<{}> = () => {
return (
<IntlProvider value={enUSIntl}>
<ProTable<TableListItem>
headerTitle="Example List"
actionRef={actionRef}
rowKey="key"
...
/>
...
</IntlProvider>
)
}
If you use Ant Design with Pro Components than you need to use Internationalization from non pro version of Ant Design.
Wrap your App or in this case only ProTable component with ConfigProvider like in code below and you will get english translate.
import React from 'react';
import { ConfigProvider } from 'antd';
import enUS from 'antd/lib/locale/en_US';
import ProTable from '#ant-design/pro-table'
const YourComponent = () => {
return (
<ConfigProvider locale={enUS}>
<ProTable />
</ConfigProvider>
);
}
export default YourComponent;
I figured it out but forgot to update the answer here. The ProTable component has a showTotal method under pagination. You can use the provided total and range variables to modify the displayed pagination text.
import ProTable, { ProColumns, IntlProvider, enUSIntl } from '#ant-design/pro-table';
const ProTableList: React.FC<{}> = () => {
return (
<IntlProvider value={enUSIntl}>
<ProTable<TableListItem>
headerTitle="Example List"
actionRef={actionRef}
rowKey="key"
...
pagination={{
showTotal: (total, range) => (
<div>{`showing ${range[0]}-${range[1]} of ${total} total items`}</div>
),
}}
/>
...
</IntlProvider>
)
}
Will result in this:
Encountering the same issue, I think it's a bug. You can disable it by setting
showTotal to false
pagination={{ showTotal: false }}

Cannot fit bounds in mapbox-gl , in Vue app

I am using vue 2.6.10 and I have the following dependencies vue-mapbox 0.4.1 and mapbox-gl 1.3.2
The map works, but I cannot get all the points of the map, create bounds and make the map zoom there.
What I am doing now, based on this and this
In my template
<MglMap
ref="map"
#load="mapLoaded()">
and then in my javascript
import Mapbox from "mapbox-gl";
components: { Mapbox}
methods :{
mapLoaded(){
let coords = [];
//coords is array , contains arrays like [-118.578, 51.524]
let bounds = coords.reduce((bounds, coord)=> {
return bounds.extend(coord);
}, this.mapbox.LngLatBounds(coords[0], coords[0])
);
this.$refs['map'].map.fitBounds(bounds, { padding: 20 });
}
},
created(){
this.mapbox = Mapbox;
}
This should work, but I keep getting
TypeError: this.setSouthWest is not a function
so I guess there is a problem in this.mapbox.LngLatBounds(coords[0], coords[0]) , maybe the this.mapbox. or the LngLatBounds does not work.
If I console log the coords[0], prints an array [10.467778, 37.600833]
What am I missing? Thanks
I have got the same error. Turns out I have missed "new" keyword.
You can try adding the "new" keyword for "this.mapbox.LngLatBounds"
The following code worked for me.
import mapboxgl from 'mapbox-gl';
Vue.prototype.$maps = mapboxgl
this.map = new this.$maps.Map({container: 'mapContainer', // container ID
style: 'mapbox://styles/mapbox/streets-v11', // style URL
zoom: 9 // starting zoom
});
const sourceMarker = new this.$maps.Marker().setLngLat(origin).addTo(this.map);
const destMarker = new this.$maps.Marker().setLngLat(destination).addTo(this.map);
const bounds = new this.$maps.LngLatBounds(origin, destination);
this.map.fitBounds(bounds);

jest snapshot testing: how to ignore part of the snapshot file in jest test results

Problem: ignore some part of the .snap file test results
the question here: there are some components in my test that have a random values and i don't really care about testing them. is there any way to ignore part of my X.snap file? so when i run tests in the future it won't give me test fail results.
Now you can also use property matcher for these cases.
By example to be able to use snapshot with these object :
const obj = {
id: dynamic(),
foo: 'bar',
other: 'value',
val: 1,
};
You can use :
expect(obj).toMatchSnapshot({
id: expect.any(String),
});
Jest will just check that id is a String and will process the other fields in the snapshot as usual.
Actually, you need to mock the moving parts.
As stated in jest docs:
Your tests should be deterministic. That is, running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data.
If it's something related to time, you could use
Date.now = jest.fn(() => 1482363367071);
I know it's quite old question but I know one more solution. You can modify property you want to ignore, so it will be always constant instead of random / dynamic. This is best for cases when you are using third party code and thus may not be able to control the non deterministic property generation
Example:
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Card from './Card';
import toJSON from 'enzyme-to-json';
Enzyme.configure({ adapter: new Adapter() });
describe('<Card />', () => {
it('renders <Card /> component', () => {
const card = shallow(
<Card
baseChance={1}
name={`test name`}
description={`long description`}
imageURL={'https://d2ph5fj80uercy.cloudfront.net/03/cat1425.jpg'}
id={0}
canBeIgnored={false}
isPassive={false}
/>
);
const snapshot = toJSON(card);
// for some reason snapshot.node.props.style.backgroundColor = "#cfc5f6"
// does not work, seems the prop is being set later
Object.defineProperty(snapshot.node.props.style, 'backgroundColor', { value: "#cfc5f6", writable: false });
// second expect statement is enaugh but this is the prop we care about:
expect(snapshot.node.props.style.backgroundColor).toBe("#cfc5f6");
expect(snapshot).toMatchSnapshot();
});
});
You can ignore some parts in the snapshot tests replacing the properties in the HTML. Using jest with testing-library, it would look something like this:
it('should match snapshot', async () => {
expect(removeUnstableHtmlProperties(await screen.findByTestId('main-container'))).toMatchSnapshot();
});
function removeUnstableHtmlProperties(htmlElement: HTMLElement) {
const domHTML = prettyDOM(htmlElement, Infinity);
if (!domHTML) return undefined;
return domHTML.replace(/id(.*)"(.*)"/g, '');
}
I used this to override moment's fromNow to make my snapshots deterministic:
import moment, {Moment} from "moment";
moment.fn.fromNow = jest.fn(function (this: Moment) {
const withoutSuffix = false;
return this.from(moment("2023-01-12T20:14:00"), withoutSuffix);
});