Skip to content

Commit

Permalink
chore: update
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Oct 16, 2022
1 parent 6bde0e5 commit cda7658
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions packages/core/useTitle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import { useMutationObserver } from '../useMutationObserver'
import type { ConfigurableDocument } from '../_configurable'
import { defaultDocument } from '../_configurable'

export interface UseTitleOptions extends ConfigurableDocument {
export type UseTitleOptionsBase =
{
/**
* Observe `document.title` changes using MutationObserve
* Cannot be used together with `titleTemplate` option.
*
* @default false
*/
observe?: boolean
}
| {
/**
* The template string to parse the title (e.g., '%s | My Website')
* Cannot be used together with `observe` option.
Expand All @@ -23,6 +26,8 @@ export interface UseTitleOptions extends ConfigurableDocument {
titleTemplate?: MaybeRef<string> | ((title: string) => string)
}

export type UseTitleOptions = ConfigurableDocument & UseTitleOptionsBase

export function useTitle(
newTitle: MaybeReadonlyRef<string | null | undefined>,
options?: UseTitleOptions,
Expand All @@ -49,22 +54,20 @@ export function useTitle(
the `document.title` to be different from the `title.value`,
causing the title to update infinitely if `observe` is set to `true`.
*/
if (options.observe && options.titleTemplate)
throw new Error('Cannot use `observe` and `titleTemplate` together.')

const {
document = defaultDocument,
observe = false,
titleTemplate = '%s',
} = options

const title: WritableComputedRef<string | null | undefined> = resolveRef(newTitle ?? document?.title ?? null)
const isReadonly = newTitle && isFunction(newTitle)

function format(t: string) {
return isFunction(titleTemplate)
? titleTemplate(t)
: unref(titleTemplate).replace(/%s/g, t)
if (!('titleTemplate' in options))
return t
const template = options.titleTemplate || '%s'
return isFunction(template)
? template(t)
: unref(template).replace(/%s/g, t)
}

watch(
Expand All @@ -76,7 +79,7 @@ export function useTitle(
{ immediate: true },
)

if (observe && document && !isReadonly) {
if ((options as any).observe && !(options as any).titleTemplate && document && !isReadonly) {
useMutationObserver(
document.head?.querySelector('title'),
() => {
Expand Down

0 comments on commit cda7658

Please sign in to comment.