summary refs log tree commit diff
path: root/client/static/main.js
blob: 25ac3bd97e187a3892ec05f47cc1028d8a1140c7 (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
$(document).ready(function() {
    const form = $('#form');
    form.on('submit', onFormSubmit);
    form.attr("novalidate",true);
    $('#url').on({'input': inputUpdate, 'paste': pasteTrim});
    inputUpdate();
});

function onFormSubmit() {
    const urlField = $('#url');
    if (validateURL(urlField.val())) {
        const data = JSON.stringify({'url': 'https://' + urlField.val()});
        $.ajax('/', {method: 'POST', data: data, contentType: 'application/json'}).then(function (r) {
            urlField.val('sho.rest/' + r.hash);
        })
    }
    return false;
}

function inputUpdate() {
    const userInput = $('#url').val();
    setButtonVisible(validateURL(userInput));
}

function setButtonVisible(visible) {
    const form = $('#form');

    if (!form[0].hasAttribute('disabled') === visible) return;

    const valuesDisabled = {borderColor: '#FFBCBC', borderRight: 'none', buttonValue: '', buttonValueColor: '#FFFFFF'};
    const valuesEnabled = {borderColor: '#E0E0E0', borderRight: '', buttonValue: '→', buttonValueColor: '#727272'};

    const btn = $('#btn');
    const left = $('#left');
    const formGroup = $('#form-group');

    const values = visible ? valuesEnabled : valuesDisabled;
    if (visible) {
        const values = valuesEnabled;
        form.removeAttr('disabled');
    } else {
        const values = valuesDisabled;
        form[0].setAttribute('disabled', '');
    }

    formGroup.css('border-color', values.borderColor);
    left.css('border-right', values.borderRight);
    btn.css('color', values.buttonValueColor);
    btn.val(values.buttonValue);

}

function pasteTrim() {
    const pattern = /^https?:\/\//;
    setTimeout(() => {
        const element = $('#url');
        element.value = element.value.replace(pattern, '');
    }, 0);
}

function validateURL(url) {
    return !validate({website: 'https://' + url}, {website: {url: true}});
}