Skip to content

Commit f041efb

Browse files
miyukocwhitequark
authored andcommitted
React to URL fragment changes while the app is open.
1 parent a3fe2cb commit f041efb

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/app.tsx

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ async function decodeShareFragment(hashQuery: string): Promise<SharePayload> {
103103
}
104104
}
105105

106-
async function stealHashQuery() {
106+
function stealHashQuery() {
107107
const { hash } = window.location;
108108
if (hash !== '') {
109109
history.replaceState(null, '', ' '); // remove #... from URL entirely
@@ -116,8 +116,6 @@ async function stealHashQuery() {
116116
}
117117
}
118118

119-
const query: { av?: string, s?: string } | undefined = await stealHashQuery();
120-
121119
interface TerminalChunk {
122120
stream: 'stdout' | 'stderr';
123121
text: string;
@@ -128,6 +126,8 @@ function TerminalOutput(key: string, output: TerminalChunk[]) {
128126
<span key={`${key}-${index}`} className={`terminal-${chunk.stream}`}>{chunk.text}</span>);
129127
}
130128

129+
const query = await stealHashQuery();
130+
131131
function AppContent() {
132132
const {mode, setMode} = useColorScheme();
133133
useEffect(() => monaco.editor.setTheme(mode === 'light' ? 'vs' : 'vs-dark'), [mode]);
@@ -162,6 +162,33 @@ function AppContent() {
162162
const verilogProductEditorState = useRef(new EditorState(verilogProduct, null, 'verilog'));
163163
useEffect(() => { verilogProductEditorState.current.text = verilogProduct ?? ''; }, [verilogProduct]);
164164

165+
const processSharePayload = React.useCallback((payload: SharePayload) => {
166+
setAmaranthVersion(payload.av);
167+
amaranthSourceEditorState.current.text = payload.s;
168+
if (activeTab === 'tutorial') {
169+
setActiveTab('amaranth-source');
170+
}
171+
}, [activeTab]);
172+
173+
const processSharePayloadRef = useRef(processSharePayload);
174+
processSharePayloadRef.current = processSharePayload;
175+
176+
useEffect(() => {
177+
let listener_ac = new AbortController();
178+
let handler_ac: AbortController | undefined;
179+
window.addEventListener('hashchange', async () => {
180+
handler_ac?.abort();
181+
handler_ac = new AbortController();
182+
let result = await stealHashQuery();
183+
handler_ac.signal.throwIfAborted();
184+
if (result) processSharePayloadRef.current(result);
185+
}, { signal: listener_ac.signal });
186+
return () => {
187+
listener_ac.abort();
188+
handler_ac?.abort();
189+
};
190+
}, []);
191+
165192
function loadDemoCode() {
166193
amaranthSourceEditorState.current.text = data.demoCode[amaranthVersion];
167194
setActiveTab('amaranth-source');

0 commit comments

Comments
 (0)