-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
feat(nuxt): usePreviewMode
composable
#21705
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
Merged
Merged
Changes from all commits
Commits
Show all changes
57 commits
Select commit
Hold shift + click to select a range
4906fe1
feat: create `usePreviewMode` composable
logotip4ik 7610815
refactor: export and add to un import preset new composable
logotip4ik 9460446
test: add testing for preview mode
logotip4ik af690ad
refactor: make token ref readonly
logotip4ik ad612d8
chore: lint
logotip4ik dd48191
test: use contain instead of be
logotip4ik 89c0c7f
refactor: use reactive state instead of multiple refs
logotip4ik be41ee5
fix(test): failing if dev mode
logotip4ik 10c29d5
[autofix.ci] apply automated fixes
autofix-ci[bot] ce664da
Merge branch 'main' into feat/use-preview-mode
logotip4ik 4c822ab
Merge branch 'main' into feat/use-preview-mode
danielroe 1cb89c8
refactor: store preview state in `useState` composable and better types
logotip4ik 8dc023a
refactor: shorter type definition
logotip4ik 53698e2
test: add `usePreviewMode` composable to skipped ones
logotip4ik d06788d
refactor: actually use `PreviewOptions` type
logotip4ik 46f10ce
Update packages/nuxt/src/app/composables/preview.ts
logotip4ik f74ee68
feat: allow storing not only `token` value in preview state
logotip4ik 7e181cc
feat: allow users manually decide how to enable preview mode
logotip4ik 9ee7aa6
refactor: remove `previewMode` from variable names
logotip4ik b44c3fb
refactor: add side note
logotip4ik 35c6d4f
refactor: use `reactive` for preview state
logotip4ik 3cea4c0
feat: allow user manually setting on and off preview mode
logotip4ik e496e1e
test: custom preview mode enabling and state testing
logotip4ik b61550f
test: add missing `page.close`
logotip4ik c4f21cd
[autofix.ci] apply automated fixes
autofix-ci[bot] c17fa96
Merge remote-tracking branch 'origin/main' into feat/use-preview-mode
danielroe 1a62917
[autofix.ci] apply automated fixes
autofix-ci[bot] f276b86
docs: `usePreviewMode` api
logotip4ik 76bb35d
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik fb8d8d7
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik 71dbe5a
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik fb10bea
Update docs/3.api/1.composables/use-preview-mode.md
logotip4ik bcea49b
docs: recommend creating a composable to specify custom way to enableβ¦
logotip4ik addfd89
Merge branch 'main' into feat/use-preview-mode
logotip4ik 23b747b
[autofix.ci] apply automated fixes
autofix-ci[bot] 63a38b9
Merge branch 'main' into feat/use-preview-mode
danielroe ac96655
Merge branch 'main' into feat/use-preview-mode
logotip4ik 314e76c
refactor: remove `control` option
logotip4ik 7e0a09f
chore(test): remove `controls` options from tests
logotip4ik 8775866
chore: clear unregister hook after call
logotip4ik f6f9272
refactor: use relative paths to import functions
logotip4ik 6c834ae
chore: move docs page to correct folder
logotip4ik 26f5dbb
chore: remove `controls` options from docs
logotip4ik 59f0b57
chore: remove not needed fallback
logotip4ik 0b6399b
Merge branch 'main' into feat/use-preview-mode
logotip4ik 0992713
Merge branch 'main' into feat/use-preview-mode
logotip4ik a012a65
refactor: rework preview mode composable
logotip4ik e318db0
Update packages/nuxt/src/app/composables/preview.ts
logotip4ik e73707c
Merge branch 'main' into feat/use-preview-mode
logotip4ik cb3f38a
Merge branch 'main' into feat/use-preview-mode
logotip4ik 0e736bb
Merge remote-tracking branch 'origin' into feat/use-preview-mode
logotip4ik 47e2c4a
chore: add since directive
logotip4ik 62314c8
Merge remote-tracking branch 'origin/main' into feat/use-preview-mode
danielroe 951edd4
fix: only initialise preview mode once
danielroe d634438
fix: reinitialise preview on client
danielroe a43a184
fix(nuxt): only mark preview mode initialised on client
danielroe 2b2eb83
test: refactor preview mode tests
danielroe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
--- | ||
title: "usePreviewMode" | ||
description: "Use usePreviewMode to check and control preview mode in Nuxt" | ||
--- | ||
|
||
# `usePreviewMode` | ||
|
||
You can use the built-in `usePreviewMode` composable to access and control preview state in Nuxt. If the composable detects preview mode it will automatically force any updates necessary for [`useAsyncData`](/docs/api/composables/use-async-data) and [`useFetch`](/docs/api/composables/use-fetch) to rerender preview content. | ||
|
||
```js | ||
const { enabled, state } = usePreviewMode() | ||
``` | ||
|
||
## Options | ||
|
||
### Custom `enable` check | ||
|
||
You can specify a custom way to enable preview mode. By default the `usePreviewMode` composable will enable preview mode if there is a `preview` param in url that is equal to `true` (for example, `http://localhost:3000?preview=true`). You can wrap the `usePreviewMode` into custom composable, to keep options consistent across usages and prevent any errors. | ||
|
||
```js | ||
export function useMyPreviewMode () { | ||
return usePreviewMode({ | ||
shouldEnable: () => { | ||
return !!route.query.customPreview | ||
} | ||
}); | ||
}``` | ||
|
||
### Modify default state | ||
|
||
`usePreviewMode` will try to store the value of a `token` param from url in state. You can modify this state and it will be available for all [`usePreviewMode`](/docs/api/composables/use-preview-mode) calls. | ||
|
||
```js | ||
const data1 = ref('data1') | ||
|
||
const { enabled, state } = usePreviewMode({ | ||
getState: (currentState) => { | ||
return { data1, data2: 'data2' } | ||
} | ||
}) | ||
``` | ||
|
||
::alert{icon=π} | ||
The `getState` function will append returned values to current state, so be careful not to accidentally overwrite important state. | ||
:: | ||
|
||
## Example | ||
|
||
```vue [pages/some-page.vue] | ||
<script setup> | ||
const route = useRoute() | ||
|
||
const { enabled, state } = usePreviewMode({ | ||
shouldEnable: () => { | ||
return route.query.customPreview === 'true' | ||
}, | ||
}) | ||
|
||
const { data } = await useFetch('/api/preview', { | ||
query: { | ||
apiKey: state.token | ||
} | ||
}) | ||
</script> | ||
|
||
<template> | ||
<div> | ||
Some base content | ||
|
||
<p v-if="enabled"> | ||
Only preview content: {{ state.token }} | ||
|
||
<br> | ||
|
||
<button @click="enabled = false"> | ||
disable preview mode | ||
</button> | ||
</p> | ||
</div> | ||
</template> | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import { toRef, watch } from 'vue' | ||
|
||
import { useState } from './state' | ||
import { refreshNuxtData } from './asyncData' | ||
import { useRoute, useRouter } from './router' | ||
|
||
interface Preview { | ||
enabled: boolean | ||
state: Record<any, unknown> | ||
_initialized?: boolean | ||
} | ||
|
||
interface PreviewModeOptions<S> { | ||
shouldEnable?: (state: Preview['state']) => boolean, | ||
getState?: (state: Preview['state']) => S, | ||
} | ||
|
||
type EnteredState = Record<any, unknown> | null | undefined | void | ||
|
||
let unregisterRefreshHook: (() => any) | undefined | ||
|
||
/** @since 3.11.0 */ | ||
export function usePreviewMode<S extends EnteredState> (options: PreviewModeOptions<S> = {}) { | ||
const preview = useState<Preview>('_preview-state', () => ({ | ||
enabled: false, | ||
state: {} | ||
})) | ||
|
||
if (preview.value._initialized) { | ||
return { | ||
enabled: toRef(preview.value, 'enabled'), | ||
state: preview.value.state as S extends void ? Preview['state'] : (NonNullable<S> & Preview['state']), | ||
} | ||
} | ||
|
||
if (import.meta.client) { | ||
preview.value._initialized = true | ||
} | ||
|
||
if (!preview.value.enabled) { | ||
const shouldEnable = options.shouldEnable ?? defaultShouldEnable | ||
const result = shouldEnable(preview.value.state) | ||
|
||
if (typeof result === 'boolean') { preview.value.enabled = result } | ||
} | ||
|
||
watch(() => preview.value.enabled, (value) => { | ||
if (value) { | ||
const getState = options.getState ?? getDefaultState | ||
const newState = getState(preview.value.state) | ||
|
||
if (newState !== preview.value.state) { | ||
Object.assign(preview.value.state, newState) | ||
} | ||
|
||
if (import.meta.client && !unregisterRefreshHook) { | ||
refreshNuxtData() | ||
|
||
unregisterRefreshHook = useRouter().afterEach((() => refreshNuxtData())) | ||
} | ||
} else if (unregisterRefreshHook) { | ||
unregisterRefreshHook() | ||
|
||
unregisterRefreshHook = undefined | ||
} | ||
}, { immediate: true, flush: 'sync' }) | ||
|
||
return { | ||
enabled: toRef(preview.value, 'enabled'), | ||
state: preview.value.state as S extends void ? Preview['state'] : (NonNullable<S> & Preview['state']), | ||
} | ||
} | ||
|
||
function defaultShouldEnable () { | ||
const route = useRoute() | ||
const previewQueryName = 'preview' | ||
|
||
return route.query[previewQueryName] === 'true' | ||
} | ||
|
||
function getDefaultState (state: Preview['state']) { | ||
if (state.token !== undefined) { | ||
return state | ||
} | ||
|
||
const route = useRoute() | ||
|
||
state.token = Array.isArray(route.query.token) ? route.query.token[0] : route.query.token | ||
|
||
return state | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
<script setup> | ||
const { enabled: isPreview } = usePreviewMode() | ||
|
||
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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
<script setup> | ||
const route = useRoute() | ||
|
||
const { enabled } = usePreviewMode({ | ||
shouldEnable: () => { | ||
return !!route.query.customPreview | ||
} | ||
}) | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<p id="enabled"> | ||
{{ enabled }} | ||
</p> | ||
</div> | ||
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
<script setup> | ||
const data1 = ref('data1') | ||
|
||
const { enabled, state } = usePreviewMode({ | ||
getState: () => { | ||
return { data1, data2: 'data2' } | ||
} | ||
}) | ||
|
||
onMounted(() => { | ||
data1.value = 'data1 updated' | ||
}) | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<NuxtLink | ||
id="with-use-fetch" | ||
to="/preview/with-use-fetch" | ||
> | ||
fetch check | ||
</NuxtLink> | ||
|
||
<p id="data1"> | ||
{{ state.data1 }} | ||
</p> | ||
|
||
<p id="data2"> | ||
{{ state.data2 }} | ||
</p> | ||
|
||
<button | ||
id="toggle-preview" | ||
@click="enabled = !enabled" | ||
> | ||
toggle preview mode | ||
</button> | ||
</div> | ||
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<script setup> | ||
const { enabled, state } = usePreviewMode() | ||
|
||
const { data } = await useFetch('/api/preview', { | ||
query: { | ||
apiKey: state.token || undefined | ||
} | ||
}) | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<p id="enabled"> | ||
{{ enabled }} | ||
</p> | ||
|
||
<p id="token-check"> | ||
{{ state.token }} | ||
</p> | ||
|
||
<p id="correct-api-key-check"> | ||
{{ data && data.hehe }} | ||
</p> | ||
</div> | ||
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
const apiKeyName = 'apiKey' | ||
const apiKey = 'hehe' | ||
|
||
export default defineEventHandler((event) => { | ||
return { | ||
hehe: getQuery(event)[apiKeyName] === apiKey | ||
} | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.