Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(design): expose accessible names for switches and clear actions (#8114)

白熱910224591662
diff --git a/packages/design/src/components/dialog/DialogPrimitive.tsx b/packages/design/src/components/dialog/DialogPrimitive.tsx
index cc674cc118..14a92cbf8d 100644
--- a/packages/design/src/components/dialog/DialogPrimitive.tsx
+++ b/packages/design/src/components/dialog/DialogPrimitive.tsx
@@ -20,7 +20,6 @@ import { CloseIcon } from '@univerjs/icons';
import { forwardRef, useContext } from 'react';
import { borderClassName } from '../../helper/class-utilities';
import { clsx } from '../../helper/clsx';
-import enUS from '../../locale/en-US';
import { ConfigContext } from '../config-provider/ConfigProvider';
const Dialog = Root;
@@ -107,7 +106,7 @@ const DialogContent = forwardRef<
}}
>
<CloseIcon className="univer-size-4 univer-text-gray-400" />
- <span className="univer-sr-only">{locale?.Accessibility.close ?? enUS.design.Accessibility.close}</span>
+ <span className="univer-sr-only">{locale?.Accessibility.close}</span>
</Close>
)}
</Content>
diff --git a/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx b/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx
index 93b10d4764..9b05136a97 100644
--- a/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx
+++ b/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx
@@ -97,9 +97,11 @@ describe('Dialog', () => {
const onClose = vi.fn();
const onOpenChange = vi.fn();
const { getByRole } = render(
- <Dialog open title="Title" mask={mask} keyboard={false} onClose={onClose} onOpenChange={onOpenChange}>
- <input aria-label="Dialog draft" />
- </Dialog>
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <Dialog open title="Title" mask={mask} keyboard={false} onClose={onClose} onOpenChange={onOpenChange}>
+ <input aria-label="Dialog draft" />
+ </Dialog>
+ </ConfigProvider>
);
const input = getByRole('textbox');
input.focus();
diff --git a/packages/design/src/components/dialog/__tests__/MobileDialog.spec.tsx b/packages/design/src/components/dialog/__tests__/MobileDialog.spec.tsx
index 3ca50e9557..2c774818b1 100644
--- a/packages/design/src/components/dialog/__tests__/MobileDialog.spec.tsx
+++ b/packages/design/src/components/dialog/__tests__/MobileDialog.spec.tsx
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { IMobileKeyboardViewport } from '../../config-provider/ConfigProvider';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IMobileKeyboardViewport } from '../../config-provider/ConfigProvider';
import enUS from '../../../locale/en-US';
import zhCN from '../../../locale/zh-CN';
import { ConfigProvider } from '../../config-provider/ConfigProvider';
@@ -125,9 +125,11 @@ describe('MobileDialog', () => {
it('keeps Escape disabled without disabling the close control', () => {
const onClose = vi.fn();
const { getByRole } = render(
- <MobileDialog open keyboard={false} onClose={onClose}>
- <input aria-label="Dialog draft" />
- </MobileDialog>
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDialog open keyboard={false} onClose={onClose}>
+ <input aria-label="Dialog draft" />
+ </MobileDialog>
+ </ConfigProvider>
);
const input = getByRole('textbox');
input.focus();
diff --git a/packages/design/src/components/gallery/Gallery.tsx b/packages/design/src/components/gallery/Gallery.tsx
index 6a2cf77ca4..4d2d4be2bb 100644
--- a/packages/design/src/components/gallery/Gallery.tsx
+++ b/packages/design/src/components/gallery/Gallery.tsx
@@ -66,7 +66,7 @@ export function Gallery(props: IGalleryProps) {
const hasPagination = images.length > 1;
const imageLabel = locale?.Accessibility.image
?.replace('{0}', String(activeImageIndex + 1))
- .replace('{1}', String(images.length)) ?? `Image ${activeImageIndex + 1} of ${images.length}`;
+ .replace('{1}', String(images.length));
useEffect(() => {
const timer = setTimeout(() => {
@@ -187,7 +187,7 @@ export function Gallery(props: IGalleryProps) {
dir={direction}
role="dialog"
aria-modal="true"
- aria-label={locale?.Accessibility.imageGallery ?? 'Image gallery'}
+ aria-label={locale?.Accessibility.imageGallery}
tabIndex={-1}
ref={dialogRef}
className={clsx(
@@ -214,7 +214,7 @@ export function Gallery(props: IGalleryProps) {
type="button"
variant="ghost"
size="icon"
- aria-label={locale?.Accessibility.close ?? 'Close'}
+ aria-label={locale?.Accessibility.close}
className={`
univer-absolute univer-right-4 univer-top-4 univer-z-10 univer-size-10 univer-rounded-full
!univer-border-gray-500 !univer-bg-gray-800 !univer-text-gray-0
@@ -269,8 +269,8 @@ export function Gallery(props: IGalleryProps) {
`}
value={activeImageIndex + 1}
total={images.length}
- previousButtonAriaLabel={locale?.Accessibility.previous ?? 'Previous'}
- nextButtonAriaLabel={locale?.Accessibility.next ?? 'Next'}
+ previousButtonAriaLabel={locale?.Accessibility.previous}
+ nextButtonAriaLabel={locale?.Accessibility.next}
onChange={(value) => setActiveImageIndex(value - 1)}
/>
)}
@@ -278,7 +278,7 @@ export function Gallery(props: IGalleryProps) {
type="button"
variant="ghost"
size="icon"
- aria-label={locale?.Accessibility.zoomIn ?? 'Zoom in'}
+ aria-label={locale?.Accessibility.zoomIn}
className={toolbarButtonClassName}
disabled={zoomLevel >= 2}
onClick={() => handleToggleZoom(0.25)}
@@ -289,7 +289,7 @@ export function Gallery(props: IGalleryProps) {
type="button"
variant="ghost"
size="icon"
- aria-label={locale?.Accessibility.zoomOut ?? 'Zoom out'}
+ aria-label={locale?.Accessibility.zoomOut}
className={toolbarButtonClassName}
disabled={zoomLevel <= 0.5}
onClick={() => handleToggleZoom(-0.25)}
@@ -300,7 +300,7 @@ export function Gallery(props: IGalleryProps) {
type="button"
variant="ghost"
size="icon"
- aria-label={locale?.Accessibility.resetZoom ?? 'Reset zoom'}
+ aria-label={locale?.Accessibility.resetZoom}
className={toolbarButtonClassName}
disabled={zoomLevel === 1}
onClick={() => handleToggleZoom('reset')}
diff --git a/packages/design/src/components/input/Input.tsx b/packages/design/src/components/input/Input.tsx
index f56885585e..1c4221c9e3 100644
--- a/packages/design/src/components/input/Input.tsx
+++ b/packages/design/src/components/input/Input.tsx
@@ -18,7 +18,7 @@ import type { VariantProps } from 'class-variance-authority';
import type { InputHTMLAttributes } from 'react';
import { CloseIcon } from '@univerjs/icons';
import { cva } from 'class-variance-authority';
-import { forwardRef, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { forwardRef, useContext, useEffect, useRef, useState } from 'react';
import { borderClassName } from '../../helper/class-utilities';
import { clsx } from '../../helper/clsx';
import { ConfigContext } from '../config-provider/ConfigProvider';
@@ -88,7 +88,7 @@ export const Input = forwardRef<HTMLInputElement, IInputProps>(
inputStyle,
...props
}, ref) => {
- const { direction } = useContext(ConfigContext);
+ const { direction, locale } = useContext(ConfigContext);
const handleClear = (e: React.MouseEvent) => {
e.stopPropagation();
@@ -99,9 +99,7 @@ export const Input = forwardRef<HTMLInputElement, IInputProps>(
onChange?.(e.target.value);
};
- const hasSlotContent = useMemo(() => {
- return (allowClear && value && !disabled) || slot;
- }, [allowClear, disabled, slot, value]);
+ const hasSlotContent = (allowClear && value && !disabled) || slot;
const [paddingRight, setPaddingRight] = useState(0);
const slotRef = useRef<HTMLDivElement>(null);
@@ -121,18 +119,18 @@ export const Input = forwardRef<HTMLInputElement, IInputProps>(
}
return () => observer?.disconnect();
- }, [slotRef.current]);
-
- useEffect(() => {
- if (allowClear && !(slot && slotRef.current)) setPaddingRight(26);
- }, []); // only enough for init, otherwise it works again when you click it
-
- const shouldOmitDefaultPadding = direction === 'rtl' && paddingRight === 0;
- const mergedInputStyle = shouldOmitDefaultPadding
+ }, [slot]);
+
+ let trailingPadding = 0;
+ if (slot) {
+ trailingPadding = paddingRight;
+ } else if (allowClear) {
+ trailingPadding = 26;
+ }
+ const paddingSide = direction === 'rtl' ? 'paddingLeft' : 'paddingRight';
+ const mergedInputStyle = direction === 'rtl' && trailingPadding === 0
? inputStyle
- : direction === 'rtl'
- ? { ...inputStyle, paddingLeft: paddingRight }
- : { ...inputStyle, paddingRight };
+ : { ...inputStyle, [paddingSide]: trailingPadding };
return (
<div
@@ -181,16 +179,17 @@ export const Input = forwardRef<HTMLInputElement, IInputProps>(
{allowClear && value && !disabled && (
<button
type="button"
+ aria-label={locale?.Accessibility.clearInput}
onClick={handleClear}
className={`
univer-flex univer-size-4 univer-cursor-pointer univer-items-center
univer-rounded-full univer-border-none univer-bg-transparent univer-p-1
univer-text-gray-400 univer-transition-colors univer-duration-200
hover:univer-text-gray-500
- focus:univer-outline-none
+ focus:univer-outline-none focus:univer-ring-2 focus:univer-ring-primary-600
`}
>
- <CloseIcon className="univer-size-3" />
+ <CloseIcon aria-hidden="true" className="univer-size-3" />
</button>
)}
</div>
diff --git a/packages/design/src/components/input/__tests__/Input.spec.tsx b/packages/design/src/components/input/__tests__/Input.spec.tsx
index 99a2d6ce13..72daa279ef 100644
--- a/packages/design/src/components/input/__tests__/Input.spec.tsx
+++ b/packages/design/src/components/input/__tests__/Input.spec.tsx
@@ -16,13 +16,12 @@
import { cleanup, fireEvent, render } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import zhCN from '../../../locale/zh-CN';
import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { Input } from '../Input';
afterEach(cleanup);
-afterEach(() => {
- vi.unstubAllGlobals();
-});
describe('Input', () => {
it('forwards mobile keyboard, validation and focus attributes to the input', () => {
@@ -87,106 +86,20 @@ describe('Input', () => {
expect(parentClick).not.toHaveBeenCalled();
});
- it('should observe slot mutations and apply slot paddingRight', () => {
- const observe = vi.fn();
- const disconnect = vi.fn();
- class MockMutationObserver {
- private _callback: MutationCallback;
-
- constructor(callback: MutationCallback) {
- this._callback = callback;
- }
-
- observe(...args: unknown[]) {
- observe(...args);
- this._callback([], {} as MutationObserver);
- }
-
- disconnect() {
- disconnect();
- }
- }
-
- vi.stubGlobal('MutationObserver', MockMutationObserver);
-
- const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
- configurable: true,
- get() {
- return 20;
- },
- });
-
- const { container } = render(<Input value="x" slot={<span>slot</span>} />);
- const input = container.querySelector('input') as HTMLInputElement;
- expect(observe).toHaveBeenCalled();
- expect(input.style.paddingRight).toBe('28px');
-
- if (originalOffsetWidth) {
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
- }
- });
-
- it('should observe slot mutations and apply slot paddingLeft in rtl', () => {
- const observe = vi.fn();
- class MockMutationObserver {
- private _callback: MutationCallback;
-
- constructor(callback: MutationCallback) {
- this._callback = callback;
- }
-
- observe(...args: unknown[]) {
- observe(...args);
- this._callback([], {} as MutationObserver);
- }
-
- disconnect() {
- }
- }
-
- vi.stubGlobal('MutationObserver', MockMutationObserver);
-
- const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
- configurable: true,
- get() {
- return 20;
- },
- });
-
- const { container } = render(
- <ConfigProvider mountContainer={document.body} direction="rtl">
- <Input value="x" slot={<span>slot</span>} />
+ it('names the clear action in the current locale and preserves its behavior', () => {
+ const onChange = vi.fn();
+ const { getByRole, rerender } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <Input allowClear value="abc" onChange={onChange} />
</ConfigProvider>
);
- const input = container.querySelector('input') as HTMLInputElement;
- const slot = container.querySelector('[data-u-comp="input"] > div') as HTMLDivElement;
-
- expect(observe).toHaveBeenCalled();
- expect(input.style.paddingLeft).toBe('28px');
- expect(input.style.paddingRight).toBe('');
- expect(slot.className).toContain('univer-left-2');
- expect(slot.className).not.toContain('univer-right-2');
-
- if (originalOffsetWidth) {
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
- }
- });
-
- it('should set default allowClear padding when no slot exists', () => {
- const { container } = render(<Input allowClear value="x" />);
- const input = container.querySelector('input') as HTMLInputElement;
- expect(input.style.paddingRight).toBe('26px');
- });
-
- it('should not override rtl right padding when no trailing content exists', () => {
- const { container } = render(
- <ConfigProvider mountContainer={document.body} direction="rtl">
- <Input />
+ fireEvent.click(getByRole('button', { name: 'Clear input' }));
+ expect(onChange).toHaveBeenCalledWith('');
+ rerender(
+ <ConfigProvider locale={zhCN.design} mountContainer={document.body}>
+ <Input allowClear value="abc" onChange={onChange} />
</ConfigProvider>
);
- const input = container.querySelector('input') as HTMLInputElement;
- expect(input.style.paddingRight).toBe('');
+ expect(getByRole('button', { name: '清空输入' })).toBeDefined();
});
});
diff --git a/packages/design/src/components/pager/Pager.tsx b/packages/design/src/components/pager/Pager.tsx
index 799e20e590..600e125318 100644
--- a/packages/design/src/components/pager/Pager.tsx
+++ b/packages/design/src/components/pager/Pager.tsx
@@ -16,7 +16,6 @@
import { MoreLeftIcon, MoreRightIcon } from '@univerjs/icons';
import { useContext } from 'react';
-
import { clsx } from '../../helper/clsx';
import { ConfigContext } from '../config-provider/ConfigProvider';
@@ -92,7 +91,7 @@ export function Pager(props: IPagerProps) {
dark:hover:!univer-bg-gray-600
`}
type="button"
- aria-label={previousButtonAriaLabel ?? locale?.Accessibility.previous ?? 'Previous'}
+ aria-label={previousButtonAriaLabel ?? locale?.Accessibility.previous}
disabled={previousButtonDisabled}
onClick={onClickLeftArrow}
>
@@ -111,7 +110,7 @@ export function Pager(props: IPagerProps) {
dark:hover:!univer-bg-gray-600
`}
type="button"
- aria-label={nextButtonAriaLabel ?? locale?.Accessibility.next ?? 'Next'}
+ aria-label={nextButtonAriaLabel ?? locale?.Accessibility.next}
disabled={nextButtonDisabled}
onClick={onClickRightArrow}
>
diff --git a/packages/design/src/components/pager/__tests__/index.spec.tsx b/packages/design/src/components/pager/__tests__/Pager.spec.tsx
similarity index 76%
rename from packages/design/src/components/pager/__tests__/index.spec.tsx
rename to packages/design/src/components/pager/__tests__/Pager.spec.tsx
index f380561033..148924e7ec 100644
--- a/packages/design/src/components/pager/__tests__/index.spec.tsx
+++ b/packages/design/src/components/pager/__tests__/Pager.spec.tsx
@@ -14,15 +14,20 @@
* limitations under the License.
*/
-import type { ComponentProps } from 'react';
+import type { ComponentProps, ReactNode } from 'react';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
+import enUS from '../../../locale/en-US';
+import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { Pager } from '../Pager';
import '@testing-library/jest-dom/vitest';
afterEach(cleanup);
+function TestConfigProvider({ children }: { children: ReactNode }) {
+ return <ConfigProvider locale={enUS.design} mountContainer={document.body}>{children}</ConfigProvider>;
+}
+
describe('Pager', () => {
let defaultProps: ComponentProps<typeof Pager>;
@@ -35,25 +40,25 @@ describe('Pager', () => {
});
it('renders correctly with default props', () => {
- const { getByText } = render(<Pager {...defaultProps} />);
+ const { getByText } = render(<Pager {...defaultProps} />, { wrapper: TestConfigProvider });
expect(getByText('1/5')).toBeTruthy();
});
it('renders correctly with custom text', () => {
const props: ComponentProps<typeof Pager> = { ...defaultProps, text: 'Custom Text' };
- const { getByText } = render(<Pager {...props} />);
+ const { getByText } = render(<Pager {...props} />, { wrapper: TestConfigProvider });
expect(getByText('Custom Text')).toBeTruthy();
});
it('renders only text when total is 0', () => {
const props: ComponentProps<typeof Pager> = { ...defaultProps, total: 0 };
- const { getByText, queryByRole } = render(<Pager {...props} />);
+ const { getByText, queryByRole } = render(<Pager {...props} />, { wrapper: TestConfigProvider });
expect(getByText('1/0')).toBeTruthy();
expect(queryByRole('button')).not.toBeTruthy();
});
it('calls onChange with correct value when arrow is clicked', () => {
- const { rerender } = render(<Pager {...defaultProps} />);
+ const { rerender } = render(<Pager {...defaultProps} />, { wrapper: TestConfigProvider });
const rightArrow = screen.getByRole('button', { name: 'Next' });
fireEvent.click(rightArrow);
@@ -67,8 +72,8 @@ describe('Pager', () => {
it('loops to last page when clicking left arrow on first page', () => {
const props: ComponentProps<typeof Pager> = { ...defaultProps, loop: true };
- const { container } = render(<Pager {...props} />);
- const leftArrow = container.querySelector('[data-u-comp="pager-left-arrow"]') as HTMLButtonElement;
+ render(<Pager {...props} />, { wrapper: TestConfigProvider });
+ const leftArrow = screen.getByRole('button', { name: 'Previous' });
fireEvent.click(leftArrow);
expect(props.onChange).toBeCalledWith(5);
@@ -76,8 +81,8 @@ describe('Pager', () => {
it('loops to first page when clicking right arrow on last page', () => {
const props: ComponentProps<typeof Pager> = { ...defaultProps, value: 5, loop: true };
- const { container } = render(<Pager {...props} />);
- const rightArrow = container.querySelector('[data-u-comp="pager-right-arrow"]') as HTMLButtonElement;
+ render(<Pager {...props} />, { wrapper: TestConfigProvider });
+ const rightArrow = screen.getByRole('button', { name: 'Next' });
fireEvent.click(rightArrow);
expect(props.onChange).toBeCalledWith(1);
@@ -85,7 +90,7 @@ describe('Pager', () => {
it('does not loop when loop prop is false', () => {
const props: ComponentProps<typeof Pager> = { ...defaultProps, value: 5, loop: false };
- render(<Pager {...props} />);
+ render(<Pager {...props} />, { wrapper: TestConfigProvider });
const rightArrow = screen.getByRole('button', { name: 'Next' });
expect(rightArrow).toBeDisabled();
diff --git a/packages/design/src/components/switch/Switch.tsx b/packages/design/src/components/switch/Switch.tsx
index feb295c885..5e75962c13 100644
--- a/packages/design/src/components/switch/Switch.tsx
+++ b/packages/design/src/components/switch/Switch.tsx
@@ -14,32 +14,35 @@
* limitations under the License.
*/
-import { useEffect, useState } from 'react';
+import type { ChangeEvent, InputHTMLAttributes } from 'react';
+import { useState } from 'react';
import { clsx } from '../../helper/clsx';
-export interface ISwitchProps {
+export interface ISwitchProps extends Pick<InputHTMLAttributes<HTMLInputElement>, 'id' | 'aria-label' | 'aria-labelledby' | 'aria-describedby'> {
defaultChecked?: boolean;
onChange?: (checked: boolean) => void;
}
const Switch = (props: ISwitchProps) => {
- const { defaultChecked = false, onChange } = props;
- const [checked, setChecked] = useState(defaultChecked);
+ const { defaultChecked = false, onChange, ...inputProps } = props;
+ const [state, setState] = useState({ checked: defaultChecked, defaultChecked });
+ if (state.defaultChecked !== defaultChecked) {
+ setState({ checked: defaultChecked, defaultChecked });
+ }
+ const { checked } = state;
- const handleChange = () => {
- setChecked(!checked);
- onChange?.(!checked);
+ const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
+ const nextChecked = event.target.checked;
+ setState({ checked: nextChecked, defaultChecked });
+ onChange?.(nextChecked);
};
- useEffect(() => {
- setChecked(defaultChecked);
- }, [defaultChecked]);
-
return (
<div className="univer-h-4">
<label className="univer-relative univer-inline-block univer-h-4 univer-w-7">
<input
- className="univer-size-0 univer-opacity-0"
+ {...inputProps}
+ className="univer-peer univer-sr-only"
type="checkbox"
checked={checked}
onChange={handleChange}
@@ -48,6 +51,7 @@ const Switch = (props: ISwitchProps) => {
className={clsx(`
univer-absolute univer-inset-0 univer-cursor-pointer univer-rounded-2xl univer-transition-colors
univer-duration-200
+ peer-focus:univer-ring-2 peer-focus:univer-ring-primary-600 peer-focus:univer-ring-offset-2
`, {
'univer-bg-primary-600': checked,
'univer-bg-gray-200 dark:!univer-bg-gray-600': !checked,
diff --git a/packages/design/src/components/switch/__tests__/Switch.spec.tsx b/packages/design/src/components/switch/__tests__/Switch.spec.tsx
new file mode 100644
index 0000000000..a3c6d2b434
--- /dev/null
+++ b/packages/design/src/components/switch/__tests__/Switch.spec.tsx
@@ -0,0 +1,49 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { Switch } from '../Switch';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(cleanup);
+
+describe('Switch', () => {
+ it('exposes its label and supports changing the setting', () => {
+ const onChange = vi.fn();
+ const { rerender } = render(<Switch aria-label="Show grid" defaultChecked onChange={onChange} />);
+ const checkbox = screen.getByRole('checkbox', { name: 'Show grid' });
+ checkbox.focus();
+ expect(checkbox).toHaveFocus();
+ expect(checkbox).toBeChecked();
+ fireEvent.click(checkbox);
+ expect(checkbox).not.toBeChecked();
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(false);
+ rerender(<Switch aria-label="Show grid" defaultChecked={false} onChange={onChange} />);
+ rerender(<Switch aria-label="Show grid" defaultChecked onChange={onChange} />);
+ expect(checkbox).toBeChecked();
+ });
+
+ it('associates the visible label with the setting', () => {
+ render(
+ <>
+ <span id="grid-label">Show grid</span>
+ <Switch aria-labelledby="grid-label" />
+ </>
+ );
+ expect(screen.getByRole('checkbox', { name: 'Show grid' })).not.toBeChecked();
+ });
+});
diff --git a/packages/design/src/components/switch/__tests__/index.spec.tsx b/packages/design/src/components/switch/__tests__/index.spec.tsx
deleted file mode 100644
index b4a761078f..0000000000
--- a/packages/design/src/components/switch/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { cleanup, render } from '@testing-library/react';
-import { afterEach, describe, expect, it } from 'vitest';
-import { Switch } from '../Switch';
-
-afterEach(cleanup);
-
-describe('Switch', () => {
- it('renders the checked', () => {
- const { container } = render(<Switch defaultChecked />);
-
- const checkboxElement = container.querySelector('[type="checkbox"]')! as HTMLInputElement;
-
- expect(checkboxElement.checked).toBeTruthy();
- });
-
- it('change the checked', () => {
- const { container } = render(<Switch defaultChecked />);
-
- const checkboxElement = container.querySelector('[type="checkbox"]')! as HTMLInputElement;
-
- checkboxElement.click();
-
- expect(checkboxElement.checked).toBeFalsy();
- });
-});
diff --git a/packages/design/src/locale/ar-SA.ts b/packages/design/src/locale/ar-SA.ts
index cf0fee670d..23d19625d8 100644
--- a/packages/design/src/locale/ar-SA.ts
+++ b/packages/design/src/locale/ar-SA.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'مسح الإدخال',
closeBadge: 'إغلاق الشارة',
close: 'إغلاق',
menu: 'القائمة',
diff --git a/packages/design/src/locale/ca-ES.ts b/packages/design/src/locale/ca-ES.ts
index 837de71bd2..5112c40d48 100644
--- a/packages/design/src/locale/ca-ES.ts
+++ b/packages/design/src/locale/ca-ES.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Esborra l’entrada',
closeBadge: 'Tanca la insígnia',
close: 'Tanca',
menu: 'Menú',
diff --git a/packages/design/src/locale/de-DE.ts b/packages/design/src/locale/de-DE.ts
index 131b71315d..cacd20c94a 100644
--- a/packages/design/src/locale/de-DE.ts
+++ b/packages/design/src/locale/de-DE.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Eingabe löschen',
closeBadge: 'Badge schließen',
close: 'Schließen',
menu: 'Menü',
diff --git a/packages/design/src/locale/en-US.ts b/packages/design/src/locale/en-US.ts
index 2c5b1d1d81..d406dbed42 100644
--- a/packages/design/src/locale/en-US.ts
+++ b/packages/design/src/locale/en-US.ts
@@ -17,6 +17,7 @@
const locale = {
design: {
Accessibility: {
+ clearInput: 'Clear input',
closeBadge: 'Close badge',
close: 'Close',
menu: 'Menu',
diff --git a/packages/design/src/locale/es-ES.ts b/packages/design/src/locale/es-ES.ts
index 8a48bd0a12..d86666af01 100644
--- a/packages/design/src/locale/es-ES.ts
+++ b/packages/design/src/locale/es-ES.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Borrar entrada',
closeBadge: 'Cerrar insignia',
close: 'Cerrar',
menu: 'Menú',
diff --git a/packages/design/src/locale/fa-IR.ts b/packages/design/src/locale/fa-IR.ts
index 9737314f95..cfb9a14e79 100644
--- a/packages/design/src/locale/fa-IR.ts
+++ b/packages/design/src/locale/fa-IR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'پاک کردن ورودی',
closeBadge: 'بستن نشان',
close: 'بستن',
menu: 'منو',
diff --git a/packages/design/src/locale/fr-FR.ts b/packages/design/src/locale/fr-FR.ts
index 486b746e6f..d697fd6462 100644
--- a/packages/design/src/locale/fr-FR.ts
+++ b/packages/design/src/locale/fr-FR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Effacer la saisie',
closeBadge: 'Fermer le badge',
close: 'Fermer',
menu: 'Menu',
diff --git a/packages/design/src/locale/id-ID.ts b/packages/design/src/locale/id-ID.ts
index 62817dd120..ad97b99164 100644
--- a/packages/design/src/locale/id-ID.ts
+++ b/packages/design/src/locale/id-ID.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Hapus input',
closeBadge: 'Tutup lencana',
close: 'Tutup',
menu: 'Menu',
diff --git a/packages/design/src/locale/it-IT.ts b/packages/design/src/locale/it-IT.ts
index 44df31c325..48ff629ccb 100644
--- a/packages/design/src/locale/it-IT.ts
+++ b/packages/design/src/locale/it-IT.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Cancella input',
closeBadge: 'Chiudi badge',
close: 'Chiudi',
menu: 'Menu',
diff --git a/packages/design/src/locale/ja-JP.ts b/packages/design/src/locale/ja-JP.ts
index bcf440b142..235bf94225 100644
--- a/packages/design/src/locale/ja-JP.ts
+++ b/packages/design/src/locale/ja-JP.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: '入力をクリア',
closeBadge: 'バッジを閉じる',
close: '閉じる',
menu: 'メニュー',
diff --git a/packages/design/src/locale/ko-KR.ts b/packages/design/src/locale/ko-KR.ts
index c24b4a966a..0c32127ff2 100644
--- a/packages/design/src/locale/ko-KR.ts
+++ b/packages/design/src/locale/ko-KR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: '입력 지우기',
closeBadge: '배지 닫기',
close: '닫기',
menu: '메뉴',
diff --git a/packages/design/src/locale/pl-PL.ts b/packages/design/src/locale/pl-PL.ts
index 5dd369254a..4ce064b4be 100644
--- a/packages/design/src/locale/pl-PL.ts
+++ b/packages/design/src/locale/pl-PL.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Wyczyść pole',
closeBadge: 'Zamknij plakietkę',
close: 'Zamknij',
menu: 'Menu',
diff --git a/packages/design/src/locale/pt-BR.ts b/packages/design/src/locale/pt-BR.ts
index 4dce995546..4e238ac346 100644
--- a/packages/design/src/locale/pt-BR.ts
+++ b/packages/design/src/locale/pt-BR.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Limpar entrada',
closeBadge: 'Fechar selo',
close: 'Fechar',
menu: 'Menu',
diff --git a/packages/design/src/locale/ru-RU.ts b/packages/design/src/locale/ru-RU.ts
index 885998f1da..c12a42daf0 100644
--- a/packages/design/src/locale/ru-RU.ts
+++ b/packages/design/src/locale/ru-RU.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Очистить поле',
closeBadge: 'Закрыть метку',
close: 'Закрыть',
menu: 'Меню',
diff --git a/packages/design/src/locale/sk-SK.ts b/packages/design/src/locale/sk-SK.ts
index f99bf92b56..c2d739e9a3 100644
--- a/packages/design/src/locale/sk-SK.ts
+++ b/packages/design/src/locale/sk-SK.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Vymazať vstup',
closeBadge: 'Zavrieť odznak',
close: 'Zavrieť',
menu: 'Ponuka',
diff --git a/packages/design/src/locale/vi-VN.ts b/packages/design/src/locale/vi-VN.ts
index f68c799773..fc8880908e 100644
--- a/packages/design/src/locale/vi-VN.ts
+++ b/packages/design/src/locale/vi-VN.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: 'Xóa nội dung nhập',
closeBadge: 'Đóng huy hiệu',
close: 'Đóng',
menu: 'Trình đơn',
diff --git a/packages/design/src/locale/zh-CN.ts b/packages/design/src/locale/zh-CN.ts
index d139720015..f3daa132d0 100644
--- a/packages/design/src/locale/zh-CN.ts
+++ b/packages/design/src/locale/zh-CN.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: '清空输入',
closeBadge: '关闭徽章',
close: '关闭',
menu: '菜单',
diff --git a/packages/design/src/locale/zh-HK.ts b/packages/design/src/locale/zh-HK.ts
index f01f534788..7cf858ca2b 100644
--- a/packages/design/src/locale/zh-HK.ts
+++ b/packages/design/src/locale/zh-HK.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: '清空輸入',
closeBadge: '關閉徽章',
close: '關閉',
menu: '選單',
diff --git a/packages/design/src/locale/zh-TW.ts b/packages/design/src/locale/zh-TW.ts
index f01f534788..7cf858ca2b 100644
--- a/packages/design/src/locale/zh-TW.ts
+++ b/packages/design/src/locale/zh-TW.ts
@@ -19,6 +19,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
design: {
Accessibility: {
+ clearInput: '清空輸入',
closeBadge: '關閉徽章',
close: '關閉',
menu: '選單',
diff --git a/packages/sheets-crosshair-highlight/src/views/mobile/MobileCrosshairHighlightPanel.tsx b/packages/sheets-crosshair-highlight/src/views/mobile/MobileCrosshairHighlightPanel.tsx
index d5ee100d5f..ae1c6e244d 100644
--- a/packages/sheets-crosshair-highlight/src/views/mobile/MobileCrosshairHighlightPanel.tsx
+++ b/packages/sheets-crosshair-highlight/src/views/mobile/MobileCrosshairHighlightPanel.tsx
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import type { LocaleKey } from '../../locale/types';
import { ICommandService, LocaleService, ThemeService } from '@univerjs/core';
import { clsx, resetButtonClassName, Switch } from '@univerjs/design';
import { useDependency, useObservable } from '@univerjs/ui';
import { map } from 'rxjs';
+import type { LocaleKey } from '../../locale/types';
import {
DisableCrosshairHighlightOperation,
EnableCrosshairHighlightOperation,
@@ -56,6 +56,7 @@ export function MobileCrosshairHighlightPanel() {
{localeService.t<LocaleKey>('sheets-crosshair-highlight.button.tooltip')}
</span>
<Switch
+ aria-label={localeService.t<LocaleKey>('sheets-crosshair-highlight.button.tooltip')}
defaultChecked={enabled}
onChange={(checked) => {
const operation = checked
diff --git a/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsx b/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsx
index cc84a04eba..4c6a74f6ed 100644
--- a/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsx
+++ b/packages/sheets-filter-ui/src/views/components/SheetsFilterSyncSwitch.tsx
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { LocaleKey } from '../../locale/types';
import { LocaleService } from '@univerjs/core';
import { MessageType, Switch, Tooltip } from '@univerjs/design';
import { InfoIcon } from '@univerjs/icons';
import { SheetsFilterSyncController } from '@univerjs/sheets-filter';
import { IMessageService, useDependency, useObservable } from '@univerjs/ui';
+import type { LocaleKey } from '../../locale/types';
export function FilterSyncSwitch() {
const sheetsFilterSyncController = useDependency(SheetsFilterSyncController);
@@ -28,7 +28,9 @@ export function FilterSyncSwitch() {
const messageService = useDependency(IMessageService);
const enabled = useObservable(sheetsFilterSyncController.enabled$, undefined, true);
- if (!visible) return null;
+ if (!visible) {
+ return null;
+ }
return (
<div
@@ -49,6 +51,7 @@ export function FilterSyncSwitch() {
</Tooltip>
</div>
<Switch
+ aria-label={localeService.t<LocaleKey>('sheets-filter-ui.sync.title')}
defaultChecked={enabled}
onChange={(checked) => {
const message = checked
diff --git a/packages/sheets-filter-ui/src/views/mobile/MobileSheetsFilterPanel.tsx b/packages/sheets-filter-ui/src/views/mobile/MobileSheetsFilterPanel.tsx
index 7002ba409f..25298eeac1 100644
--- a/packages/sheets-filter-ui/src/views/mobile/MobileSheetsFilterPanel.tsx
+++ b/packages/sheets-filter-ui/src/views/mobile/MobileSheetsFilterPanel.tsx
@@ -15,12 +15,6 @@
*/
import type { MobileDrawerSnap } from '@univerjs/ui';
-import type { LocaleKey } from '../../locale/types';
-import type {
- ByColorsModel,
- ByConditionsModel,
- ByValuesModel,
-} from '../../services/sheets-filter-panel.service';
import { ICommandService, IContextService, LocaleService, Tools } from '@univerjs/core';
import {
Button,
@@ -40,6 +34,12 @@ import {
} from '@univerjs/ui';
import { useRef, useState } from 'react';
import { map, of } from 'rxjs';
+import type { LocaleKey } from '../../locale/types';
+import type {
+ ByColorsModel,
+ ByConditionsModel,
+ ByValuesModel,
+} from '../../services/sheets-filter-panel.service';
import {
ChangeFilterByOperation,
CloseFilterPanelOperation,
@@ -96,6 +96,7 @@ function MobileFilterSyncSwitch() {
</div>
</div>
<Switch
+ aria-label={localeService.t<LocaleKey>('sheets-filter-ui.sync.title')}
defaultChecked={enabled}
onChange={(checked) => {
filterSyncController.setEnabled(checked);
diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx
index a7f7c017ea..e37904d0dd 100644
--- a/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx
+++ b/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx
@@ -16,10 +16,10 @@
import type { Workbook } from '@univerjs/core';
import type { ICollaborator, UnitAction } from '@univerjs/protocol';
-import type { LocaleKey } from '../../locale/types';
import {
IAuthzIoService,
ICommandService,
+ ILogService,
IPermissionService,
IUniverInstanceService,
LocaleService,
@@ -34,6 +34,7 @@ import {
} from '@univerjs/sheets';
import { IDialogService, useDependency } from '@univerjs/ui';
import { useEffect, useState } from 'react';
+import type { LocaleKey } from '../../locale/types';
import {
defaultWorksheetUnitActionList,
subUnitPermissionTypeMap,
@@ -54,6 +55,7 @@ export interface ISheetPermissionDialogProps {
export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheetPermissionDialogProps = {}) => {
const localeService = useDependency(LocaleService);
+ const logService = useDependency(ILogService);
const univerInstanceService = useDependency(IUniverInstanceService);
const authzIoService = useDependency(IAuthzIoService);
const worksheetProtectionPointRuleModel = useDependency(WorksheetProtectionPointModel);
@@ -84,19 +86,19 @@ export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheet
useEffect(() => {
let cancelled = false;
- void authzIoService.listCollaborators({
+ authzIoService.listCollaborators({
objectID: unitId,
unitID: unitId,
}).then((collaborators) => {
if (!cancelled) {
setCollaborators(collaborators);
}
- });
+ }).catch((error) => logService.error(error));
return () => {
cancelled = true;
};
- }, [authzIoService, unitId]);
+ }, [authzIoService, logService, unitId]);
useEffect(() => {
let cancelled = false;
@@ -106,7 +108,7 @@ export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheet
if (worksheetPointRule) {
setLoading(true);
- void authzIoService.list({
+ authzIoService.list({
unitID: unitId,
objectIDs: [worksheetPointRule.permissionId],
actions: defaultWorksheetUnitActionList,
@@ -128,7 +130,7 @@ export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheet
loadingTimer = setTimeout(() => {
setLoading(false);
}, 100);
- });
+ }).catch((error) => logService.error(error));
}
return () => {
@@ -137,7 +139,7 @@ export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheet
clearTimeout(loadingTimer);
}
};
- }, [authzIoService, localeService, subUnitId, unitId, worksheetProtectionPointRuleModel]);
+ }, [authzIoService, localeService, logService, subUnitId, unitId, worksheetProtectionPointRuleModel]);
const handleChangeActionPermission = async () => {
const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -219,6 +221,7 @@ export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheet
>
<span className="univer-text-sm">{text}</span>
<Switch
+ aria-label={text}
defaultChecked={allowed}
onChange={() => {
setPermissionMap({