Skip to content

Commit b092b45

Browse files
committed
fix(ui-sourcecodeeditor): link label to input field programmatically
1 parent 98adf34 commit b092b45

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

packages/ui-source-code-editor/src/SourceCodeEditor/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ class LanguageExamples extends React.Component {
231231
<Flex.Item padding="0 0 0 large" shouldGrow shouldShrink>
232232
<FormField label="SourceCodeEditor with syntax highlight">
233233
<SourceCodeEditor
234-
label={`${this.state.currentLanguage} code editor`}
234+
label={`${this.state.currentLanguage} SourceCodeEditor with syntax highlight`}
235235
language={this.state.currentLanguage}
236236
value={this.state.currentValue}
237237
onChange={(value) => {

packages/ui-source-code-editor/src/SourceCodeEditor/__new-tests__/SourceCodeEditor.test.tsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,19 @@ describe('<SourceCodeEditor />', () => {
4444
expect(activeLine[1]).toHaveStyle({ color: '#0000ff' })
4545
expect(activeLine[2]).toHaveStyle({ color: '#116644' })
4646
})
47+
48+
it('should link editor element to label using aria-labelledby attribute', async () => {
49+
const { container } = render(
50+
<SourceCodeEditor
51+
label="test"
52+
language="jsx"
53+
defaultValue="const a = 2;"
54+
/>
55+
)
56+
const editorElement = container.querySelector('[role="textbox"]')
57+
const labelId = container.querySelector('[class$="-label"]')?.id
58+
59+
expect(editorElement).toHaveAttribute('aria-labelledby', labelId)
60+
})
4761
})
4862
})

packages/ui-source-code-editor/src/SourceCodeEditor/index.tsx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ class SourceCodeEditor extends Component<SourceCodeEditorProps> {
302302
if (indentOnLoad) {
303303
this.indentAll()
304304
}
305+
this.assignAriaLabel()
305306
}
306307

307308
componentWillUnmount() {
@@ -644,6 +645,15 @@ class SourceCodeEditor extends Component<SourceCodeEditorProps> {
644645
}
645646
}
646647

648+
assignAriaLabel = () => {
649+
if (this._containerRef) {
650+
const editorDiv = this._containerRef.querySelector('[role="textbox"]')
651+
if (editorDiv) {
652+
editorDiv.setAttribute('aria-labelledby', `${this._id}`)
653+
}
654+
}
655+
}
656+
647657
render() {
648658
const { label, styles, ...restProps } = this.props
649659

@@ -655,7 +665,7 @@ class SourceCodeEditor extends Component<SourceCodeEditorProps> {
655665
omitProps(restProps, SourceCodeEditor.allowedProps)
656666
)}
657667
>
658-
<label css={styles?.label} htmlFor={this._id}>
668+
<label css={styles?.label} id={this._id}>
659669
<ScreenReaderContent>{label}</ScreenReaderContent>
660670
<div
661671
ref={this.handleContainerRef}

0 commit comments

Comments
 (0)