diff --git a/.changeset/techdocs-coats-obey.md b/.changeset/techdocs-coats-obey.md new file mode 100644 index 0000000000..0c2c2b5ac2 --- /dev/null +++ b/.changeset/techdocs-coats-obey.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-techdocs': patch +--- + +Fix permalink scrolling for anchors where the id starts with a number. diff --git a/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.test.ts b/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.test.ts index b06762399b..896f909be4 100644 --- a/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.test.ts +++ b/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.test.ts @@ -35,11 +35,25 @@ describe('scrollIntoAnchor', () => { it('scroll to the hash anchor element', async () => { const scrollIntoView = jest.fn(); dom.querySelector.mockReturnValue({ scrollIntoView }); - const hash = '#hash'; - window.location.hash = hash; + window.location.hash = '#hash'; transformer(dom as unknown as Element); jest.advanceTimersByTime(200); - expect(dom.querySelector).toHaveBeenCalledWith(`#${hash.slice(1)}`); + expect(dom.querySelector).toHaveBeenCalledWith( + expect.stringMatching('[id="hash"]'), + ); + expect(scrollIntoView).toHaveBeenCalledWith(); + window.location.hash = ''; + }); + + it('works for anchor starting with number', async () => { + const scrollIntoView = jest.fn(); + dom.querySelector.mockReturnValue({ scrollIntoView }); + window.location.hash = '#1-hash'; + transformer(dom as unknown as Element); + jest.advanceTimersByTime(200); + expect(dom.querySelector).toHaveBeenCalledWith( + expect.stringMatching('[id="1-hash"]'), + ); expect(scrollIntoView).toHaveBeenCalledWith(); window.location.hash = ''; }); diff --git a/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.ts b/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.ts index 0fa977865e..7ba02bcdfc 100644 --- a/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.ts +++ b/plugins/techdocs/src/reader/transformers/scrollIntoAnchor.ts @@ -22,7 +22,8 @@ export const scrollIntoAnchor = (): Transformer => { // Scroll to the desired anchor on initial navigation if (window.location.hash) { const hash = window.location.hash.slice(1); - dom?.querySelector(`#${hash}`)?.scrollIntoView(); + // fix invalid selector error for anchor starting with number + dom?.querySelector(`[id="${hash}"]`)?.scrollIntoView(); } }, 200); return dom;