Skip to content

Commit

Permalink
fix(ui-sourcecodeeditor): link label to input field programmatically
Browse files Browse the repository at this point in the history
  • Loading branch information
ToMESSKa committed Feb 11, 2025
1 parent 98adf34 commit b092b45
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ class LanguageExamples extends React.Component {
<Flex.Item padding="0 0 0 large" shouldGrow shouldShrink>
<FormField label="SourceCodeEditor with syntax highlight">
<SourceCodeEditor
label={`${this.state.currentLanguage} code editor`}
label={`${this.state.currentLanguage} SourceCodeEditor with syntax highlight`}
language={this.state.currentLanguage}
value={this.state.currentValue}
onChange={(value) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,19 @@ describe('<SourceCodeEditor />', () => {
expect(activeLine[1]).toHaveStyle({ color: '#0000ff' })
expect(activeLine[2]).toHaveStyle({ color: '#116644' })
})

it('should link editor element to label using aria-labelledby attribute', async () => {
const { container } = render(
<SourceCodeEditor
label="test"
language="jsx"
defaultValue="const a = 2;"
/>
)
const editorElement = container.querySelector('[role="textbox"]')
const labelId = container.querySelector('[class$="-label"]')?.id

expect(editorElement).toHaveAttribute('aria-labelledby', labelId)
})
})
})
12 changes: 11 additions & 1 deletion packages/ui-source-code-editor/src/SourceCodeEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ class SourceCodeEditor extends Component<SourceCodeEditorProps> {
if (indentOnLoad) {
this.indentAll()
}
this.assignAriaLabel()
}

componentWillUnmount() {
Expand Down Expand Up @@ -644,6 +645,15 @@ class SourceCodeEditor extends Component<SourceCodeEditorProps> {
}
}

assignAriaLabel = () => {
if (this._containerRef) {
const editorDiv = this._containerRef.querySelector('[role="textbox"]')
if (editorDiv) {
editorDiv.setAttribute('aria-labelledby', `${this._id}`)
}
}
}

render() {
const { label, styles, ...restProps } = this.props

Expand All @@ -655,7 +665,7 @@ class SourceCodeEditor extends Component<SourceCodeEditorProps> {
omitProps(restProps, SourceCodeEditor.allowedProps)
)}
>
<label css={styles?.label} htmlFor={this._id}>
<label css={styles?.label} id={this._id}>
<ScreenReaderContent>{label}</ScreenReaderContent>
<div
ref={this.handleContainerRef}
Expand Down

0 comments on commit b092b45

Please sign in to comment.