aboutsummaryrefslogtreecommitdiff
path: root/src/fields/URLField.ts
blob: 87334ad1644e92ccb044f0dfc90233a0812b16b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Deserializable } from '../client/util/SerializationHelper';
import { serializable, custom } from 'serializr';
import { ObjectField } from './ObjectField';
import { ToScriptString, ToString, Copy, ToJavascriptString } from './FieldSymbols';
import { scriptingGlobal } from '../client/util/ScriptingGlobals';
import { Utils } from '../Utils';

function url() {
    return custom(
        function (value: URL) {
            return value?.origin === window.location.origin ? value.pathname : value?.href;
        },
        function (jsonValue: string) {
            return new URL(jsonValue, window.location.origin);
        }
    );
}

export abstract class URLField extends ObjectField {
    @serializable(url())
    readonly url: URL;

    constructor(url: string);
    constructor(url: URL);
    constructor(url: URL | string) {
        super();
        if (typeof url === 'string') {
            url = url.startsWith('http') ? new URL(url) : new URL(url, window.location.origin);
        }
        this.url = url;
    }

    [ToScriptString]() {
        if (Utils.prepend(this.url?.pathname) === this.url?.href) {
            return `new ${this.constructor.name}("${this.url.pathname}")`;
        }
        return `new ${this.constructor.name}("${this.url?.href}")`;
    }
    [ToJavascriptString]() {
        if (Utils.prepend(this.url?.pathname) === this.url?.href) {
            return `new ${this.constructor.name}("${this.url.pathname}")`;
        }
        return `new ${this.constructor.name}("${this.url?.href}")`;
    }
    [ToString]() {
        if (Utils.prepend(this.url?.pathname) === this.url?.href) {
            return this.url.pathname;
        }
        return this.url?.href;
    }

    [Copy](): this {
        return new (this.constructor as any)(this.url);
    }
}

export const nullAudio = 'https://actions.google.com/sounds/v1/alarms/beep_short.ogg';

@scriptingGlobal
@Deserializable('audio')
export class AudioField extends URLField {}
@scriptingGlobal
@Deserializable('image')
export class ImageField extends URLField {}
@scriptingGlobal
@Deserializable('video')
export class VideoField extends URLField {}
@scriptingGlobal
@Deserializable('pdf')
export class PdfField extends URLField {}
@scriptingGlobal
@Deserializable('web')
export class WebField extends URLField {}
@scriptingGlobal
@Deserializable('csv')
export class CsvField extends URLField {}
@scriptingGlobal
@Deserializable('youtube')
export class YoutubeField extends URLField {}