ANSI escapes working in some semblence

This commit is contained in:
Gnarwhal 2024-09-17 07:11:54 +00:00
parent a698136493
commit 19cf7246e8
Signed by: Gnarwhal
GPG key ID: 0989A73D8C421174
8 changed files with 184 additions and 23 deletions

View file

@ -2,29 +2,58 @@
import { useState, useEffect } from 'react'
import Error from './types/error';
import Image from './types/image';
import Text from './types/text';
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;
}
export default function Content({ src }: { src: string}) {
const [content, set_content] = useState();
type ContentType<T> = {
matcher: RegExp,
emit: () => undefined | Processor<T>,
};
type Processor<T> = {
process: (response: Response) => Promise<T>,
postprocess: (data: T) => undefined,
};
const recognized_types: ContentType<Any>[] = [{
matcher: /image\/\w+/,
content_type: /image\/\w+/,
emit: () => {
set_content(<Image src={src} />);
},
}, {
matcher: /text\/\w+/,
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)/,
emit: () => {
return {
process: (response: Response) => {
@ -42,8 +71,8 @@ export default function Content({ src }: { src: string}) {
const result = fetch(src)
.then(response => {
const content_type = response.headers.get('Content-Type').split(';')[0];
for (let type of recognized_types) {
if (type.matcher.test(content_type)) {
for (const type of recognized_types) {
if (type.content_type.test(content_type)) {
const emitted = type.emit();
if (emitted != undefined) {
result.then(emitted.postprocess);
@ -52,7 +81,10 @@ export default function Content({ src }: { src: string}) {
return;
}
}
set_content(<Error content_type={content_type} />);
set_content(<ContentTypeError content_type={content_type} />);
})
.catch(err => {
set_content(<NetworkError err={err} />);
});
}
}, []);