Changelog: @tremolo-ui/dom
0.5.0
Minor Changes
-
#139
954dc53Thanks @m1m0zzz! - Move the drag-to-value logic into@tremolo-ui/domascreateDragValue.Slider,Knob,XYPadandPointsEditoreach turned pointer movement into a value on their own. They now share one primitive: a mapping decides where the pointer sits on the 0-1 travel of each axis, and the axis options (min/max/step/skew/reverse) turn that into a value, in the same order everywhere — position,reverse,skew, rounding to the step, clamping to the range.Two mappings ship with it.
elementMappingnormalizes the pointer against the bounding rect of an element, so the value is the position pointed at (Slider,XYPad,PointsEditor).relativeMappingmoves the value away from where it stood when the drag started, by the distance dragged (Knob).Breaking:
useDragWithElementis replaced byuseDragValue, which reports values rather than normalized coordinates and covers both mappings.const { refCallback, dragging } = useDragValue({axis: { min: 0, max: 100, step: 1 },baseElementRef: trackRef,updateOnPointerDown: true,onChange: ([x]) => setValue(x),})Breaking: the
XYOrSingletype ofXYPadis nowXYInput, and its pair form is areadonlytuple. A single value is told from a pair withArray.isArray, so where the value could itself be an array the single form is dropped and only the pair is left.createDragandcreateDragValuealso gainedupdate(), so a wrapper can feed fresh settings in without tearing down the listeners. Changingminormaxwhile a drag is in progress no longer aborts it.Fixes a crash when the element a drag normalizes against has collapsed to zero width or height: the position now reads 0 instead of throwing a
RangeError. -
#144
27209dcThanks @m1m0zzz! - Move the AnimationCanvas loop into@tremolo-ui/domascreateAnimationCanvas, and stop restarting it on every renderAnimationCanvaskept its whole setup — the 2D context, theResizeObserver, the device pixel ratio, therequestAnimationFrameloop — inside one effect whose dependencies includeddraw,initandoptions. Those are written inline at almost every call site, so they were new on every render and the effect tore everything down and built it again:initran repeatedly, andcountandelapsedTimewent back to zero. A canvas next to anything that sets state — a meter reading its level, say — never got past frame 0.The loop now lives in
@tremolo-ui/dom:const instance = createAnimationCanvas(canvas, { draw, animate, size })instance.update({ draw: nextDraw }) // swaps the handler, keeps the loop runninginstance.redraw()instance.destroy()The React component is a wrapper that creates the instance once and pushes fresh handlers in with
update(), the same shapeuseDragValuealready used.Fixed along the way:
widthandheighthad no effect once mounted. They were not effect dependencies, so changing them reset the canvas's backing store without re-applying the device pixel ratio transform, leaving the drawing at the wrong scale.- The first size of a
relativeSizecanvas came fromparent.clientWidth, later ones from the observer'scontentRect. Those differ by the parent's padding, so a padded parent drew at one size and then jumped. TheResizeObservernow reports every size, including the first. - Resizing blurred the canvas on a HiDPI screen. The snapshot that carries the drawing across a resize was scaled down by the device pixel ratio on the way out and back up on the way in. The two cancelled out, so it landed in the right place at the right size, but it had been through a downscale and an upscale. It is now copied at the canvas's own device resolution and drawn back at its old CSS size, which is a 1:1 copy of device pixels while the ratio holds — and a single correct rescale from full resolution when the ratio changes.
- The hidden
<canvas>used to carry the drawing across a resize is no longer rendered into the document; the core makes one off-document when it needs it.
With
animateoff,update()draws a frame: the loop is not running, so a resize and that call are the only things that can put a new drawing on the canvas. That is what keeps the documented "reactive canvas" —useStatewithanimate={false}— repainting when state changes.optionsis no longer an effect dependency. It is read once when the context is created, so writing it inline no longer rebuilds the canvas on every render.AnimationCanvaskeeps the same props.@tremolo-ui/domgainscreateAnimationCanvas,drawingStateandisDrawingState, with theAnimationFrame,AnimationCanvasOptionsandAnimationCanvasInstancetypes. -
#142
0646236Thanks @m1m0zzz! - Replaceskewwithscale, and add scales that do not break down at the ends of the rangeBreaking. The
skewprop ofSlider.Root,Knob.Root,XYPad.RootandNumberInput.Root, andValueRange.skewin@tremolo-ui/functions, are replaced byscale, which takes aScale.-<Knob.Root min={20} max={22000} skew={skewWithCenterValue(663, 20, 22000)} …>+<Knob.Root min={20} max={22000} scale={exponentialScale} …>@tremolo-ui/functionsgains theScaleinterface and five scales:linearScale— the default. Equal travel, equal change in valueexponentialScale— equal travel, equal ratio: every octave takes the same distance. For frequency, free running rates and delay times. Requiresminandmaxto be non-zero and of the same signcurveScale(curve)— an exponential bend that still passes throughminandmax, so it works on a range that starts at or crosses 0.curve > 0favours the lower end,curve < 0the upper end. Pair it withcurveWithCenterValue()symmetricSkewScale(skew)— the same bend mirrored about the middle, for a bipolar control that needs fine adjustment around its centreskewScale(skew)— the power law of JUCE'sNormalisableRange, for a value that has to agree with a JUCE or iPlug2 parameter.skewWithCenterValue()still applies to it
A
Scaletakesminandmaxas arguments rather than holding them, so it carries no state and can be a module level constant.normalizeValue()andrawValue()lose theirskewparameter and are now the linear mapping alone — every curve lives in aScale.applyDelta()takes the scale through itsValueRange.skewWithCenterValue(),ValueRangeandapplyDelta()keep their behaviour and move next to the scales they belong to; the names exported from the package are unchanged.-normalizeValue(value, min, max, skew)+skewScale(skew).normalize(value, min, max)-rawValue(position, min, max, skew)+skewScale(skew).denormalize(position, min, max)This fixes the value jumping on a knob with a logarithmic scale. The power law is applied to
value - min, so its slope atminis either infinite or zero: a dB knob over-60..6moved 12% of its range on the first pixel of a drag, and a frequency knob over20..22000did not move at all for the first 12 pixels.exponentialScaleandcurveScalehave neither problem.skewScalestill behaves this way, since matching JUCE is the point of it. -
#146
fe74061Thanks @m1m0zzz! - RedesignPiano: the keyboard is no longer built from key components, and several fingers can play at once.Piano.Rootused to draw nothing on its own — a note only sounded becausePiano.WhiteKey/Piano.BlackKeycalledonPlayNotefrom an imperative handle, whichRootreached through an array of refs indexed by the order of its children. Custom children, or children in a different order, silently broke both the sound and the highlighting. The key geometry was kept in two places as well:Roothit-tested with its own white key width while each key drew itself with its ownwidthprop, so<Piano.WhiteKey width={60} />drew a key that responded somewhere else.Rootnow owns the keys and everything that is sounding. Per-key customization is two callbacks rather than a component per key.<Piano.RootnoteRange={{ first: noteNumber('C3'), last: noteNumber('B4') }}label={(note, { index }) => SHORTCUTS.HOME_ROW.keys[index]}keyProps={(note) => ({ 'data-in-scale': inScale(note, root, 'major') })}onPlayNote={(note) => synth.triggerAttack(noteName(note))}onStopNote={(note) => synth.triggerRelease(noteName(note))}/>Each key carries
data-note,data-note-key,data-activeandaria-disabled, so static styling needs no callback at all. The geometry of a key is applied after whateverkeyPropsreturns, so a key can no longer be drawn away from where it responds.Every way of playing a note — pointers, keyboard shortcuts,
playNote()from the ref — now goes through one instance that counts the sources holding each note, so a note stops only once the last of them lets go. Multi-touch and glissando work:createDraggainedmultiPointer, and@tremolo-ui/domgainedcreatePianoInput.Also new in
@tremolo-ui/functions: musical scales (scaleIntervals,inScale,scaleNotes) inmidi, and the piano geometry (PianoLayout,notePosition,noteAt,pianoWidth) inpiano.Breaking changes:
Piano.WhiteKey,Piano.BlackKey,Piano.KeyLabeland theKeyProps/KeyMethods/KeyLabelPropstypes are removed. UselabelandkeyProps, or plain CSS on.tremolo-piano-white-key/.tremolo-piano-black-keylabeltakes(note, state)rather than(note, index); the index isstate.index. A label of'',nullorundefinednow draws nothing rather than an empty boxgetNoteRangeArrayand theNoteRangetype moved to@tremolo-ui/functionswhiteNoteWidthis nowwhiteKeyWidth, and the deadblackNoteWidthprop is replaced byblackKeyWidthRatio/blackKeyHeightRatio/keyGapKeyboardShortcuts.flagsis removed. It was declared but never implemented;SHORTCUTS.HOME_ROW_NATURALcovers whatnaturalOnlywas for, by leaving an empty string where a note has no shortcut
-
#141
95df589Thanks @m1m0zzz! - RebuildNumberInputon the compound pattern the other components already use, and give it one piece of state: the text being typed.The value is a
number, and what the input shows isformat(value)— except while the user is typing, when their own text stands until it is committed. Everything else is derived during render. The<input>is no longer rendered for you; compose it asNumberInput.InputField, the waySlider.Trackis composed.<NumberInput.Root value={value} min={0} max={100} units="Hz" onChange={setValue}><NumberInput.InputField /><NumberInput.Stepper><NumberInput.IncrementStepper /><NumberInput.DecrementStepper /></NumberInput.Stepper></NumberInput.Root>Keeping the typed text rather than reformatting it on every keystroke removes the cursor-position restoring that used to be needed, and lets a value be entered digit by digit: typing is never clamped, and the entry is brought into range when it is committed on blur or Enter.
Breaking changes to
NumberInput:childrenis required, andInputFieldhas to be composed in. There is no default markup to fall back tovalueis anumber; astringis no longer acceptedonChangereports(value: number)rather than(value, text)variant,activeColorandwrapperClassNameare gone.Rootis the wrapper, so itsclassNamestyles it, and the colors are CSS variables. The four variants are shown in the documentation as CSS to copykeepWithinRangeandclampValueOnBlurare oneclampValueprop (defaulttrue)selectWithFocusandblurOnEntermoved toInputField, asselectOnFocusandblurOnEnter. ItsonFocus/onBlurare plain DOM handlersStepperlostdynamic, and the steppers lostsize: both are styling, now the--stepper-icon-sizevariable and the demo CSS- the class names follow the parts:
tremolo-number-inputis the root andtremolo-number-input-fieldthe input, where the root used to betremolo-number-input-wrapper data-errorisdata-out-of-range
New in
NumberInput:skew,format/parsefor text the units cannot express, and dragging theStepperup and down to move the value, onestepeverydragpixels (1 by default). It needs no range to work against, so an unbounded input can be dragged too.The
<input>is now the tab stop and carries the spinbutton role and range, where the wrapper used to take focus and the input was skipped.Wheel control now only acts while the focus is inside the component, across
Slider,Knob,XYPadandNumberInput. Reacting on hover alone took the scroll away from the page, so passing over a control while reading changed its value.createWheelgained arequireFocusoption, andupdate().@tremolo-ui/functionsgainsformatValue,parseValue,selectUnitand theUnitstype, moved out of@tremolo-ui/reactso that they are available to any wrapper.It also gains
applyDelta, which moves a value by one wheel notch or arrow key press.Slider,Knob,XYPadandNumberInputeach had their own copy of this; they now share one, andAxisOptionsof@tremolo-ui/domextends itsValueRange, so a drag and a nudge describe their scaling the same way.Fixes
NumberInputthrowing"min" and "max" are requiredfromwheelorkeyboardinnormalizedmode wheneverminwas0, which a truthiness check rejected.
Patch Changes
-
#137
68f05cbThanks @m1m0zzz! - Fix a slow drag not registering. Movement belowcreateDrag's threshold was discarded instead of carried over, and pointer coordinates are fractional, so dragging slowly moved less than a pixel per event and never reported anything. It now accumulates until it crosses the threshold.The threshold also now defaults to 0 in
createDrag, which restoresuseDragWithElement(used bySlider,XYPadandPointsEditor) to having no threshold at all, as it did before the move to@tremolo-ui/dom.useDragstill defaults to 1. -
Updated dependencies [
0646236,fe74061,95df589]:- @tremolo-ui/functions@0.5.0
0.4.0
Minor Changes
-
#133
c0bda83Thanks @m1m0zzz! - Move pointer drag and wheel handling into@tremolo-ui/domascreateDragandcreateWheel.createDraguses Pointer Events only and relies on pointer capture, so the drag keeps working once the pointer leaves the element and no window level listeners are needed. It appliestouch-action: noneso that touch dragging does not scroll the page, and cancelsselectstartso that a long press does not start a text selection instead.The drag cursor (
externalStyles.cursor) is now applied to the dragged element rather than todocument.body. Pointer capture keeps it in effect once the pointer leaves the element, so there is no need to restyle the whole document, and long pressing no longer flashes a selection across the page.Fixes a bug where a drag starting at screen coordinate 0 (the top or left edge of the screen) never reported any movement, and a bug where
useDragWithElementpassed stale coordinates toonDragStart.SliderandXYPadnow move to the pointer position on pointer down, instead of waiting for the first movement.Breaking:
useDragnow returns a single ref callback instead of[refCallback, pointerDownHandler], anduseDragWithElementreturns{ refCallback, dragging }instead of{ refHandler, pointerDownHandler, dragging }. A newuseWheelhook is exported.Breaking:
DragObserverandWheelObserverare removed. They had become thin wrappers arounduseDraganduseWheel, which replace them.