lib/composable.ts   A
last analyzed

Complexity

Total Complexity 3
Complexity/F 0

Size

Lines of Code 73
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
eloc 26
mnd 3
bc 3
fnc 0
dl 0
loc 73
ccs 72
cts 72
cp 1
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1 1
import type { ComputedRef, ComputedGetter, WatchSource } from 'vue';
2 1
import type { SetTitleFn } from './types';
3 1
import { inject, computed, ref, watch } from 'vue';
4 1
import { PAGE_TITLE, SET_PAGE_TITLE } from './injection-keys';
5 1
6 1
export type initialValue =
7 1
  | string
8 1
  | ComputedRef<string>
9 1
  | ComputedGetter<string>
10 1
  | WatchSource<string>;
11 1
12 1
/**
13 1
 * Get current title or update it.
14 1
 *
15 1
 * ## Define initial title
16 1
 *
17 1
 * ```ts
18 1
 * const { title } = useTitle('initial title`)
19 1
 * ```
20 1
 *
21 1
 * ## React from ref state
22 1
 *
23 1
 * ```ts
24 1
 * const name = ref('initial name')
25 1
 * const { title } = useTitle(name)
26 1
 * ```
27 1
 *
28 1
 * ## Use like a watch source argument
29 1
 *
30 1
 * ```ts
31 1
 * const product = ref({ name: 'One Piece 1017' })
32 1
 * const { title } = useTitle(() => product.name)
33 1
 * ```
34 1
 *
35 1
 * ## Pass a computed as argument
36 1
 *
37 1
 * ```ts
38 1
 * const product = ref({ name: 'One Piece 1017' })
39 1
 * const name = computed(() => product.name)
40 1
 * const { title } = useTitle(name)
41 1
 * ```
42 1
 *
43 1
 * ## Use `setTitle` to dynamically change the title
44 1
 *
45 1
 * ```ts
46 1
 * const product = ref({ name: 'One Piece 1017' })
47 1
 * const { setTitle } = useTitle()
48 1
 *
49 1
 * watchEffect(() => {
50 1
 *   setTitle(product.name)
51 1
 * })
52 1
 * ```
53 1
 */
54 1
const useTitle = (
55 1
  initial?: initialValue
56 3
): { title: ComputedRef<string>; setTitle: SetTitleFn } => {
57 3
  const title = inject(PAGE_TITLE, ref<string>(''));
58 3
  const setTitle = inject(SET_PAGE_TITLE, () => {});
59 3
60 3
  if (typeof initial === 'string') {
61 1
    setTitle(initial);
62 3
  } else if (initial != null) {
63 1
    watch(initial, setTitle, { immediate: true });
64 1
  }
65 1
66 3
  return {
67 3
    title: computed(() => title?.value),
68 3
    setTitle,
69 3
  };
70 3
};
71 1
72
export { useTitle };
73