1 |
b8cae450
|
Dominik Poch
|
import React, { createContext, useEffect, useState } from 'react';
|
2 |
|
|
import { TagCategoryInfo, TagInfo } from '../api';
|
3 |
|
|
import { tagController } from '../controllers';
|
4 |
|
|
|
5 |
|
|
/**
|
6 |
|
|
* Interface of a tag context provider.
|
7 |
|
|
*/
|
8 |
|
|
interface ITagCategoryContextProvider {
|
9 |
|
|
/**
|
10 |
|
|
* Tags managed by the context.
|
11 |
|
|
*/
|
12 |
|
|
tagCategories: TagCategoryInfo[] | null;
|
13 |
|
|
|
14 |
|
|
/**
|
15 |
|
|
* Sets new tags.
|
16 |
|
|
* @param newTags An array of new tags.
|
17 |
|
|
*/
|
18 |
|
|
setTagCategories: (newTagCategories: TagCategoryInfo[] | null) => void;
|
19 |
|
|
}
|
20 |
|
|
|
21 |
|
|
/**
|
22 |
|
|
* The tag context that manages available tags.
|
23 |
|
|
*/
|
24 |
|
|
export const TagCategoryContext = createContext<ITagCategoryContextProvider>({
|
25 |
|
|
/**
|
26 |
|
|
* Default tags.
|
27 |
|
|
*/
|
28 |
|
|
tagCategories: null,
|
29 |
|
|
|
30 |
|
|
/**
|
31 |
|
|
* Default implementation of setTags method.
|
32 |
|
|
* @param v Array of new tags.
|
33 |
|
|
*/
|
34 |
|
|
setTagCategories: (c) => {
|
35 |
|
|
return;
|
36 |
|
|
},
|
37 |
|
|
});
|
38 |
|
|
|
39 |
|
|
/**
|
40 |
|
|
* Provider of the tag context.
|
41 |
|
|
* @param props Children that should have access to the tag context.
|
42 |
|
|
* @returns Prepared html of the provider.
|
43 |
|
|
*/
|
44 |
|
|
const TagCategoryProvider = (props: { children: React.ReactNode }) => {
|
45 |
|
|
/**
|
46 |
|
|
* Tags managed by the context.
|
47 |
|
|
*/
|
48 |
|
|
const [tagCategories, setTagCategories] = useState<TagCategoryInfo[] | null>(null);
|
49 |
|
|
|
50 |
|
|
/**
|
51 |
|
|
* Initializes the context.
|
52 |
|
|
*/
|
53 |
|
|
useEffect(() => {
|
54 |
|
|
tagController.tagsGet().then((tagTree) => {
|
55 |
|
|
if (typeof tagTree.data.tagCategories != 'undefined') {
|
56 |
|
|
setTagCategories(tagTree.data.tagCategories);
|
57 |
|
|
}
|
58 |
|
|
});
|
59 |
|
|
}, []);
|
60 |
|
|
|
61 |
|
|
return (
|
62 |
|
|
<TagCategoryContext.Provider
|
63 |
|
|
value={{
|
64 |
|
|
tagCategories,
|
65 |
|
|
setTagCategories,
|
66 |
|
|
}}
|
67 |
|
|
>
|
68 |
|
|
{props.children}
|
69 |
|
|
</TagCategoryContext.Provider>
|
70 |
|
|
);
|
71 |
|
|
};
|
72 |
|
|
|
73 |
|
|
export default TagCategoryProvider;
|