@teleporthq/teleport-project-generator-next 0.45.18 → 0.45.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/__tests__/nav-active-links-locale.test.ts +279 -0
  2. package/__tests__/page-transition-end2end.test.ts +3 -3
  3. package/__tests__/page-transition-language-switch.test.ts +273 -0
  4. package/dist/cjs/nav-active-link/nav-active-link-component.d.ts +1 -1
  5. package/dist/cjs/nav-active-link/nav-active-link-component.d.ts.map +1 -1
  6. package/dist/cjs/nav-active-link/nav-active-link-component.js +12 -4
  7. package/dist/cjs/nav-active-link/nav-active-link-component.js.map +1 -1
  8. package/dist/cjs/page-transition/page-transition-component.d.ts.map +1 -1
  9. package/dist/cjs/page-transition/page-transition-component.js +1 -1
  10. package/dist/cjs/page-transition/page-transition-component.js.map +1 -1
  11. package/dist/cjs/project-template.d.ts.map +1 -1
  12. package/dist/cjs/project-template.js +1 -1
  13. package/dist/cjs/project-template.js.map +1 -1
  14. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  15. package/dist/esm/nav-active-link/nav-active-link-component.d.ts +1 -1
  16. package/dist/esm/nav-active-link/nav-active-link-component.d.ts.map +1 -1
  17. package/dist/esm/nav-active-link/nav-active-link-component.js +12 -4
  18. package/dist/esm/nav-active-link/nav-active-link-component.js.map +1 -1
  19. package/dist/esm/page-transition/page-transition-component.d.ts.map +1 -1
  20. package/dist/esm/page-transition/page-transition-component.js +1 -1
  21. package/dist/esm/page-transition/page-transition-component.js.map +1 -1
  22. package/dist/esm/project-template.d.ts.map +1 -1
  23. package/dist/esm/project-template.js +1 -1
  24. package/dist/esm/project-template.js.map +1 -1
  25. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  26. package/package.json +14 -14
  27. package/src/nav-active-link/nav-active-link-component.ts +68 -5
  28. package/src/page-transition/page-transition-component.ts +19 -5
  29. package/src/project-template.ts +1 -2
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The generated `components/nav-active-links.js` marks the menu link of the page
3
+ * the visitor is on. On a site with several languages the rendered links carry
4
+ * the language prefix (`/es/classes`) while `router.asPath` never does
5
+ * (`/classes`). Comparing the two as plain strings marked NO menu link on any
6
+ * translated page and marked the default language's link in the language
7
+ * switcher as the current page on every one of them.
8
+ */
9
+
10
+ import { moduleBody } from './_helpers/load-client-runtime'
11
+ import { NAV_ACTIVE_LINK_COMPONENT_SOURCE } from '../src/nav-active-link/nav-active-link-component'
12
+
13
+ interface FakeAnchor {
14
+ label: string
15
+ getAttribute: (name: string) => string | null
16
+ setAttribute: (name: string, value: string) => void
17
+ removeAttribute: (name: string) => void
18
+ querySelectorAll: () => FakeAnchor[]
19
+ classList: { add: (name: string) => void; remove: (name: string) => void }
20
+ isMarked: () => boolean
21
+ }
22
+
23
+ const link = (label: string, href: string, markedBefore = false): FakeAnchor => {
24
+ const attributes = new Map<string, string>([['href', href]])
25
+ const classes = new Set<string>()
26
+ if (markedBefore) {
27
+ attributes.set('aria-current', 'page')
28
+ classes.add('active')
29
+ }
30
+ return {
31
+ label,
32
+ getAttribute: (name) => attributes.get(name) ?? null,
33
+ setAttribute: (name, value) => {
34
+ attributes.set(name, value)
35
+ },
36
+ removeAttribute: (name) => {
37
+ attributes.delete(name)
38
+ },
39
+ querySelectorAll: () => [],
40
+ classList: { add: (name) => classes.add(name), remove: (name) => classes.delete(name) },
41
+ isMarked: () => attributes.get('aria-current') === 'page' && classes.has('active'),
42
+ }
43
+ }
44
+
45
+ interface FakeRoute {
46
+ asPath: string
47
+ locale?: string
48
+ locales?: string[]
49
+ defaultLocale?: string
50
+ }
51
+
52
+ const markedLinks = (route: FakeRoute, links: FakeAnchor[]): string[] => {
53
+ const navigation = { querySelectorAll: () => links }
54
+ const documentFake = { querySelectorAll: () => [navigation] }
55
+ const router = { ...route, events: { on: (): void => undefined, off: (): void => undefined } }
56
+ const runEffectAtOnce = (effect: () => void) => {
57
+ effect()
58
+ }
59
+
60
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
61
+ const NavActiveLinks = new Function(
62
+ 'useEffect',
63
+ 'useRouter',
64
+ 'document',
65
+ `${moduleBody(
66
+ NAV_ACTIVE_LINK_COMPONENT_SOURCE.replace(/^export default .*$/m, '')
67
+ )}\nreturn NavActiveLinks`
68
+ )(runEffectAtOnce, () => router, documentFake) as () => null
69
+ NavActiveLinks()
70
+
71
+ return links.filter((anchor) => anchor.isMarked()).map((anchor) => anchor.label)
72
+ }
73
+
74
+ /**
75
+ * The same component with the browser's change watcher: what it does when elements are added to
76
+ * the page after it marked the links.
77
+ */
78
+ const mountOnAChangingPage = (route: FakeRoute, firstLinks: FakeAnchor[]) => {
79
+ let links = firstLinks
80
+ let passes = 0
81
+ let onChange: (records: Array<{ addedNodes: unknown[] }>) => void = () => undefined
82
+ let nextFrame: (() => void) | null = null
83
+ const navigation = { querySelectorAll: () => links }
84
+ const documentFake = {
85
+ body: {},
86
+ querySelectorAll: () => {
87
+ passes += 1
88
+ return [navigation]
89
+ },
90
+ }
91
+ const router = { ...route, events: { on: (): void => undefined, off: (): void => undefined } }
92
+ class FakeObserver {
93
+ constructor(callback: typeof onChange) {
94
+ onChange = callback
95
+ }
96
+ observe(): void {
97
+ return undefined
98
+ }
99
+ disconnect(): void {
100
+ return undefined
101
+ }
102
+ }
103
+
104
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
105
+ const NavActiveLinks = new Function(
106
+ 'useEffect',
107
+ 'useRouter',
108
+ 'document',
109
+ 'MutationObserver',
110
+ 'requestAnimationFrame',
111
+ 'cancelAnimationFrame',
112
+ `${moduleBody(
113
+ NAV_ACTIVE_LINK_COMPONENT_SOURCE.replace(/^export default .*$/m, '')
114
+ )}\nreturn NavActiveLinks`
115
+ )(
116
+ (effect: () => void) => {
117
+ effect()
118
+ },
119
+ () => router,
120
+ documentFake,
121
+ FakeObserver,
122
+ (callback: () => void) => {
123
+ nextFrame = callback
124
+ return 1
125
+ },
126
+ (): void => undefined
127
+ ) as () => null
128
+ NavActiveLinks()
129
+
130
+ return {
131
+ /** The page puts these elements in; the next frame runs. */
132
+ add: (added: unknown[], linksAfter: FakeAnchor[] = links) => {
133
+ links = linksAfter
134
+ onChange([{ addedNodes: added }])
135
+ const frame = nextFrame
136
+ nextFrame = null
137
+ if (frame) {
138
+ frame()
139
+ }
140
+ },
141
+ marked: () => links.filter((anchor) => anchor.isMarked()).map((anchor) => anchor.label),
142
+ passes: () => passes,
143
+ }
144
+ }
145
+
146
+ const asAddedElement = (anchor: FakeAnchor) => ({ ...anchor, nodeType: 1, tagName: 'A' })
147
+ const addedBlock = (holdsALink: boolean) => ({
148
+ nodeType: 1,
149
+ tagName: 'DIV',
150
+ querySelector: () => (holdsALink ? {} : null),
151
+ })
152
+
153
+ const TWO_LANGUAGES = { locales: ['en', 'es'], defaultLocale: 'en' }
154
+
155
+ describe('generated nav-active-links on a site with several languages', () => {
156
+ it('marks the page link on a page in the default language', () => {
157
+ const marked = markedLinks({ asPath: '/classes', locale: 'en', ...TWO_LANGUAGES }, [
158
+ link('Home', '/'),
159
+ link('Classes', '/classes'),
160
+ link('Pricing', '/pricing'),
161
+ link('switch to en', '/classes'),
162
+ link('switch to es', '/es/classes'),
163
+ ])
164
+
165
+ expect(marked).toEqual(['Classes', 'switch to en'])
166
+ })
167
+
168
+ it('marks the page link on a translated page, and never the other language', () => {
169
+ const marked = markedLinks({ asPath: '/classes', locale: 'es', ...TWO_LANGUAGES }, [
170
+ link('Inicio', '/es'),
171
+ link('Clases', '/es/classes'),
172
+ link('Precios', '/es/pricing'),
173
+ link('switch to en', '/classes'),
174
+ link('switch to es', '/es/classes'),
175
+ ])
176
+
177
+ expect(marked).toEqual(['Clases', 'switch to es'])
178
+ })
179
+
180
+ it('marks the home link on a translated home page', () => {
181
+ const marked = markedLinks({ asPath: '/', locale: 'es', ...TWO_LANGUAGES }, [
182
+ link('Inicio', '/es'),
183
+ link('Clases', '/es/classes'),
184
+ link('switch to en', '/'),
185
+ link('switch to es', '/es'),
186
+ ])
187
+
188
+ expect(marked).toEqual(['Inicio', 'switch to es'])
189
+ })
190
+
191
+ it('removes the mark a link kept from the language the visitor just left', () => {
192
+ const marked = markedLinks({ asPath: '/', locale: 'es', ...TWO_LANGUAGES }, [
193
+ link('switch to en', '/', true),
194
+ link('switch to es', '/es'),
195
+ ])
196
+
197
+ expect(marked).toEqual(['switch to es'])
198
+ })
199
+
200
+ it('treats a link written with the default language prefix as that language', () => {
201
+ const marked = markedLinks({ asPath: '/classes', locale: 'en', ...TWO_LANGUAGES }, [
202
+ link('Classes', '/en/classes'),
203
+ link('Clases', '/es/classes'),
204
+ ])
205
+
206
+ expect(marked).toEqual(['Classes'])
207
+ })
208
+
209
+ it('leaves query strings, hashes and trailing slashes out of the comparison', () => {
210
+ const marked = markedLinks({ asPath: '/classes?level=1#top', locale: 'es', ...TWO_LANGUAGES }, [
211
+ link('Clases', '/es/classes/'),
212
+ link('Precios', '/es/pricing'),
213
+ ])
214
+
215
+ expect(marked).toEqual(['Clases'])
216
+ })
217
+ })
218
+
219
+ describe('generated nav-active-links on a site with one language', () => {
220
+ it('marks the page link as before', () => {
221
+ const marked = markedLinks({ asPath: '/classes' }, [
222
+ link('Home', '/'),
223
+ link('Classes', '/classes'),
224
+ link('External', 'https://example.com/classes'),
225
+ link('Anchor', '#classes'),
226
+ ])
227
+
228
+ expect(marked).toEqual(['Classes'])
229
+ })
230
+
231
+ it('does not read a page address as a language', () => {
232
+ const marked = markedLinks({ asPath: '/es/menu' }, [
233
+ link('Menu', '/es/menu'),
234
+ link('Other', '/menu'),
235
+ ])
236
+
237
+ expect(marked).toEqual(['Menu'])
238
+ })
239
+ })
240
+
241
+ describe('generated nav-active-links on a page that changes after it loaded', () => {
242
+ const spanishHome = { asPath: '/', locale: 'es', locales: ['en', 'es'], defaultLocale: 'en' }
243
+
244
+ it('marks a menu the page builds again, as a page does when the language is switched', () => {
245
+ const page = mountOnAChangingPage(spanishHome, [
246
+ link('Inicio', '/es'),
247
+ link('Clases', '/es/classes'),
248
+ ])
249
+ expect(page.marked()).toEqual(['Inicio'])
250
+
251
+ const rebuilt = [
252
+ link('Inicio', '/es'),
253
+ link('Clases', '/es/classes'),
254
+ link('switch to es', '/es'),
255
+ ]
256
+ page.add([addedBlock(true)], rebuilt)
257
+
258
+ expect(page.marked()).toEqual(['Inicio', 'switch to es'])
259
+ })
260
+
261
+ it('marks a link added on its own', () => {
262
+ const page = mountOnAChangingPage(spanishHome, [link('Clases', '/es/classes')])
263
+ const home = link('Inicio', '/es')
264
+
265
+ page.add([asAddedElement(home)], [link('Clases', '/es/classes'), home])
266
+
267
+ expect(page.marked()).toEqual(['Inicio'])
268
+ })
269
+
270
+ it('does not look at the links again for changes that add none', () => {
271
+ const page = mountOnAChangingPage(spanishHome, [link('Inicio', '/es')])
272
+ const passesAfterLoad = page.passes()
273
+
274
+ page.add([{ nodeType: 3 }])
275
+ page.add([addedBlock(false)])
276
+
277
+ expect(page.passes()).toBe(passesAfterLoad)
278
+ })
279
+ })
@@ -91,7 +91,7 @@ describe('Next generator page transition', () => {
91
91
 
92
92
  expect(wrapper).not.toContain('useReducedMotion')
93
93
  expect(wrapper).toContain('if (!variants) {\n return children\n }')
94
- expect(wrapper).toContain('const skip = prefersLessMotion() || isSkippedRoute(routeKeyOf(url))')
94
+ expect(wrapper).toContain('const skip = prefersLessMotion() || isSkippedRoute(arrivingKey)')
95
95
  })
96
96
 
97
97
  it('ignores a transition it does not know and a preset of none', async () => {
@@ -340,7 +340,7 @@ describe('Next generator per-page skip', () => {
340
340
  )
341
341
  const wrapper = findFile(output, 'components', 'tq-page-transition')?.content || ''
342
342
  expect(wrapper).toContain('const SKIP_ROUTES = ["/checkout","/products/[slug]"]')
343
- expect(wrapper).toContain('const skip = prefersLessMotion() || isSkippedRoute(routeKeyOf(url))')
343
+ expect(wrapper).toContain('const skip = prefersLessMotion() || isSkippedRoute(arrivingKey)')
344
344
  expect(wrapper).not.toContain('isSkippedRoute(routeKeyRef.current)')
345
345
  })
346
346
 
@@ -872,7 +872,7 @@ describe('Next generator dissolve presets (Fade, Crossfade)', () => {
872
872
  expect(() => setLeaving(null, true)).not.toThrow()
873
873
  // back to a page that has not gone yet: it takes input again and plays at once
874
874
  expect(wrapper).toContain(
875
- ' const returning = pageIn(routeKeyOf(url))\n if (returning) {\n setLeaving(returning, false)\n readyKeyRef.current = routeKeyOf(url)\n setReadyKey(readyKeyRef.current)\n }'
875
+ ' const returning = pageIn(arrivingKey)\n if (returning) {\n setLeaving(returning, false)\n readyKeyRef.current = arrivingKey\n setReadyKey(readyKeyRef.current)\n }'
876
876
  )
877
877
  const pageIn = new Function('document', `${declarationOf(wrapper, 'pageIn')}\nreturn pageIn`)({
878
878
  querySelectorAll: (selector: string) =>
@@ -0,0 +1,273 @@
1
+ /**
2
+ * The page transition freezes the page a visitor leaves (fixed in place, at its scroll
3
+ * offset) until the next page has arrived. "Another page" was decided by comparing the
4
+ * address in the route event with the current page's key. The event carries the language
5
+ * (`/es/classes`), the key, made from `router.asPath`, never does (`/classes`), so on a
6
+ * site with several languages a language switch counted as a move to another page: the
7
+ * page was frozen, no other page ever arrived to release it, and it could not be scrolled
8
+ * again until the visitor went somewhere else.
9
+ */
10
+
11
+ import { moduleBody } from './_helpers/load-client-runtime'
12
+ import { generatePageTransitionComponentCode } from '../src/page-transition/page-transition-component'
13
+
14
+ interface RenderedElement {
15
+ type: unknown
16
+ props: Record<string, unknown>
17
+ children: unknown[]
18
+ }
19
+
20
+ interface Route {
21
+ asPath: string
22
+ locale?: string
23
+ locales?: string[]
24
+ defaultLocale?: string
25
+ }
26
+
27
+ type RouteHandler = (url: string) => void
28
+
29
+ const isElement = (value: unknown): value is RenderedElement =>
30
+ !!value && typeof value === 'object' && 'props' in value && 'children' in value
31
+
32
+ const findPage = (tree: unknown): RenderedElement | undefined => {
33
+ if (Array.isArray(tree)) {
34
+ for (const item of tree) {
35
+ const found = findPage(item)
36
+ if (found) {
37
+ return found
38
+ }
39
+ }
40
+ return undefined
41
+ }
42
+ if (!isElement(tree)) {
43
+ return undefined
44
+ }
45
+ return 'data-tq-page-transition' in tree.props ? tree : findPage(tree.children)
46
+ }
47
+
48
+ /**
49
+ * The generated `components/tq-page-transition.js` under a minimal hooks runtime: effects
50
+ * run after each render, state setters ask for another render, and the route events it
51
+ * subscribed to can be fired.
52
+ */
53
+ const mountTransition = (preset: string, firstRoute: Route) => {
54
+ const source = generatePageTransitionComponentCode({ preset, duration: 0.3, easing: 'ease-out' })
55
+ const slots: unknown[] = []
56
+ const handlers: Record<string, RouteHandler[]> = {}
57
+ const router = {
58
+ ...firstRoute,
59
+ events: {
60
+ on: (name: string, handler: RouteHandler) => {
61
+ handlers[name] = [...(handlers[name] || []), handler]
62
+ },
63
+ off: (name: string, handler: RouteHandler) => {
64
+ handlers[name] = (handlers[name] || []).filter((item) => item !== handler)
65
+ },
66
+ },
67
+ beforePopState: (): void => undefined,
68
+ }
69
+ let cursor = 0
70
+ let pendingEffects: Array<() => void> = []
71
+
72
+ const sameDeps = (a: unknown[] | undefined, b: unknown[] | undefined) =>
73
+ !!a && !!b && a.length === b.length && a.every((item, index) => Object.is(item, b[index]))
74
+ const slot = <T>(create: () => T): T => {
75
+ if (cursor >= slots.length) {
76
+ slots.push(create())
77
+ }
78
+ return slots[cursor++] as T
79
+ }
80
+
81
+ const useEffect = (effect: () => void | (() => void), deps?: unknown[]) => {
82
+ const record = slot<{ deps?: unknown[]; cleanup?: void | (() => void) }>(() => ({}))
83
+ if (!deps || !sameDeps(record.deps, deps)) {
84
+ record.deps = deps
85
+ pendingEffects.push(() => {
86
+ if (typeof record.cleanup === 'function') {
87
+ record.cleanup()
88
+ }
89
+ record.cleanup = effect()
90
+ })
91
+ }
92
+ }
93
+
94
+ const React = {
95
+ Fragment: 'fragment',
96
+ createElement: (
97
+ type: unknown,
98
+ props: Record<string, unknown> | null,
99
+ ...children: unknown[]
100
+ ) => ({
101
+ type,
102
+ props: props || {},
103
+ children,
104
+ }),
105
+ useRef: (initial: unknown) => slot(() => ({ current: initial })),
106
+ useState: (initial: unknown) => {
107
+ const state = slot(() => ({ value: initial }))
108
+ const set = (next: unknown) => {
109
+ state.value =
110
+ typeof next === 'function' ? (next as (v: unknown) => unknown)(state.value) : next
111
+ }
112
+ return [state.value, set]
113
+ },
114
+ useMemo: (create: () => unknown, deps: unknown[]) => {
115
+ const memo = slot<{ deps?: unknown[]; value?: unknown }>(() => ({}))
116
+ if (!sameDeps(memo.deps, deps)) {
117
+ memo.deps = deps
118
+ memo.value = create()
119
+ }
120
+ return memo.value
121
+ },
122
+ useCallback: (callback: unknown, deps: unknown[]) => {
123
+ const memo = slot<{ deps?: unknown[]; value?: unknown }>(() => ({}))
124
+ if (!sameDeps(memo.deps, deps)) {
125
+ memo.deps = deps
126
+ memo.value = callback
127
+ }
128
+ return memo.value
129
+ },
130
+ useEffect,
131
+ useLayoutEffect: useEffect,
132
+ }
133
+
134
+ const style = {
135
+ getPropertyValue: () => '',
136
+ getPropertyPriority: () => '',
137
+ setProperty: (): void => undefined,
138
+ removeProperty: (): void => undefined,
139
+ }
140
+ const element = { style, getAttribute: (): null => null, clientWidth: 1440, scrollHeight: 4000 }
141
+ const windowFake = {
142
+ innerWidth: 1440,
143
+ innerHeight: 900,
144
+ scrollY: 250,
145
+ matchMedia: () => ({ matches: false }),
146
+ addEventListener: (): void => undefined,
147
+ removeEventListener: (): void => undefined,
148
+ getComputedStyle: () => ({ backgroundColor: 'rgb(255, 255, 255)', overflowY: 'auto' }),
149
+ }
150
+ const documentFake = {
151
+ documentElement: element,
152
+ body: element,
153
+ images: [] as unknown[],
154
+ querySelector: (): null => null,
155
+ querySelectorAll: (): unknown[] => [],
156
+ addEventListener: (): void => undefined,
157
+ removeEventListener: (): void => undefined,
158
+ }
159
+
160
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
161
+ const Component = new Function(
162
+ 'React',
163
+ 'useRouter',
164
+ 'AnimatePresence',
165
+ 'motion',
166
+ 'usePresence',
167
+ 'window',
168
+ 'document',
169
+ 'setTimeout',
170
+ 'clearTimeout',
171
+ `${moduleBody(source.replace(/^export default .*$/m, ''))}\nreturn TqPageTransition`
172
+ )(
173
+ React,
174
+ () => router,
175
+ 'AnimatePresence',
176
+ { div: 'motion.div' },
177
+ () => [true, (): void => undefined],
178
+ windowFake,
179
+ documentFake,
180
+ () => 0,
181
+ (): void => undefined
182
+ ) as (props: { children: unknown }) => unknown
183
+
184
+ const render = () => {
185
+ cursor = 0
186
+ const tree = Component({ children: 'the page' })
187
+ const effects = pendingEffects
188
+ pendingEffects = []
189
+ effects.forEach((effect) => effect())
190
+ return tree
191
+ }
192
+ render()
193
+
194
+ return {
195
+ /** What Next announces before it changes the route. */
196
+ announce: (url: string) => (handlers.routeChangeStart || []).forEach((handler) => handler(url)),
197
+ /** The route after the change; the page as it renders then. */
198
+ arriveAt: (route: Route) => {
199
+ Object.assign(router, route)
200
+ return findPage(render())
201
+ },
202
+ page: () => findPage(render()),
203
+ }
204
+ }
205
+
206
+ const TWO_LANGUAGES = { locales: ['en', 'es'], defaultLocale: 'en' }
207
+ const isFrozen = (page: RenderedElement | undefined) =>
208
+ (page?.props.style as { position?: string } | undefined)?.position === 'fixed'
209
+
210
+ describe.each(['slide-up', 'fade'])('generated page transition (%s) and languages', (preset) => {
211
+ it('does not freeze the page when the visitor switches language', () => {
212
+ const site = mountTransition(preset, { asPath: '/classes', locale: 'en', ...TWO_LANGUAGES })
213
+
214
+ site.announce('/es/classes')
215
+ const page = site.arriveAt({ asPath: '/classes', locale: 'es' })
216
+
217
+ expect(page?.props['data-tq-page-transition']).toBe('/classes')
218
+ expect(isFrozen(page)).toBe(false)
219
+ })
220
+
221
+ it('does not freeze the home page on a language switch either', () => {
222
+ const site = mountTransition(preset, { asPath: '/', locale: 'en', ...TWO_LANGUAGES })
223
+
224
+ site.announce('/es')
225
+
226
+ expect(isFrozen(site.arriveAt({ asPath: '/', locale: 'es' }))).toBe(false)
227
+ })
228
+
229
+ it('still freezes the page being left when a translated page moves to another page', () => {
230
+ const site = mountTransition(preset, { asPath: '/', locale: 'es', ...TWO_LANGUAGES })
231
+
232
+ site.announce('/es/classes')
233
+
234
+ expect(isFrozen(site.page())).toBe(true)
235
+ })
236
+
237
+ it('still freezes the page being left on a site with one language', () => {
238
+ const site = mountTransition(preset, { asPath: '/classes' })
239
+
240
+ site.announce('/pricing')
241
+
242
+ expect(isFrozen(site.page())).toBe(true)
243
+ })
244
+
245
+ it('takes an address that only differs by its query or hash for the same page', () => {
246
+ const site = mountTransition(preset, { asPath: '/classes', locale: 'es', ...TWO_LANGUAGES })
247
+
248
+ site.announce('/es/classes?level=1#top')
249
+
250
+ expect(isFrozen(site.page())).toBe(false)
251
+ })
252
+ })
253
+
254
+ describe('generated page transition (fade): the page arriving in a translated language', () => {
255
+ it('is laid over the page being left, as in the default language', () => {
256
+ const over = (route: Route, announced: string, arrived: Route) => {
257
+ const site = mountTransition('fade', route)
258
+ site.announce(announced)
259
+ const page = site.arriveAt(arrived)
260
+ return (page?.props.style as { position?: string } | undefined)?.position
261
+ }
262
+
263
+ const english = over({ asPath: '/', locale: 'en', ...TWO_LANGUAGES }, '/classes', {
264
+ asPath: '/classes',
265
+ })
266
+ const spanish = over({ asPath: '/', locale: 'es', ...TWO_LANGUAGES }, '/es/classes', {
267
+ asPath: '/classes',
268
+ })
269
+
270
+ expect(english).toBe('relative')
271
+ expect(spanish).toBe('relative')
272
+ })
273
+ })
@@ -1,2 +1,2 @@
1
- export declare const NAV_ACTIVE_LINK_COMPONENT_SOURCE = "import { useEffect } from 'react'\nimport { useRouter } from 'next/router'\n\n// Containers whose <a> descendants are navigation links.\nconst NAV_CONTAINERS = 'nav, [role=\"navigation\"], [class*=\"navigation\"], [class*=\"sidebar\"], [class*=\"navbar\"]'\n// The visible element the CSS styles as active may be the <a> itself or an\n// inner wrapper carrying the shared base class (e.g. <a><div class=\"navigation-link\">).\nconst ACTIVE_TARGET_TOKENS = ['navigation-link', 'nav-link', 'sidebar-link', 'nav-item', 'menu-item']\n\nfunction normalizePath(path) {\n if (!path) return '/'\n const clean = path.split('#')[0].split('?')[0]\n const trimmed = clean.replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\nfunction collectActiveTargets(anchor) {\n const targets = [anchor]\n const descendants = anchor.querySelectorAll('*')\n for (let i = 0; i < descendants.length; i++) {\n const el = descendants[i]\n const tokens = (el.getAttribute('class') || '').split(/\\s+/)\n for (let t = 0; t < tokens.length; t++) {\n if (ACTIVE_TARGET_TOKENS.indexOf(tokens[t]) !== -1) {\n targets.push(el)\n break\n }\n }\n }\n return targets\n}\n\nconst NavActiveLinks = () => {\n const router = useRouter()\n\n useEffect(() => {\n const apply = () => {\n try {\n const current = normalizePath(router.asPath)\n const seen = new Set()\n const containers = document.querySelectorAll(NAV_CONTAINERS)\n containers.forEach((container) => {\n const anchors = container.querySelectorAll('a[href]')\n anchors.forEach((anchor) => {\n if (seen.has(anchor)) return\n seen.add(anchor)\n const raw = anchor.getAttribute('href') || ''\n const linkable = raw && raw.charAt(0) !== '#' && !/^(https?:|mailto:|tel:)/i.test(raw)\n const isActive = linkable && normalizePath(raw) === current\n const targets = collectActiveTargets(anchor)\n targets.forEach((el) => {\n if (isActive) {\n el.classList.add('active')\n } else {\n el.classList.remove('active')\n }\n })\n if (isActive) {\n anchor.setAttribute('aria-current', 'page')\n } else if (anchor.getAttribute('aria-current') === 'page') {\n anchor.removeAttribute('aria-current')\n }\n })\n })\n } catch (err) {\n // Highlighting is best-effort \u2014 never let it break the page.\n }\n }\n\n apply()\n router.events.on('routeChangeComplete', apply)\n return () => {\n router.events.off('routeChangeComplete', apply)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [router.asPath])\n\n return null\n}\n\nexport default NavActiveLinks\n";
1
+ export declare const NAV_ACTIVE_LINK_COMPONENT_SOURCE = "import { useEffect } from 'react'\nimport { useRouter } from 'next/router'\n\n// Containers whose <a> descendants are navigation links.\nconst NAV_CONTAINERS = 'nav, [role=\"navigation\"], [class*=\"navigation\"], [class*=\"sidebar\"], [class*=\"navbar\"]'\n// The visible element the CSS styles as active may be the <a> itself or an\n// inner wrapper carrying the shared base class (e.g. <a><div class=\"navigation-link\">).\nconst ACTIVE_TARGET_TOKENS = ['navigation-link', 'nav-link', 'sidebar-link', 'nav-item', 'menu-item']\n\nfunction normalizePath(path) {\n if (!path) return '/'\n const clean = path.split('#')[0].split('?')[0]\n const trimmed = clean.replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n// '/es/classes' -> { locale: 'es', path: '/classes' }. A path with no language\n// prefix is in the default language (undefined on a single-language site).\nfunction splitLocale(path, locales, defaultLocale) {\n const segments = path.split('/')\n if (locales && segments.length > 1 && locales.indexOf(segments[1]) !== -1) {\n return { locale: segments[1], path: normalizePath('/' + segments.slice(2).join('/')) }\n }\n return { locale: defaultLocale, path: path }\n}\n\nfunction collectActiveTargets(anchor) {\n const targets = [anchor]\n const descendants = anchor.querySelectorAll('*')\n for (let i = 0; i < descendants.length; i++) {\n const el = descendants[i]\n const tokens = (el.getAttribute('class') || '').split(/\\s+/)\n for (let t = 0; t < tokens.length; t++) {\n if (ACTIVE_TARGET_TOKENS.indexOf(tokens[t]) !== -1) {\n targets.push(el)\n break\n }\n }\n }\n return targets\n}\n\nconst NavActiveLinks = () => {\n const router = useRouter()\n\n useEffect(() => {\n const apply = () => {\n try {\n const current = normalizePath(router.asPath)\n const seen = new Set()\n const containers = document.querySelectorAll(NAV_CONTAINERS)\n containers.forEach((container) => {\n const anchors = container.querySelectorAll('a[href]')\n anchors.forEach((anchor) => {\n if (seen.has(anchor)) return\n seen.add(anchor)\n const raw = anchor.getAttribute('href') || ''\n const linkable = raw && raw.charAt(0) !== '#' && !/^(https?:|mailto:|tel:)/i.test(raw)\n const target = linkable\n ? splitLocale(normalizePath(raw), router.locales, router.defaultLocale)\n : null\n const isActive = !!target && target.path === current && target.locale === router.locale\n const targets = collectActiveTargets(anchor)\n targets.forEach((el) => {\n if (isActive) {\n el.classList.add('active')\n } else {\n el.classList.remove('active')\n }\n })\n if (isActive) {\n anchor.setAttribute('aria-current', 'page')\n } else if (anchor.getAttribute('aria-current') === 'page') {\n anchor.removeAttribute('aria-current')\n }\n })\n })\n } catch (err) {\n // Highlighting is best-effort \u2014 never let it break the page.\n }\n }\n\n apply()\n router.events.on('routeChangeComplete', apply)\n\n // Links can be put on the page after this ran: a page that is built again\n // when the visitor reaches it again (a language switch, another item of the\n // same page), a menu drawn only when it opens. Whenever links are added,\n // mark them, once per frame at most. Marking changes classes and attributes\n // only, never the elements, so it cannot call itself.\n let frame = 0\n const addsLinks = (records) => {\n for (let r = 0; r < records.length; r++) {\n const added = records[r].addedNodes\n for (let n = 0; n < added.length; n++) {\n const node = added[n]\n if (node.nodeType === 1 && (node.tagName === 'A' || node.querySelector('a[href]'))) {\n return true\n }\n }\n }\n return false\n }\n const observer =\n typeof MutationObserver === 'function'\n ? new MutationObserver((records) => {\n if (!frame && addsLinks(records)) {\n frame = requestAnimationFrame(() => {\n frame = 0\n apply()\n })\n }\n })\n : null\n if (observer) {\n observer.observe(document.body, { childList: true, subtree: true })\n }\n\n return () => {\n router.events.off('routeChangeComplete', apply)\n if (observer) {\n observer.disconnect()\n }\n if (frame) {\n cancelAnimationFrame(frame)\n }\n }\n // A language switch keeps asPath and changes only the locale; the links it\n // re-renders must be marked again once they are on the page.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [router.asPath, router.locale])\n\n return null\n}\n\nexport default NavActiveLinks\n";
2
2
  //# sourceMappingURL=nav-active-link-component.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"nav-active-link-component.d.ts","sourceRoot":"","sources":["../../../src/nav-active-link/nav-active-link-component.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,gCAAgC,ozFAiF5C,CAAA"}
1
+ {"version":3,"file":"nav-active-link-component.d.ts","sourceRoot":"","sources":["../../../src/nav-active-link/nav-active-link-component.ts"],"names":[],"mappings":"AAsBA,eAAO,MAAM,gCAAgC,27JAwI5C,CAAA"}
@@ -9,11 +9,19 @@ exports.NAV_ACTIVE_LINK_COMPONENT_SOURCE = void 0;
9
9
  // class and NO hardcoded `active` / `aria-current` — a hardcoded active makes
10
10
  // one link (e.g. "Taproom"/"Dashboard") look selected on EVERY page. This
11
11
  // helper adds the `active` class + `aria-current="page"` to the link whose
12
- // href matches the current page and REMOVES it from the others, on first paint
13
- // and on every client-side route change. Removing it from non-matching links
14
- // also self-corrects a link the generator may have accidentally left marked.
12
+ // href matches the current page and REMOVES it from the others, on first paint,
13
+ // on every client-side route change, and whenever links are added to the page.
14
+ // Removing it from non-matching links also self-corrects a link the generator
15
+ // may have accidentally left marked.
15
16
  //
16
17
  // It is purely additive: it never touches href/onClick, and the whole pass is
17
18
  // wrapped in try/catch, so it can never break navigation.
18
- exports.NAV_ACTIVE_LINK_COMPONENT_SOURCE = "import { useEffect } from 'react'\nimport { useRouter } from 'next/router'\n\n// Containers whose <a> descendants are navigation links.\nconst NAV_CONTAINERS = 'nav, [role=\"navigation\"], [class*=\"navigation\"], [class*=\"sidebar\"], [class*=\"navbar\"]'\n// The visible element the CSS styles as active may be the <a> itself or an\n// inner wrapper carrying the shared base class (e.g. <a><div class=\"navigation-link\">).\nconst ACTIVE_TARGET_TOKENS = ['navigation-link', 'nav-link', 'sidebar-link', 'nav-item', 'menu-item']\n\nfunction normalizePath(path) {\n if (!path) return '/'\n const clean = path.split('#')[0].split('?')[0]\n const trimmed = clean.replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\nfunction collectActiveTargets(anchor) {\n const targets = [anchor]\n const descendants = anchor.querySelectorAll('*')\n for (let i = 0; i < descendants.length; i++) {\n const el = descendants[i]\n const tokens = (el.getAttribute('class') || '').split(/\\s+/)\n for (let t = 0; t < tokens.length; t++) {\n if (ACTIVE_TARGET_TOKENS.indexOf(tokens[t]) !== -1) {\n targets.push(el)\n break\n }\n }\n }\n return targets\n}\n\nconst NavActiveLinks = () => {\n const router = useRouter()\n\n useEffect(() => {\n const apply = () => {\n try {\n const current = normalizePath(router.asPath)\n const seen = new Set()\n const containers = document.querySelectorAll(NAV_CONTAINERS)\n containers.forEach((container) => {\n const anchors = container.querySelectorAll('a[href]')\n anchors.forEach((anchor) => {\n if (seen.has(anchor)) return\n seen.add(anchor)\n const raw = anchor.getAttribute('href') || ''\n const linkable = raw && raw.charAt(0) !== '#' && !/^(https?:|mailto:|tel:)/i.test(raw)\n const isActive = linkable && normalizePath(raw) === current\n const targets = collectActiveTargets(anchor)\n targets.forEach((el) => {\n if (isActive) {\n el.classList.add('active')\n } else {\n el.classList.remove('active')\n }\n })\n if (isActive) {\n anchor.setAttribute('aria-current', 'page')\n } else if (anchor.getAttribute('aria-current') === 'page') {\n anchor.removeAttribute('aria-current')\n }\n })\n })\n } catch (err) {\n // Highlighting is best-effort \u2014 never let it break the page.\n }\n }\n\n apply()\n router.events.on('routeChangeComplete', apply)\n return () => {\n router.events.off('routeChangeComplete', apply)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [router.asPath])\n\n return null\n}\n\nexport default NavActiveLinks\n";
19
+ //
20
+ // On a multi-language site a link is current only when it leads to the page
21
+ // the visitor is on IN THE LANGUAGE they are on. `router.asPath` never carries
22
+ // the language prefix while a rendered href does (`/es/classes`), so the two
23
+ // are compared as { language, path } pairs. Comparing the bare strings marked
24
+ // no menu link on any translated page, and marked the default language's link
25
+ // in a language switcher as the current page on every one of them.
26
+ exports.NAV_ACTIVE_LINK_COMPONENT_SOURCE = "import { useEffect } from 'react'\nimport { useRouter } from 'next/router'\n\n// Containers whose <a> descendants are navigation links.\nconst NAV_CONTAINERS = 'nav, [role=\"navigation\"], [class*=\"navigation\"], [class*=\"sidebar\"], [class*=\"navbar\"]'\n// The visible element the CSS styles as active may be the <a> itself or an\n// inner wrapper carrying the shared base class (e.g. <a><div class=\"navigation-link\">).\nconst ACTIVE_TARGET_TOKENS = ['navigation-link', 'nav-link', 'sidebar-link', 'nav-item', 'menu-item']\n\nfunction normalizePath(path) {\n if (!path) return '/'\n const clean = path.split('#')[0].split('?')[0]\n const trimmed = clean.replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n// '/es/classes' -> { locale: 'es', path: '/classes' }. A path with no language\n// prefix is in the default language (undefined on a single-language site).\nfunction splitLocale(path, locales, defaultLocale) {\n const segments = path.split('/')\n if (locales && segments.length > 1 && locales.indexOf(segments[1]) !== -1) {\n return { locale: segments[1], path: normalizePath('/' + segments.slice(2).join('/')) }\n }\n return { locale: defaultLocale, path: path }\n}\n\nfunction collectActiveTargets(anchor) {\n const targets = [anchor]\n const descendants = anchor.querySelectorAll('*')\n for (let i = 0; i < descendants.length; i++) {\n const el = descendants[i]\n const tokens = (el.getAttribute('class') || '').split(/\\s+/)\n for (let t = 0; t < tokens.length; t++) {\n if (ACTIVE_TARGET_TOKENS.indexOf(tokens[t]) !== -1) {\n targets.push(el)\n break\n }\n }\n }\n return targets\n}\n\nconst NavActiveLinks = () => {\n const router = useRouter()\n\n useEffect(() => {\n const apply = () => {\n try {\n const current = normalizePath(router.asPath)\n const seen = new Set()\n const containers = document.querySelectorAll(NAV_CONTAINERS)\n containers.forEach((container) => {\n const anchors = container.querySelectorAll('a[href]')\n anchors.forEach((anchor) => {\n if (seen.has(anchor)) return\n seen.add(anchor)\n const raw = anchor.getAttribute('href') || ''\n const linkable = raw && raw.charAt(0) !== '#' && !/^(https?:|mailto:|tel:)/i.test(raw)\n const target = linkable\n ? splitLocale(normalizePath(raw), router.locales, router.defaultLocale)\n : null\n const isActive = !!target && target.path === current && target.locale === router.locale\n const targets = collectActiveTargets(anchor)\n targets.forEach((el) => {\n if (isActive) {\n el.classList.add('active')\n } else {\n el.classList.remove('active')\n }\n })\n if (isActive) {\n anchor.setAttribute('aria-current', 'page')\n } else if (anchor.getAttribute('aria-current') === 'page') {\n anchor.removeAttribute('aria-current')\n }\n })\n })\n } catch (err) {\n // Highlighting is best-effort \u2014 never let it break the page.\n }\n }\n\n apply()\n router.events.on('routeChangeComplete', apply)\n\n // Links can be put on the page after this ran: a page that is built again\n // when the visitor reaches it again (a language switch, another item of the\n // same page), a menu drawn only when it opens. Whenever links are added,\n // mark them, once per frame at most. Marking changes classes and attributes\n // only, never the elements, so it cannot call itself.\n let frame = 0\n const addsLinks = (records) => {\n for (let r = 0; r < records.length; r++) {\n const added = records[r].addedNodes\n for (let n = 0; n < added.length; n++) {\n const node = added[n]\n if (node.nodeType === 1 && (node.tagName === 'A' || node.querySelector('a[href]'))) {\n return true\n }\n }\n }\n return false\n }\n const observer =\n typeof MutationObserver === 'function'\n ? new MutationObserver((records) => {\n if (!frame && addsLinks(records)) {\n frame = requestAnimationFrame(() => {\n frame = 0\n apply()\n })\n }\n })\n : null\n if (observer) {\n observer.observe(document.body, { childList: true, subtree: true })\n }\n\n return () => {\n router.events.off('routeChangeComplete', apply)\n if (observer) {\n observer.disconnect()\n }\n if (frame) {\n cancelAnimationFrame(frame)\n }\n }\n // A language switch keeps asPath and changes only the locale; the links it\n // re-renders must be marked again once they are on the page.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [router.asPath, router.locale])\n\n return null\n}\n\nexport default NavActiveLinks\n";
19
27
  //# sourceMappingURL=nav-active-link-component.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"nav-active-link-component.js","sourceRoot":"","sources":["../../../src/nav-active-link/nav-active-link-component.ts"],"names":[],"mappings":";;;AAAA,8EAA8E;AAC9E,yEAAyE;AACzE,wCAAwC;AACxC,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,6EAA6E;AAC7E,EAAE;AACF,8EAA8E;AAC9E,0DAA0D;AAC7C,QAAA,gCAAgC,GAAG,izFAiF/C,CAAA"}
1
+ {"version":3,"file":"nav-active-link-component.js","sourceRoot":"","sources":["../../../src/nav-active-link/nav-active-link-component.ts"],"names":[],"mappings":";;;AAAA,8EAA8E;AAC9E,yEAAyE;AACzE,wCAAwC;AACxC,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,gFAAgF;AAChF,+EAA+E;AAC/E,8EAA8E;AAC9E,qCAAqC;AACrC,EAAE;AACF,8EAA8E;AAC9E,0DAA0D;AAC1D,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,mEAAmE;AACtD,QAAA,gCAAgC,GAAG,w7JAwI/C,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"page-transition-component.d.ts","sourceRoot":"","sources":["../../../src/page-transition/page-transition-component.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAS5D,MAAM,MAAM,oBAAoB,GAAG,cAAc,CAAC,oBAAoB,CAAA;AAatE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,eAAO,MAAM,mCAAmC,WAAY,oBAAoB,KAAG,MAylBlF,CAAA"}
1
+ {"version":3,"file":"page-transition-component.d.ts","sourceRoot":"","sources":["../../../src/page-transition/page-transition-component.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAS5D,MAAM,MAAM,oBAAoB,GAAG,cAAc,CAAC,oBAAoB,CAAA;AAatE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,eAAO,MAAM,mCAAmC,WAAY,oBAAoB,KAAG,MAumBlF,CAAA"}