<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/html/canvas/resources/canvas-tests.js"></script>
<link rel="help" href="https://html.spec.whatwg.org/#dom-canvas-transfercontroltooffscreen">

<script id="myWorker" type="text/worker">

function testSize(offscreenCanvas)
{
    if (offscreenCanvas.width == 100 && offscreenCanvas.height == 50)
        return true;
    return false;
}

self.onmessage = function(e) {
    switch (e.data.msg) {
        case 'test1':
            self.postMessage(testSize(e.data.data));
            break;
        case 'test2':
            self.postMessage("");
            break;
        case 'test3':
            self.postMessage("");
            break;
    }
};

</script>

<script>
function makeWorker(script)
{
    var blob = new Blob([script]);
    return new Worker(URL.createObjectURL(blob));
}

async_test(function(t) {
    var placeholder = document.createElement('canvas');
    placeholder.width = 100;
    placeholder.height = 50;
    var offscreenCanvas = placeholder.transferControlToOffscreen();
    var worker = makeWorker(document.getElementById("myWorker").textContent);
    worker.addEventListener('message', t.step_func_done(function(msg) {
        assert_true(msg.data);
    }));
    worker.postMessage({msg: 'test1', data: offscreenCanvas}, [offscreenCanvas]);
}, "Test that an OffscreenCanvas generated by transferControlToOffscreen gets correct width and height when it is transferred to a worker");

async_test(function(t) {
    var placeholder = document.createElement('canvas');
    placeholder.width = 100;
    placeholder.height = 50;
    var offscreenCanvas = placeholder.transferControlToOffscreen();
    var worker = makeWorker(document.getElementById("myWorker").textContent);
    worker.addEventListener('message', t.step_func_done(function(msg) {
        assert_throws_dom("InvalidStateError", function() { placeholder.getContext('2d'); });
    }));
    worker.postMessage({msg: 'test2', data: offscreenCanvas}, [offscreenCanvas]);
}, "Test that calling getContext on a placeholder canvas that is transferred its control to an OffscreenCanvas throws an exception, when the OffscreenCanvas is transferred to a worker");

async_test(function(t) {
    var placeholder = document.createElement('canvas');
    placeholder.width = 100;
    placeholder.height = 50;
    var offscreenCanvas = placeholder.transferControlToOffscreen();
    var worker = makeWorker(document.getElementById("myWorker").textContent);
    worker.addEventListener('message', t.step_func_done(function(msg) {
        assert_throws_dom("InvalidStateError", function() { placeholder.transferControlToOffscreen(); });
    }));
    worker.postMessage({msg: 'test3', data: offscreenCanvas}, [offscreenCanvas]);
}, "Test that calling transferControlToOffscreen twice throws an exception, when its associated OffscreenCanvas is transferred to a worker");

</script>

