refactor(editor): extract slider component (#12210)

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
  - Introduced a new slider component for line width selection, providing a more interactive and streamlined UI.
  - Added support for using the slider component across relevant panels.
- **Improvements**
  - Simplified the line width selection panel for easier use and improved maintainability.
  - Enhanced event handling to prevent dropdowns from closing when interacting with the panel.
- **Bug Fixes**
  - Improved event propagation control within the line styles panel.
- **Chores**
  - Updated package exports to include the new slider component.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
L-Sun
2025-05-12 09:42:52 +00:00
parent bc00a58ae1
commit f3ca17fcb3
14 changed files with 308 additions and 227 deletions
@@ -0,0 +1,6 @@
import { Slider } from './slider';
export * from './types';
export function effects() {
customElements.define('affine-slider', Slider);
}
@@ -0,0 +1,159 @@
import { on, once } from '@blocksuite/affine-shared/utils';
import { clamp } from '@blocksuite/global/gfx';
import { WithDisposable } from '@blocksuite/global/lit';
import { PropTypes, requiredProperties } from '@blocksuite/std';
import { html, LitElement, nothing, type PropertyValues } from 'lit';
import { property } from 'lit/decorators.js';
import { repeat } from 'lit/directives/repeat.js';
import { styles } from './styles';
import type { SliderRange, SliderSelectEvent, SliderStyle } from './types';
import { isDiscreteRange } from './utils';
const defaultSliderStyle: SliderStyle = {
width: '100%',
itemSize: 16,
itemIconSize: 8,
dragHandleSize: 14,
};
@requiredProperties({
range: PropTypes.of(isDiscreteRange),
})
export class Slider extends WithDisposable(LitElement) {
static override styles = styles;
@property({ attribute: false })
accessor value: number = 0;
@property({ attribute: true, type: Boolean })
accessor disabled = false;
@property({ attribute: false })
accessor tooltip: string | undefined = undefined;
@property({ attribute: false })
accessor range!: SliderRange;
@property({ attribute: false })
accessor sliderStyle: Partial<SliderStyle> | undefined = defaultSliderStyle;
private get _sliderStyle(): SliderStyle {
return {
...defaultSliderStyle,
...this.sliderStyle,
};
}
private _onSelect(value: number) {
this.dispatchEvent(
new CustomEvent('select', {
detail: { value },
bubbles: true,
composed: true,
}) satisfies SliderSelectEvent
);
}
private _updateLineWidthPanelByDragHandlePosition(x: number) {
// Calculate the selected size based on the drag handle position.
// Need to select the nearest size.
const {
_sliderStyle: { itemSize },
} = this;
const width = this.getBoundingClientRect().width;
const { points } = this.range;
const count = points.length;
const targetWidth = width - itemSize;
const halfItemSize = itemSize / 2;
const offsetX = halfItemSize + (width - itemSize * count) / (count - 1) / 2;
const selectedSize = points.findLast((_, n) => {
const cx = halfItemSize + (n / (count - 1)) * targetWidth;
return x >= cx - offsetX && x < cx + offsetX;
});
if (!selectedSize) return;
this._onSelect(selectedSize);
}
private readonly _getDragHandlePosition = (e: PointerEvent) => {
const width = this.getBoundingClientRect().width;
return clamp(e.offsetX, 0, width);
};
private readonly _onPointerDown = (e: PointerEvent) => {
e.preventDefault();
e.stopPropagation();
this._onPointerMove(e);
const dispose = on(this, 'pointermove', this._onPointerMove);
this._disposables.add(once(this, 'pointerup', dispose));
this._disposables.add(once(this, 'pointerout', dispose));
};
private readonly _onPointerMove = (e: PointerEvent) => {
e.preventDefault();
e.stopPropagation();
const x = this._getDragHandlePosition(e);
this._updateLineWidthPanelByDragHandlePosition(x);
};
override connectedCallback() {
super.connectedCallback();
this._disposables.addFromEvent(this, 'pointerdown', this._onPointerDown);
this._disposables.addFromEvent(this, 'click', e => {
e.stopPropagation();
});
}
override willUpdate(changedProperties: PropertyValues<this>) {
const { style } = this;
if (changedProperties.has('sliderStyle')) {
const {
_sliderStyle: { width, itemSize, itemIconSize, dragHandleSize },
} = this;
style.setProperty('--width', width);
style.setProperty('--item-size', `${itemSize}px`);
style.setProperty('--item-icon-size', `${itemIconSize}px`);
style.setProperty('--drag-handle-size', `${dragHandleSize}px`);
}
if (changedProperties.has('range')) {
style.setProperty('--count', `${this.range.points.length}`);
}
if (changedProperties.has('value')) {
const index = this.range.points.findIndex(p => p === this.value);
style.setProperty('--cursor', `${index}`);
}
}
override render() {
return html`<div class="slider-container">
${repeat(
this.range.points,
w => w,
(w, n) =>
html`<div
class="point-button"
aria-label=${w}
data-index=${n}
?data-selected=${w <= this.value}
>
<div class="point-circle"></div>
</div>`
)}
<div class="drag-handle"></div>
<div class="bottom-line"></div>
<div class="slider-selected-overlay"></div>
${this.tooltip
? html`<affine-tooltip .offset=${8}>${this.tooltip}</affine-tooltip>`
: nothing}
</div>`;
}
}
@@ -0,0 +1,74 @@
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { css } from 'lit';
export const styles = css`
:host([disabled]) {
opacity: 0.5;
pointer-events: none;
}
.slider-container {
--drag-handle-center-x: calc(
(var(--item-size) - var(--drag-handle-size)) / 2 +
(var(--cursor) / (var(--count) - 1)) *
calc(var(--width) - var(--item-size))
);
width: var(--width);
height: 24px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
position: relative;
cursor: default;
}
.point-button {
display: flex;
align-items: center;
justify-content: center;
width: var(--item-size);
height: var(--item-size);
z-index: 2;
}
.point-circle {
width: var(--item-icon-size);
height: var(--item-icon-size);
background-color: ${unsafeCSSVarV2('layer/insideBorder/border')};
border-radius: 50%;
}
.point-button[data-selected] .point-circle {
background-color: ${unsafeCSSVarV2('icon/primary')};
}
.drag-handle {
position: absolute;
width: var(--drag-handle-size);
height: var(--drag-handle-size);
border-radius: 50%;
background-color: ${unsafeCSSVarV2('icon/primary')};
z-index: 3;
left: var(--drag-handle-center-x);
}
.bottom-line,
.slider-selected-overlay {
position: absolute;
height: 1px;
left: calc(var(--item-size) / 2);
}
.bottom-line {
width: calc(100% - var(--item-size));
background-color: ${unsafeCSSVarV2('layer/insideBorder/border')};
}
.slider-selected-overlay {
background-color: ${unsafeCSSVarV2('icon/primary')};
z-index: 1;
width: var(--drag-handle-center-x);
}
`;
@@ -0,0 +1,22 @@
export type SliderRange = {
/**
* a series of points in slider
*/
points: number[];
/**
* whether the points are uniformly distributed
* @default true
*/
uniform?: boolean;
};
export type SliderStyle = {
width: string;
itemSize: number;
itemIconSize: number;
dragHandleSize: number;
};
export type SliderSelectEvent = CustomEvent<{
value: number;
}>;
@@ -0,0 +1,10 @@
import type { SliderRange } from './types';
export function isDiscreteRange(range: unknown): range is SliderRange {
return (
typeof range === 'object' &&
range !== null &&
'points' in range &&
Array.isArray(range.points)
);
}