Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nuxt): usePreviewMode composable #21705

Merged
merged 57 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
4906fe1
feat: create `usePreviewMode` composable
logotip4ik Jun 22, 2023
7610815
refactor: export and add to un import preset new composable
logotip4ik Jun 22, 2023
9460446
test: add testing for preview mode
logotip4ik Jun 22, 2023
af690ad
refactor: make token ref readonly
logotip4ik Jun 22, 2023
ad612d8
chore: lint
logotip4ik Jun 22, 2023
dd48191
test: use contain instead of be
logotip4ik Jun 22, 2023
89c0c7f
refactor: use reactive state instead of multiple refs
logotip4ik Jun 22, 2023
be41ee5
fix(test): failing if dev mode
logotip4ik Jun 23, 2023
10c29d5
[autofix.ci] apply automated fixes
autofix-ci[bot] Jun 23, 2023
ce664da
Merge branch 'main' into feat/use-preview-mode
logotip4ik Jul 8, 2023
4c822ab
Merge branch 'main' into feat/use-preview-mode
danielroe Jul 30, 2023
1cb89c8
refactor: store preview state in `useState` composable and better types
logotip4ik Jul 31, 2023
8dc023a
refactor: shorter type definition
logotip4ik Jul 31, 2023
53698e2
test: add `usePreviewMode` composable to skipped ones
logotip4ik Jul 31, 2023
d06788d
refactor: actually use `PreviewOptions` type
logotip4ik Aug 1, 2023
46f10ce
Update packages/nuxt/src/app/composables/preview.ts
logotip4ik Aug 2, 2023
f74ee68
feat: allow storing not only `token` value in preview state
logotip4ik Aug 2, 2023
7e181cc
feat: allow users manually decide how to enable preview mode
logotip4ik Aug 2, 2023
9ee7aa6
refactor: remove `previewMode` from variable names
logotip4ik Aug 2, 2023
b44c3fb
refactor: add side note
logotip4ik Aug 3, 2023
35c6d4f
refactor: use `reactive` for preview state
logotip4ik Aug 3, 2023
3cea4c0
feat: allow user manually setting on and off preview mode
logotip4ik Aug 3, 2023
e496e1e
test: custom preview mode enabling and state testing
logotip4ik Aug 3, 2023
b61550f
test: add missing `page.close`
logotip4ik Aug 3, 2023
c4f21cd
[autofix.ci] apply automated fixes
autofix-ci[bot] Aug 3, 2023
c17fa96
Merge remote-tracking branch 'origin/main' into feat/use-preview-mode
danielroe Oct 2, 2023
1a62917
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 2, 2023
f276b86
docs: `usePreviewMode` api
logotip4ik Oct 4, 2023
76bb35d
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik Oct 11, 2023
fb8d8d7
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik Oct 11, 2023
71dbe5a
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik Oct 11, 2023
fb10bea
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik Oct 11, 2023
bcea49b
docs: recommend creating a composable to specify custom way to enable…
logotip4ik Oct 11, 2023
addfd89
Merge branch 'main' into feat/use-preview-mode
logotip4ik Nov 25, 2023
23b747b
[autofix.ci] apply automated fixes
autofix-ci[bot] Nov 25, 2023
63a38b9
Merge branch 'main' into feat/use-preview-mode
danielroe Dec 11, 2023
ac96655
Merge branch 'main' into feat/use-preview-mode
logotip4ik Dec 15, 2023
314e76c
refactor: remove `control` option
logotip4ik Dec 15, 2023
7e0a09f
chore(test): remove `controls` options from tests
logotip4ik Dec 15, 2023
8775866
chore: clear unregister hook after call
logotip4ik Dec 15, 2023
f6f9272
refactor: use relative paths to import functions
logotip4ik Dec 15, 2023
6c834ae
chore: move docs page to correct folder
logotip4ik Dec 17, 2023
26f5dbb
chore: remove `controls` options from docs
logotip4ik Dec 17, 2023
59f0b57
chore: remove not needed fallback
logotip4ik Dec 17, 2023
0b6399b
Merge branch 'main' into feat/use-preview-mode
logotip4ik Dec 19, 2023
0992713
Merge branch 'main' into feat/use-preview-mode
logotip4ik Dec 19, 2023
a012a65
refactor: rework preview mode composable
logotip4ik Dec 19, 2023
e318db0
Update packages/nuxt/src/app/composables/preview.ts
logotip4ik Dec 20, 2023
e73707c
Merge branch 'main' into feat/use-preview-mode
logotip4ik Jan 18, 2024
cb3f38a
Merge branch 'main' into feat/use-preview-mode
logotip4ik Jan 25, 2024
0e736bb
Merge remote-tracking branch 'origin' into feat/use-preview-mode
logotip4ik Feb 18, 2024
47e2c4a
chore: add since directive
logotip4ik Feb 18, 2024
62314c8
Merge remote-tracking branch 'origin/main' into feat/use-preview-mode
danielroe Mar 6, 2024
951edd4
fix: only initialise preview mode once
danielroe Mar 6, 2024
d634438
fix: reinitialise preview on client
danielroe Mar 6, 2024
a43a184
fix(nuxt): only mark preview mode initialised on client
danielroe Mar 6, 2024
2b2eb83
test: refactor preview mode tests
danielroe Mar 6, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/index.ts
Expand Up @@ -32,3 +32,4 @@ export { isPrerendered, loadPayload, preloadPayload, definePayloadReducer, defin
export type { ReloadNuxtAppOptions } from './chunk'
export { reloadNuxtApp } from './chunk'
export { useRequestURL } from './url'
export { usePreviewMode } from './preview'
65 changes: 65 additions & 0 deletions packages/nuxt/src/app/composables/preview.ts
@@ -0,0 +1,65 @@
import { reactive, readonly, toRef } from 'vue'

import { refreshNuxtData, useRoute, useRouter, useState } from '#app'

export interface PreviewOptions<Controls extends boolean = false> {
controls?: Controls
tokenQueryName?: string
}

interface PreviewState {
enabled: boolean
token: string | null
addedAfterNavigationCallback: boolean
}

const previewQueryName = 'preview'

export function usePreviewMode<Controls extends boolean = false> (options?: PreviewOptions<Controls>) {
options = {
controls: false as Controls,
tokenQueryName: 'token',
...(options || {})
}

const router = useRouter()
const route = useRoute()

logotip4ik marked this conversation as resolved.
Show resolved Hide resolved
const previewState = useState('_preview-composable', () => reactive<PreviewState>({
enabled: false,
token: null,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few ideas:

  • instead of defaulting to just token which I agree is the most common scenario, what do you think about setting arbitrary state?
  • What about an option that ignores query param and allowing user to manually engage/disengage query mode instead (for more complex situations?
  • when enabled is manually set to false, we probably want to remove the refreshNuxtData router hook - maybe a computed ref with manual set/get values could be useful here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a little question, is there a point of something like shouldEnable if we give user ability to toggle on and off preview mode ? I think of flag shouldAutoDetect and if it is true, then detect preview in query (or we could say that shouldAutoDetect can be boolean or string, if it is a string we will match for that string instead), if false, let user manually do some detection (in for example onMounted hook) and set enabled to true ?

addedAfterNavigationCallback: false
}))

if (!previewState.value.enabled) {
const previewParam = route.query[previewQueryName]

previewState.value.enabled = !!previewParam && previewParam === 'true'
logotip4ik marked this conversation as resolved.
Show resolved Hide resolved

if (previewState.value.enabled && !previewState.value.token) {
const query = route.query[options!.tokenQueryName!]
const token = Array.isArray(query) ? query[0] : query

if (token) {
previewState.value.token = token
}
}
}

const refreshData = () => {
previewState.value.addedAfterNavigationCallback = true
refreshNuxtData()
}

if (previewState.value.enabled && !previewState.value.addedAfterNavigationCallback && process.client) {
refreshData()
router.afterEach(refreshData)
}

const enabled = readonly(toRef(previewState.value, 'enabled'))
const token = readonly(toRef(previewState.value, 'token'))

return (options.controls
? { enabled, token }
: enabled) as Controls extends true ? { enabled: typeof enabled, token: typeof token } : typeof enabled
}
1 change: 1 addition & 0 deletions packages/nuxt/src/imports/presets.ts
Expand Up @@ -35,6 +35,7 @@ const appPreset = defineUnimportPreset({
'useRequestEvent',
'useRequestFetch',
'useRequestURL',
'usePreviewMode',
'setResponseStatus',
'setPageLayout',
'onNuxtReady',
Expand Down
25 changes: 25 additions & 0 deletions test/basic.test.ts
Expand Up @@ -439,6 +439,31 @@ describe('pages', () => {
expect(response).not.toContain('don\'t look at this')
expect(response).toContain('OH NNNNNNOOOOOOOOOOO')
})

it('respects preview mode', async () => {
const token = 'hehe'

const page = await createPage(`/preview?preview=true&token=${token}`)

const hasRunOnClient = await new Promise<boolean>((resolve) => {
page.on('console', (message) => {
setTimeout(() => resolve(false), 4000)

if (message.text() === 'true') { resolve(true) }
})
})

expect(hasRunOnClient).toBe(true)

expect(await page.locator('#fetched-on-client').textContent()).toContain('fetched on client')
expect(await page.locator('#preview-mode').textContent()).toContain('preview mode enabled')

await page.click('#use-fetch-check')
await page.waitForLoadState('networkidle')

expect(await page.locator('#token-check').textContent()).toContain(token)
expect(await page.locator('#correct-api-key-check').textContent()).toContain('true')
})
})

describe('nuxt composables', () => {
Expand Down
29 changes: 29 additions & 0 deletions test/fixtures/basic/pages/preview/index.vue
@@ -0,0 +1,29 @@
<script setup>
const { enabled: isPreview } = usePreviewMode({ controls: true })

const { data } = await useAsyncData(async () => {
await new Promise(resolve => setTimeout(resolve, 200))

const fetchedOnClient = process.client

console.log(fetchedOnClient)

return { fetchedOnClient }
})
</script>

<template>
<div>
<NuxtLink id="use-fetch-check" href="/preview/with-use-fetch">
check useFetch
</NuxtLink>

<p v-if="data && data.fetchedOnClient" id="fetched-on-client">
fetched on client
</p>

<p v-if="isPreview" id="preview-mode">
preview mode enabled
</p>
</div>
</template>
21 changes: 21 additions & 0 deletions test/fixtures/basic/pages/preview/with-use-fetch.vue
@@ -0,0 +1,21 @@
<script setup>
const { token } = usePreviewMode({ controls: true })

const { data } = await useFetch('/api/preview', {
query: {
apiKey: token.value || undefined
}
})
</script>

<template>
<div>
<p id="token-check">
{{ token }}
</p>

<p id="correct-api-key-check">
{{ data && data.hehe }}
</p>
</div>
</template>
8 changes: 8 additions & 0 deletions test/fixtures/basic/server/api/preview.ts
@@ -0,0 +1,8 @@
const apiKeyName = 'apiKey'
const apiKey = 'hehe'

export default defineEventHandler((event) => {
return {
hehe: getQuery(event)[apiKeyName] === apiKey
}
})
3 changes: 2 additions & 1 deletion test/nuxt/composables.test.ts
Expand Up @@ -63,7 +63,8 @@ describe('composables', () => {
'useRoute',
'useRouter',
'useSeoMeta',
'useServerSeoMeta'
'useServerSeoMeta',
'usePreviewMode'
]
expect(Object.keys(composables).sort()).toEqual([...new Set([...testedComposables, ...skippedComposables])].sort())
})
Expand Down