motto/src/app/[...file]/content.tsx

94 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-09-16 19:44:19 +00:00
'use client'
import { useState, useEffect } from 'react'
2024-09-17 07:11:54 +00:00
import NetworkError from './types/error/network';
import ContentTypeError from './types/error/content_type';
import Image from './types/image';
import Terminal from './types/terminal';
import Text from './types/text';
type ContentType<T> = {
content_type: RegExp,
extension: RegExp,
emit: () => undefined | Processor<T>,
};
type Processor<T> = {
process: (response: Response) => Promise<T>,
postprocess: (data: T) => undefined,
};
function not_match(regex: RegExp | undefined, str: string) {
return !(regex ?? /(?:)/).test(str);
}
function is_type(response: Response, type: ContentType<Any>) {
if (not_match(type.content_type, response.headers.get('Content-Type').split(';')[0])) {
return false;
} else if (not_match(type.path, window.location.pathname)) {
return false;
}
return true;
}
2024-09-16 19:44:19 +00:00
export default function Content({ src }: { src: string}) {
const [content, set_content] = useState();
const recognized_types: ContentType<Any>[] = [{
2024-09-17 07:11:54 +00:00
content_type: /image\/\w+/,
2024-09-16 19:44:19 +00:00
emit: () => {
set_content(<Image src={src} />);
},
}, {
2024-09-17 07:11:54 +00:00
content_type: /application\/octet-stream/,
path: /.*\.term/,
emit: () => {
return {
process: (response: Response) => {
return response.text();
},
postprocess: (data: string) => {
set_content(<Terminal text={data} />);
}
};
}
}, {
content_type: /(text\/\w+)|(application\/octet-stream)/,
2024-09-16 19:44:19 +00:00
emit: () => {
return {
process: (response: Response) => {
return response.text();
},
postprocess: (data: string) => {
set_content(<Text text={data} />);
}
};
}
}];
useEffect(() => {
if (content == undefined) {
const result = fetch(src)
.then(response => {
const content_type = response.headers.get('Content-Type').split(';')[0];
2024-09-17 07:11:54 +00:00
for (const type of recognized_types) {
if (type.content_type.test(content_type)) {
2024-09-16 19:44:19 +00:00
const emitted = type.emit();
if (emitted != undefined) {
result.then(emitted.postprocess);
return emitted.process(response);
}
return;
}
}
2024-09-17 07:11:54 +00:00
set_content(<ContentTypeError content_type={content_type} />);
})
.catch(err => {
set_content(<NetworkError err={err} />);
2024-09-16 19:44:19 +00:00
});
}
}, []);
return content ?? <p>Loading...</p>;
}