@milabench/bujang 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +108 -2
  2. package/dist/api.d.ts +151 -0
  3. package/dist/components/AutocompleteInput.d.ts +15 -0
  4. package/dist/components/MonacoEditor.d.ts +11 -0
  5. package/dist/components/toaster.d.ts +2 -0
  6. package/dist/components/tooltip.d.ts +11 -0
  7. package/dist/constants.d.ts +3 -0
  8. package/dist/context.d.ts +44 -0
  9. package/dist/hooks/useColorMode.d.ts +4 -0
  10. package/dist/hooks/usePageTitle.d.ts +2 -0
  11. package/dist/index.d.ts +26 -0
  12. package/dist/index.js +5036 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/paths.d.ts +26 -0
  15. package/dist/routes.d.ts +22 -0
  16. package/dist/theme.css +72 -0
  17. package/dist/toast.d.ts +18 -0
  18. package/dist/types.d.ts +474 -0
  19. package/dist/views/AgentActivityView.d.ts +8 -0
  20. package/dist/views/JobDetails.d.ts +2 -0
  21. package/dist/views/JobLogs.d.ts +4 -0
  22. package/dist/views/JobSubmit.d.ts +22 -0
  23. package/dist/views/JobSubmitView.d.ts +2 -0
  24. package/dist/views/JobsView.d.ts +4 -0
  25. package/dist/views/LogDisplay.d.ts +11 -0
  26. package/dist/views/PipelinesView.d.ts +2 -0
  27. package/dist/views/ScheduledJobsView.d.ts +2 -0
  28. package/package.json +70 -4
  29. package/src/api.ts +602 -0
  30. package/src/components/AutocompleteInput.tsx +253 -0
  31. package/src/components/MonacoEditor.tsx +163 -0
  32. package/src/components/toaster.tsx +38 -0
  33. package/src/components/tooltip.tsx +52 -0
  34. package/src/constants.ts +3 -0
  35. package/src/context.tsx +106 -0
  36. package/src/hooks/useColorMode.ts +31 -0
  37. package/src/hooks/usePageTitle.ts +21 -0
  38. package/src/index.ts +33 -0
  39. package/src/paths.ts +71 -0
  40. package/src/routes.tsx +55 -0
  41. package/src/theme.css +72 -0
  42. package/src/toast.ts +35 -0
  43. package/src/types.ts +542 -0
  44. package/src/views/AgentActivityView.tsx +262 -0
  45. package/src/views/JobDetails.tsx +675 -0
  46. package/src/views/JobLogs.tsx +987 -0
  47. package/src/views/JobSubmit.tsx +1272 -0
  48. package/src/views/JobSubmitView.tsx +69 -0
  49. package/src/views/JobsView.tsx +736 -0
  50. package/src/views/LogDisplay.tsx +171 -0
  51. package/src/views/PipelinesView.tsx +1318 -0
  52. package/src/views/ScheduledJobsView.tsx +735 -0
@@ -0,0 +1,253 @@
1
+ import React, { useState, useEffect, useMemo, useRef } from 'react';
2
+ import {
3
+ Box,
4
+ Input,
5
+ VStack,
6
+ Text,
7
+ Spinner,
8
+ } from '@chakra-ui/react';
9
+
10
+ interface AutocompleteInputProps {
11
+ value: string;
12
+ onChange: (value: string) => void;
13
+ suggestions: string[];
14
+ placeholder?: string;
15
+ disabled?: boolean;
16
+ size?: 'sm' | 'md' | 'lg';
17
+ width?: string;
18
+ isLoading?: boolean;
19
+ onSelect?: (value: string) => void;
20
+ renderSuggestion?: (suggestion: string) => React.ReactNode;
21
+ }
22
+
23
+ const AutocompleteInput: React.FC<AutocompleteInputProps> = ({
24
+ value,
25
+ onChange,
26
+ suggestions = [],
27
+ placeholder = "Enter value...",
28
+ disabled = false,
29
+ size = 'md',
30
+ width = 'auto',
31
+ isLoading = false,
32
+ onSelect,
33
+ renderSuggestion
34
+ }) => {
35
+ const [inputValue, setInputValue] = useState(value);
36
+ const [showSuggestions, setShowSuggestions] = useState(false);
37
+ const [selectedIndex, setSelectedIndex] = useState(-1);
38
+
39
+ const dropdownRef = useRef<HTMLDivElement>(null);
40
+
41
+
42
+ // Close dropdown when clicking outside
43
+ useEffect(() => {
44
+ const handleClickOutside = (event: MouseEvent) => {
45
+ if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
46
+ setShowSuggestions(false);
47
+ setSelectedIndex(-1);
48
+ }
49
+ };
50
+
51
+ document.addEventListener('mousedown', handleClickOutside);
52
+ return () => {
53
+ document.removeEventListener('mousedown', handleClickOutside);
54
+ };
55
+ }, []);
56
+
57
+ // Update input value when prop changes
58
+ useEffect(() => {
59
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- inputValue is a local editable mirror of the `value` prop (also mutated by typing/selection), so it must be resynced after the prop changes from outside.
60
+ setInputValue(value);
61
+ }, [value]);
62
+
63
+ // Calculate similarity score between input and suggestion
64
+ const calculateSimilarity = (input: string, suggestion: string): number => {
65
+ const inputLower = input.toLowerCase().trim();
66
+ const suggestionLower = suggestion.toLowerCase();
67
+
68
+ if (!inputLower) return 0;
69
+ if (suggestionLower === inputLower) return 1000; // Exact match gets highest score
70
+ if (suggestionLower.startsWith(inputLower)) return 900; // Starts with gets very high score
71
+ if (suggestionLower.includes(inputLower)) return 800; // Contains gets high score
72
+
73
+ // Calculate fuzzy similarity for partial matches
74
+ let similarity = 0;
75
+ let inputIndex = 0;
76
+
77
+ for (let i = 0; i < suggestionLower.length && inputIndex < inputLower.length; i++) {
78
+ if (suggestionLower[i] === inputLower[inputIndex]) {
79
+ similarity += 10;
80
+ inputIndex++;
81
+ }
82
+ }
83
+
84
+ // Bonus for matching more characters
85
+ similarity += (inputIndex / inputLower.length) * 100;
86
+
87
+ // Penalty for length difference
88
+ const lengthDiff = Math.abs(suggestionLower.length - inputLower.length);
89
+ similarity -= lengthDiff * 2;
90
+
91
+ return Math.max(0, similarity);
92
+ };
93
+
94
+ // Sort suggestions by similarity to input
95
+ const filteredSuggestions = useMemo(() => {
96
+ if (!inputValue.trim()) {
97
+ return suggestions;
98
+ }
99
+ return suggestions
100
+ .map(suggestion => ({
101
+ suggestion,
102
+ score: calculateSimilarity(inputValue, suggestion)
103
+ }))
104
+ .filter(item => item.score > 0) // Only include items with some similarity
105
+ .sort((a, b) => b.score - a.score) // Sort by score descending
106
+ .map(item => item.suggestion);
107
+ }, [inputValue, suggestions]);
108
+
109
+ // Reset the highlighted suggestion whenever the (derived) list changes
110
+ useEffect(() => {
111
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- selectedIndex is independently mutated by keyboard/mouse handlers, so it can't be a pure derivation; reset it whenever the filtered list changes.
112
+ setSelectedIndex(-1);
113
+ }, [filteredSuggestions]);
114
+
115
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
116
+ const newValue = e.target.value;
117
+ setInputValue(newValue);
118
+ onChange(newValue);
119
+ setShowSuggestions(true);
120
+ setSelectedIndex(-1);
121
+ };
122
+
123
+ const handleInputFocus = () => {
124
+ setShowSuggestions(true);
125
+ };
126
+
127
+ const handleSuggestionSelect = (suggestion: string) => {
128
+ setInputValue(suggestion);
129
+ onChange(suggestion);
130
+ setShowSuggestions(false);
131
+ setSelectedIndex(-1);
132
+ if (onSelect) {
133
+ onSelect(suggestion);
134
+ }
135
+ };
136
+
137
+ const handleInputBlur = () => {
138
+ // Small delay to allow suggestion clicks to register
139
+ setTimeout(() => {
140
+ if (!dropdownRef.current?.contains(document.activeElement)) {
141
+ setShowSuggestions(false);
142
+ setSelectedIndex(-1);
143
+ }
144
+ }, 200);
145
+ };
146
+
147
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
148
+ if (!showSuggestions) return;
149
+
150
+ switch (e.key) {
151
+ case 'ArrowDown':
152
+ e.preventDefault();
153
+ setSelectedIndex(prev =>
154
+ prev < filteredSuggestions.length - 1 ? prev + 1 : prev
155
+ );
156
+ break;
157
+ case 'ArrowUp':
158
+ e.preventDefault();
159
+ setSelectedIndex(prev => prev > 0 ? prev - 1 : -1);
160
+ break;
161
+ case 'Enter':
162
+ e.preventDefault();
163
+ if (selectedIndex >= 0 && selectedIndex < filteredSuggestions.length) {
164
+ handleSuggestionSelect(filteredSuggestions[selectedIndex]);
165
+ } else {
166
+ setShowSuggestions(false);
167
+ setSelectedIndex(-1);
168
+ }
169
+ break;
170
+ case 'Escape':
171
+ setShowSuggestions(false);
172
+ setSelectedIndex(-1);
173
+ break;
174
+ }
175
+ };
176
+
177
+ const inputSize = size === 'sm' ? 'sm' : size === 'lg' ? 'lg' : 'md';
178
+
179
+ return (
180
+ <Box position="relative" width={width} ref={dropdownRef}>
181
+ <Input
182
+ value={inputValue}
183
+ onChange={handleInputChange}
184
+ onFocus={handleInputFocus}
185
+ onBlur={handleInputBlur}
186
+ onKeyDown={handleKeyDown}
187
+ placeholder={placeholder}
188
+ disabled={disabled}
189
+ size={inputSize}
190
+ bg="var(--color-bg-card)"
191
+ borderColor="var(--color-border)"
192
+ color="var(--color-text)"
193
+ _hover={{ borderColor: 'var(--color-border)' }}
194
+ _focus={{ borderColor: 'var(--color-primary)', boxShadow: '0 0 0 1px var(--color-primary)' }}
195
+ />
196
+
197
+ {showSuggestions && !disabled && (
198
+ <Box
199
+ position="absolute"
200
+ top="100%"
201
+ left={0}
202
+ right={0}
203
+ bg="var(--color-bg-card)"
204
+ border="1px solid"
205
+ borderColor="var(--color-border)"
206
+ borderRadius="md"
207
+ boxShadow="md"
208
+ zIndex={1000}
209
+ maxHeight="200px"
210
+ overflowY="auto"
211
+ >
212
+ {isLoading ? (
213
+ <Box p={2} textAlign="center">
214
+ <Spinner size="sm" />
215
+ </Box>
216
+ ) : filteredSuggestions.length > 0 ? (
217
+ <VStack gap={0} align="stretch">
218
+ {filteredSuggestions.map((suggestion, index) => (
219
+ <Box
220
+ key={index}
221
+ px={3}
222
+ py={2}
223
+ cursor="pointer"
224
+ bg={selectedIndex === index ? 'var(--color-bg-hover)' : "transparent"}
225
+ borderLeft={selectedIndex === index ? "3px solid" : "3px solid transparent"}
226
+ borderColor={selectedIndex === index ? 'var(--color-primary)' : "transparent"}
227
+ color="var(--color-text)"
228
+ _hover={{ bg: 'var(--color-bg-hover)' }}
229
+ onMouseDown={(e) => {
230
+ e.preventDefault(); // Prevent input blur
231
+ handleSuggestionSelect(suggestion);
232
+ }}
233
+ onMouseEnter={() => setSelectedIndex(index)}
234
+ fontSize={inputSize === 'sm' ? 'sm' : 'md'}
235
+ >
236
+ {renderSuggestion ? renderSuggestion(suggestion) : (
237
+ <Text color="var(--color-text)">{suggestion}</Text>
238
+ )}
239
+ </Box>
240
+ ))}
241
+ </VStack>
242
+ ) : (
243
+ <Box p={2} color="var(--color-text-muted)" fontSize="sm" textAlign="center">
244
+ No suggestions found
245
+ </Box>
246
+ )}
247
+ </Box>
248
+ )}
249
+ </Box>
250
+ );
251
+ };
252
+
253
+ export default AutocompleteInput;
@@ -0,0 +1,163 @@
1
+ import React from 'react';
2
+ import { useColorMode } from '../hooks/useColorMode';
3
+ import { Box } from '@chakra-ui/react';
4
+ import Editor from '@monaco-editor/react';
5
+ import type { OnMount } from '@monaco-editor/react';
6
+
7
+ /** Monaco standalone code editor instance (without depending on monaco-editor's types directly). */
8
+ export type MonacoCodeEditor = Parameters<OnMount>[0];
9
+
10
+ // Monaco Editor component for bash script editing
11
+ export const MonacoEditor: React.FC<{
12
+ value: string;
13
+ onChange: (value: string) => void;
14
+ onMount?: (editor: MonacoCodeEditor) => void;
15
+ height?: string;
16
+ language?: string;
17
+ }> = ({ value, onChange, onMount, height = "400px", language = 'shell' }) => {
18
+ const { colorMode } = useColorMode();
19
+ const isDark = colorMode === 'dark';
20
+ const containerRef = React.useRef<HTMLDivElement>(null);
21
+ const [editorHeight, setEditorHeight] = React.useState(height);
22
+ const lastHeightRef = React.useRef<number>(0);
23
+ const updateTimeoutRef = React.useRef<number | null>(null);
24
+
25
+ React.useEffect(() => {
26
+ if (height === "100%" && containerRef.current) {
27
+ const updateHeight = () => {
28
+ if (containerRef.current && containerRef.current.parentElement) {
29
+ const parentRect = containerRef.current.parentElement.getBoundingClientRect();
30
+ const newHeight = parentRect.height;
31
+
32
+ // Only update if height actually changed significantly (more than 2px difference)
33
+ if (newHeight > 0 && Math.abs(newHeight - lastHeightRef.current) > 2) {
34
+ lastHeightRef.current = newHeight;
35
+ setEditorHeight(`${newHeight}px`);
36
+ }
37
+ }
38
+ };
39
+
40
+ // Initial update after a short delay to ensure layout is stable
41
+ const initialTimeout = window.setTimeout(() => {
42
+ requestAnimationFrame(updateHeight);
43
+ }, 100);
44
+
45
+ // Watch parent container resize, not the editor container itself
46
+ let resizeObserver: ResizeObserver | null = null;
47
+ const parentElement = containerRef.current.parentElement;
48
+
49
+ if (parentElement) {
50
+ resizeObserver = new ResizeObserver(() => {
51
+ // Clear any pending updates
52
+ if (updateTimeoutRef.current !== null) {
53
+ window.clearTimeout(updateTimeoutRef.current);
54
+ }
55
+
56
+ // Debounce updates to prevent rapid-fire changes
57
+ updateTimeoutRef.current = window.setTimeout(() => {
58
+ requestAnimationFrame(updateHeight);
59
+ }, 50);
60
+ });
61
+ resizeObserver.observe(parentElement);
62
+ }
63
+
64
+ // Also listen to window resize with debounce
65
+ let resizeTimeout: number;
66
+ const handleResize = () => {
67
+ clearTimeout(resizeTimeout);
68
+ resizeTimeout = window.setTimeout(() => {
69
+ requestAnimationFrame(updateHeight);
70
+ }, 150);
71
+ };
72
+ window.addEventListener('resize', handleResize);
73
+
74
+ return () => {
75
+ window.clearTimeout(initialTimeout);
76
+ if (updateTimeoutRef.current !== null) {
77
+ window.clearTimeout(updateTimeoutRef.current);
78
+ }
79
+ if (resizeObserver) {
80
+ resizeObserver.disconnect();
81
+ }
82
+ window.removeEventListener('resize', handleResize);
83
+ window.clearTimeout(resizeTimeout);
84
+ };
85
+ } else {
86
+ setEditorHeight(height);
87
+ }
88
+ }, [height]);
89
+
90
+ return (
91
+ <Box
92
+ ref={containerRef}
93
+ border="1px solid"
94
+ borderColor="var(--color-border)"
95
+ borderRadius="md"
96
+ overflow="hidden"
97
+ flex={1}
98
+ height={height === "100%" ? "100%" : undefined}
99
+ minH={height === "100%" ? "400px" : undefined}
100
+ maxH={height === "100%" ? "100%" : undefined}
101
+ display="flex"
102
+ flexDirection="column"
103
+ position="relative"
104
+ >
105
+ <Box flex={1} minH={0} overflow="hidden" height="100%">
106
+ <Editor
107
+ height={editorHeight}
108
+ defaultLanguage={language}
109
+ language={language}
110
+ value={value}
111
+ onChange={(value) => onChange(value || '')}
112
+ theme={isDark ? 'vs-dark' : 'light'}
113
+ onMount={(editor, monaco) => {
114
+ if (onMount) {
115
+ onMount(editor);
116
+ }
117
+ const model = editor.getModel();
118
+ if (model) {
119
+ model.setEOL(monaco.editor.EndOfLineSequence.LF);
120
+ }
121
+ }}
122
+ options={{
123
+ minimap: { enabled: false },
124
+ scrollBeyondLastLine: false,
125
+ fontSize: 14,
126
+ lineNumbers: 'on',
127
+ roundedSelection: false,
128
+ scrollbar: {
129
+ vertical: 'visible',
130
+ horizontal: 'visible'
131
+ },
132
+ automaticLayout: true,
133
+ wordWrap: 'on',
134
+ folding: true,
135
+ foldingStrategy: 'indentation',
136
+ showFoldingControls: 'always',
137
+ lineDecorationsWidth: 10,
138
+ lineNumbersMinChars: 3,
139
+ glyphMargin: true,
140
+ fixedOverflowWidgets: true,
141
+ overviewRulerBorder: false,
142
+ overviewRulerLanes: 0,
143
+ hideCursorInOverviewRuler: true,
144
+ renderLineHighlight: 'all',
145
+ selectOnLineNumbers: true,
146
+ contextmenu: true,
147
+ mouseWheelZoom: true,
148
+ quickSuggestions: false,
149
+ suggestOnTriggerCharacters: false,
150
+ acceptSuggestionOnEnter: 'on',
151
+ tabCompletion: 'on',
152
+ wordBasedSuggestions: 'off',
153
+ parameterHints: {
154
+ enabled: false
155
+ },
156
+ insertSpaces: true,
157
+ tabSize: 4
158
+ }}
159
+ />
160
+ </Box>
161
+ </Box>
162
+ );
163
+ };
@@ -0,0 +1,38 @@
1
+ import type React from "react"
2
+
3
+ import {
4
+ Toaster as ChakraToaster,
5
+ Portal,
6
+ Spinner,
7
+ Stack,
8
+ Toast,
9
+ } from "@chakra-ui/react"
10
+ import { bujangToaster as toaster } from "../toast"
11
+
12
+ export const BujangToaster = (): React.ReactElement => {
13
+ return (
14
+ <Portal>
15
+ <ChakraToaster toaster={toaster} insetInline={{ mdDown: "4" }}>
16
+ {(toast) => (
17
+ <Toast.Root width={{ md: "sm" }}>
18
+ {toast.type === "loading" ? (
19
+ <Spinner size="sm" color="blue.solid" />
20
+ ) : (
21
+ <Toast.Indicator />
22
+ )}
23
+ <Stack gap="1" flex="1" maxWidth="100%">
24
+ {toast.title && <Toast.Title>{toast.title}</Toast.Title>}
25
+ {toast.description && (
26
+ <Toast.Description>{toast.description}</Toast.Description>
27
+ )}
28
+ </Stack>
29
+ {toast.action && (
30
+ <Toast.ActionTrigger>{toast.action.label}</Toast.ActionTrigger>
31
+ )}
32
+ {toast.closable && <Toast.CloseTrigger />}
33
+ </Toast.Root>
34
+ )}
35
+ </ChakraToaster>
36
+ </Portal>
37
+ )
38
+ }
@@ -0,0 +1,52 @@
1
+ import { Tooltip as ChakraTooltip, Portal } from "@chakra-ui/react"
2
+ import * as React from "react"
3
+
4
+ export interface TooltipProps extends ChakraTooltip.RootProps {
5
+ showArrow?: boolean
6
+ portalled?: boolean
7
+ portalRef?: React.RefObject<HTMLElement | null>
8
+ content: React.ReactNode
9
+ contentProps?: ChakraTooltip.ContentProps
10
+ disabled?: boolean
11
+ }
12
+
13
+ export const Tooltip = React.forwardRef<HTMLDivElement, TooltipProps>(
14
+ function Tooltip(props, ref) {
15
+ const {
16
+ showArrow,
17
+ children,
18
+ disabled,
19
+ portalled = true,
20
+ content,
21
+ contentProps,
22
+ portalRef,
23
+ ...rest
24
+ } = props
25
+
26
+
27
+
28
+ if (disabled) return children
29
+
30
+ return (
31
+ <ChakraTooltip.Root {...rest}>
32
+ <ChakraTooltip.Trigger asChild>{children}</ChakraTooltip.Trigger>
33
+ <Portal disabled={!portalled} container={portalRef}>
34
+ <ChakraTooltip.Positioner>
35
+ <ChakraTooltip.Content
36
+ ref={ref}
37
+ {...contentProps}
38
+ padding="10px"
39
+ >
40
+ {showArrow && (
41
+ <ChakraTooltip.Arrow>
42
+ <ChakraTooltip.ArrowTip />
43
+ </ChakraTooltip.Arrow>
44
+ )}
45
+ {content}
46
+ </ChakraTooltip.Content>
47
+ </ChakraTooltip.Positioner>
48
+ </Portal>
49
+ </ChakraTooltip.Root>
50
+ )
51
+ },
52
+ )
@@ -0,0 +1,3 @@
1
+ export const NO_JOB_ID = "-";
2
+ export const NO_JOB_STATE = "-";
3
+ export const NO_JR_JOB_ID = "-";
@@ -0,0 +1,106 @@
1
+ import React, { createContext, useContext, useEffect, useMemo } from 'react';
2
+ import { configureBujangApi, DEFAULT_API_BASE } from './api';
3
+ import type { BujangHttpClient } from './api';
4
+ import { createBujangPaths } from './paths';
5
+ import type { BujangPaths } from './paths';
6
+ import { setBujangToastHandler } from './toast';
7
+ import type { BujangToastHandler } from './toast';
8
+ import { BujangToaster } from './components/toaster';
9
+
10
+ /** Result of the optional host "push job data" action shown on the job logs page. */
11
+ export interface PushJobDataResult {
12
+ status: string;
13
+ [key: string]: unknown;
14
+ }
15
+
16
+ export interface BujangProviderProps {
17
+ /** Prefix of the bujang HTTP routes. Default "/api/slurm". */
18
+ apiBase?: string;
19
+ /** Axios instance used for every request. apiBase is joined to its baseURL. */
20
+ axios?: BujangHttpClient;
21
+ /** Where the host mounted the views (same value as `bujangRoutes({ basePath })`). Default "". */
22
+ basePath?: string;
23
+ /** Override some or all URL builders (defaults derive from basePath). */
24
+ paths?: Partial<BujangPaths>;
25
+ /** Toast handler. When omitted bujang renders its own Chakra toaster. */
26
+ toast?: BujangToastHandler;
27
+ /** Page title hook, called by every view with its title. Default sets document.title. */
28
+ usePageTitle?: (title: string) => void;
29
+ /** Suffix of the default document.title ("<title> - <suffix>"). Default "bujang". */
30
+ titleSuffix?: string;
31
+ /** Force the Monaco editor theme. Default follows the `dark` class / data-theme on <html>. */
32
+ colorMode?: 'light' | 'dark';
33
+ /**
34
+ * Optional host action rendered as a "Push Data" button on the job logs page
35
+ * (e.g. to push job results to a database).
36
+ */
37
+ pushJobData?: (jrJobId: string) => Promise<PushJobDataResult>;
38
+ children?: React.ReactNode;
39
+ }
40
+
41
+ export interface BujangContextValue {
42
+ apiBase: string;
43
+ paths: BujangPaths;
44
+ usePageTitle?: (title: string) => void;
45
+ titleSuffix: string;
46
+ colorMode?: 'light' | 'dark';
47
+ pushJobData?: (jrJobId: string) => Promise<PushJobDataResult>;
48
+ }
49
+
50
+ const defaultContext: BujangContextValue = {
51
+ apiBase: DEFAULT_API_BASE,
52
+ paths: createBujangPaths(),
53
+ titleSuffix: 'bujang',
54
+ };
55
+
56
+ const BujangContext = createContext<BujangContextValue>(defaultContext);
57
+
58
+ export function BujangProvider({
59
+ apiBase = DEFAULT_API_BASE,
60
+ axios,
61
+ basePath = '',
62
+ paths,
63
+ toast,
64
+ usePageTitle,
65
+ titleSuffix = 'bujang',
66
+ colorMode,
67
+ pushJobData,
68
+ children,
69
+ }: BujangProviderProps): React.ReactElement {
70
+ // Configure synchronously so the children's first queries use it.
71
+ configureBujangApi({ apiBase, axios });
72
+ setBujangToastHandler(toast);
73
+
74
+ useEffect(() => {
75
+ configureBujangApi({ apiBase, axios });
76
+ setBujangToastHandler(toast);
77
+ return () => {
78
+ configureBujangApi();
79
+ setBujangToastHandler(undefined);
80
+ };
81
+ }, [apiBase, axios, toast]);
82
+
83
+ const value = useMemo<BujangContextValue>(() => ({
84
+ apiBase,
85
+ paths: { ...createBujangPaths(basePath), ...paths },
86
+ usePageTitle,
87
+ titleSuffix,
88
+ colorMode,
89
+ pushJobData,
90
+ }), [apiBase, basePath, paths, usePageTitle, titleSuffix, colorMode, pushJobData]);
91
+
92
+ return (
93
+ <BujangContext.Provider value={value}>
94
+ {!toast && <BujangToaster />}
95
+ {children}
96
+ </BujangContext.Provider>
97
+ );
98
+ }
99
+
100
+ export function useBujang(): BujangContextValue {
101
+ return useContext(BujangContext);
102
+ }
103
+
104
+ export function useBujangPaths(): BujangPaths {
105
+ return useContext(BujangContext).paths;
106
+ }
@@ -0,0 +1,31 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { useBujang } from '../context';
3
+
4
+ const detectDark = (): boolean => {
5
+ if (typeof document === 'undefined') return false;
6
+ const el = document.documentElement;
7
+ return (
8
+ el.classList.contains('dark') ||
9
+ el.getAttribute('data-theme') === 'dark' ||
10
+ el.style.colorScheme === 'dark'
11
+ );
12
+ };
13
+
14
+ /** 'dark' | 'light', from the provider override or the <html> class / data-theme (next-themes, Chakra). */
15
+ export function useColorMode(): { colorMode: 'light' | 'dark' } {
16
+ const { colorMode: forced } = useBujang();
17
+ const [dark, setDark] = useState(detectDark);
18
+
19
+ useEffect(() => {
20
+ if (forced || typeof MutationObserver === 'undefined') return;
21
+ const observer = new MutationObserver(() => setDark(detectDark()));
22
+ observer.observe(document.documentElement, {
23
+ attributes: true,
24
+ attributeFilter: ['class', 'data-theme', 'style'],
25
+ });
26
+ setDark(detectDark());
27
+ return () => observer.disconnect();
28
+ }, [forced]);
29
+
30
+ return { colorMode: forced ?? (dark ? 'dark' : 'light') };
31
+ }
@@ -0,0 +1,21 @@
1
+ import { useEffect } from 'react';
2
+ import { useBujang } from '../context';
3
+
4
+ function useDocumentTitle(title: string | null, suffix: string) {
5
+ useEffect(() => {
6
+ if (title === null) return;
7
+ const previous = document.title;
8
+ document.title = title ? `${title} - ${suffix}` : suffix;
9
+ return () => {
10
+ document.title = previous;
11
+ };
12
+ }, [title, suffix]);
13
+ }
14
+
15
+ /** Sets the page title through the host hook when provided, else document.title. */
16
+ export const usePageTitle = (title: string): void => {
17
+ const { usePageTitle: hostHook, titleSuffix } = useBujang();
18
+ useDocumentTitle(hostHook ? null : title, titleSuffix);
19
+ // The host hook is expected to stay the same for the provider's lifetime.
20
+ hostHook?.(title);
21
+ };