Title: [247664] trunk/Tools
Revision
247664
Author
[email protected]
Date
2019-07-19 18:15:26 -0700 (Fri, 19 Jul 2019)

Log Message

Move Ref.js to WebKit to support resultsdbpy's frontend
https://bugs.webkit.org/show_bug.cgi?id=199956

Patch by Zhifei Fang <[email protected]> on 2019-07-19
Reviewed by Jonathan Bedard.

* resultsdbpy/resultsdbpy/view/static/js/drawer.js:
* resultsdbpy/resultsdbpy/view/static/js/search.js:
* resultsdbpy/resultsdbpy/view/static/js/timeline.js:
* resultsdbpy/resultsdbpy/view/static/library/js/Ref.js: Added.
* resultsdbpy/resultsdbpy/view/static/library/js/Utils.js: Added.
* resultsdbpy/resultsdbpy/view/static/library/js/components/BaseComponents.js: Added.
* resultsdbpy/resultsdbpy/view/static/library/js/components/TimelineComponents.js: Added.
* resultsdbpy/resultsdbpy/view/templates/base.html:
* resultsdbpy/resultsdbpy/view/templates/commits.html:
* resultsdbpy/resultsdbpy/view/templates/documentation.html:
* resultsdbpy/resultsdbpy/view/templates/search.html:
* resultsdbpy/resultsdbpy/view/templates/suite_results.html:
* resultsdbpy/resultsdbpy/view/view_routes.py:

Modified Paths

Added Paths

Diff

Modified: trunk/Tools/ChangeLog (247663 => 247664)


--- trunk/Tools/ChangeLog	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/ChangeLog	2019-07-20 01:15:26 UTC (rev 247664)
@@ -1,3 +1,24 @@
+2019-07-19  Zhifei Fang  <[email protected]>
+
+        Move Ref.js to WebKit to support resultsdbpy's frontend
+        https://bugs.webkit.org/show_bug.cgi?id=199956
+
+        Reviewed by Jonathan Bedard.
+
+        * resultsdbpy/resultsdbpy/view/static/js/drawer.js:
+        * resultsdbpy/resultsdbpy/view/static/js/search.js:
+        * resultsdbpy/resultsdbpy/view/static/js/timeline.js:
+        * resultsdbpy/resultsdbpy/view/static/library/js/Ref.js: Added.
+        * resultsdbpy/resultsdbpy/view/static/library/js/Utils.js: Added.
+        * resultsdbpy/resultsdbpy/view/static/library/js/components/BaseComponents.js: Added.
+        * resultsdbpy/resultsdbpy/view/static/library/js/components/TimelineComponents.js: Added.
+        * resultsdbpy/resultsdbpy/view/templates/base.html:
+        * resultsdbpy/resultsdbpy/view/templates/commits.html:
+        * resultsdbpy/resultsdbpy/view/templates/documentation.html:
+        * resultsdbpy/resultsdbpy/view/templates/search.html:
+        * resultsdbpy/resultsdbpy/view/templates/suite_results.html:
+        * resultsdbpy/resultsdbpy/view/view_routes.py:
+
 2019-07-19  Carlos Alberto Lopez Perez  <[email protected]>
 
         [webkitpy] Allow the testrunner driver to setup the environment completely without needing to start the server process.

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/drawer.js (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/drawer.js	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/drawer.js	2019-07-20 01:15:26 UTC (rev 247664)
@@ -21,7 +21,7 @@
 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 // THE POSSIBILITY OF SUCH DAMAGE.
 
-import {DOM, REF} from '/library/ref.js';
+import {DOM, REF} from '/library/js/Ref.js';
 import {QueryModifier} from '/assets/js/common.js';
 import {Configuration} from '/assets/js/configuration.js'
 
@@ -95,7 +95,7 @@
                     return `<option selected value="${branch}">${branch}</option>`;
                 return `<option value="${branch}">${branch}</option>`;
             }).join('');
-        }, 
+        },
     });
 
     fetch('api/commits/branches').then(response => {
@@ -269,7 +269,7 @@
                                 </label>
                             </div>`;
                     }).join('')}`);
-            }, 
+            },
         });
         configurationsDefinedCallbacks.push(() => {
             ref.setState(configurations);

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/search.js (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/search.js	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/search.js	2019-07-20 01:15:26 UTC (rev 247664)
@@ -21,7 +21,7 @@
 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 // THE POSSIBILITY OF SUCH DAMAGE.
 
-import {DOM, REF} from '/library/ref.js';
+import {DOM, REF} from '/library/js/Ref.js';
 import {QueryModifier, paramsToQuery} from '/assets/js/common.js';
 
 const LIMIT = 10;

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/timeline.js (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/timeline.js	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/static/js/timeline.js	2019-07-20 01:15:26 UTC (rev 247664)
@@ -24,7 +24,7 @@
 import {CommitBank} from '/assets/js/commit.js';
 import {Configuration} from '/assets/js/configuration.js';
 import {deepCompare, ErrorDisplay, paramsToQuery, queryToParams} from '/assets/js/common.js';
-import {DOM, REF} from '/library/ref.js';
+import {DOM, REF} from '/library/js/Ref.js';
 
 
 const DEFAULT_LIMIT = 100;
@@ -420,7 +420,7 @@
                 }
                 --currentCommitIndex;
             }
-            
+
         }
 
         repositories = [...repositories];

Added: trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/Ref.js (0 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/Ref.js	                        (rev 0)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/Ref.js	2019-07-20 01:15:26 UTC (rev 247664)
@@ -0,0 +1,455 @@
+// Copyright (C) 2019 Apple Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1.  Redistributions of source code must retain the above copyright
+//     notice, this list of conditions and the following disclaimer.
+// 2.  Redistributions in binary form must reproduce the above copyright
+//     notice, this list of conditions and the following disclaimer in the
+//     documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS "AS IS" AND
+// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
+// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+function uuidv4() {
+    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
+        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
+    )
+}
+
+const TRACE_STATE = false;
+
+class Signal {
+    constructor(handlers) {
+        this.handlers = handlers ? handlers : [];
+        this.maxinumRunTime = 1 / 30 * 1000;
+    }
+    addListener(fn) {
+        if (!fn) return this;
+        this.handlers.push(fn);
+        return this;
+    }
+    removeListener(fn) {
+        const removeIndex = 0;
+        this.handlers.forEach((handler, index) => {
+            if (handler === fn)
+                removeIndex = index;
+        });
+        this.handler.splice(removeIndex, 1);
+        return this;
+    }
+    removeAllListener() {
+        this.handlers = [];
+        return this;
+    }
+    emit(...args) {
+        if (this.handlers) {
+            this.requestEmit(0, ...args);
+        }
+        return this;
+    }
+    requestEmit(from, ...args) {
+        return new Promise(resolve => {
+            setTimeout(() => {
+                const startedTime = new Date().getTime();
+                // Run as many handlers as posible
+                let i = from;
+                for (; i < this.handlers.length; i++) {
+                    this.handlers[i](...args);
+                    const endTime = new Date().getTime();
+                    if (endTime - startedTime >= this.maxinumRunTime) {
+                        this.requestEmit(i+1, ...args).then(() => resolve());
+                        break;
+                    }
+                }
+                if (i === this.handlers.length) {
+                    resolve();
+                }
+            });
+        });
+    }
+}
+
+class EventStream {
+    constructor(signal) {
+        this.signal = signal ? signal : new Signal();
+        this.errorSignal = new Signal();
+        this.stopSignal = new Signal();
+        this.lastValue = null;
+    }
+    action(fn) {
+        this.signal.addListener(fn);
+        return this;
+    }
+    error(fn) {
+        this.errorSignal.addListener(fn);
+        return this;
+    }
+    stop() {
+        this.signal.removeAllListener();
+        this.errorSignal.removeAllListener();
+        this.stopSignal.emit();
+        return this;
+    }
+    onStop(fn) {
+        this.stopSignal.addListener(fn);
+        return this;
+    }
+    add(...args) {
+        this.lastValue = args;
+        this.signal.emit(...args);
+        return this;
+    }
+    getLastValue() {
+        return this.lastValue;
+    }
+    replayLast() {
+        const lastValue = this.getLastValue();
+        if (lastValue)
+            this.add(...lastValue);
+    }
+    addPromise(p) {
+        let that = this;
+        p.then((...args) => {
+            that.add(...args);
+        }).catch((...args) => {
+            that.addError(...args);
+        });
+    }
+    addError(...args) {
+        this.errorSignal.emit(...args);
+    }
+    addWithDelay(delay, ...args) {
+        setTimeout(() => {
+            console.log(args);
+            this.add(...args);
+        }, delay);
+        return this;
+    }
+    filter(filterFn) {
+        const res = new EventStream();
+        this.action((...args) => {
+            if (filterFn(...args))
+                res.add(...args);
+        });
+        return res;
+    }
+    remains(filterFn) {
+        const res = new EventStream();
+        this.action((...args) => {
+            if (!filterFn(...args))
+                res.add(...args);
+        });
+        return res;
+    }
+    map(fn) {
+        const res = new EventStream();
+        this.action((...args) => {
+            res.add(fn(...args));
+        });
+        return res;
+    }
+    scan(fn) {
+        const res = new EventStream();
+        let accumulator = null;
+        this.action((...args) => {
+            accumulator = fn(accumulator, ...args);
+            res.add(accumulator);
+        });
+        return res;
+    }
+    flatMap(fn) {
+        const res = new EventStream();
+        this.action((...args) => {
+            fn(res)(...args);
+        });
+        return res;
+    }
+    inject(es, ...args) {
+        return this.action(() => {
+            es.add(...args);
+        });
+    }
+    static merge(...args) {
+        const res = new EventStream();
+        Array.prototype.forEach.call(args, ((stream) => {
+            stream.action(() => {
+                res.add(...args);
+            });
+        }));
+        return res;
+    }
+    static fromMonitor(fn, interval, initial) {
+        const res = new EventStream();
+        let handler = null;
+        let result = initial;
+        res.onStop(() => {
+            clearTimeout(handler);
+        });
+        const poll = () => {
+            result = fn(result);
+            if (result instanceof Promise)
+                res.addPromise(result);
+            else
+                res.add(result);
+            handler = setTimeout(poll, interval);
+        }
+        poll();
+        return res;
+    }
+}
+
+function isMergeableState(state) {
+    return Object.prototype.toString.call(state) === "[object Object]";
+}
+
+function applyStateDiff(state, diff) {
+    if (!diff)
+        return state;
+    if (!isMergeableState(diff))
+        return diff;
+    const res = {};
+    if (state) {
+        Object.keys(state).forEach((key) => {
+            res[key] = state[key];
+        });
+    } else {
+        return state;
+    }
+    if (diff) {
+        Object.keys(diff).forEach((key) => {
+            res[key] = diff[key];
+        });
+    }
+    return res;
+}
+
+class Ref {
+    constructor(config) {
+        this.key = uuidv4();
+        this.element = null;
+        this.lastStateDiff = null;
+        config = config ? config : {};
+        this.stateTracer = config.state !== undefined ? [config.state] : [];
+        this.state = config.state !== undefined ? config.state : {};
+        this._onStateUpdate_ = new Signal().addListener(config.onStateUpdate);
+        this._onElementMount_ = new Signal().addListener(config.onElementMount);
+        this._onElementUnmout_ = new Signal().addListener(config.onElementUnmout);
+    }
+    bind(element) {
+        this.apply(element.querySelector(`[ref="${this.key}"]`));
+    }
+
+    apply(element) {
+        if (!element)
+            return;
+        if (this.element === element)
+            return;
+        if (this.element && this.element !== element)
+            this.onElementUnmout.emit(this.element);
+        this.element = element;
+        //Initial state
+        if (this.state !== undefined && this.state !== null)
+            this.onStateUpdate.emit(this.element, this.state, this.state);
+        this.onElementMount.emit(this.element);
+    }
+    destory(element) {
+        if (!element || element !== this.element)
+            return;
+        this.onElementUnmout.emit(this.element);
+    }
+    toString() {
+        return this.key;
+    }
+    setState(stateDiff) {
+        if (TRACE_STATE)
+            this.stateTracer.push(stateDiff);
+        else
+            this.stateTracer = [stateDiff];
+        this.lastStateDiff = stateDiff;
+        //If element haven't been mount, we just update the state, so that we will only render the finial stat when element mount
+        if (this.element)
+            this.onStateUpdate.emit(this.element, stateDiff, this.state);
+        this.state = applyStateDiff(this.state, stateDiff);
+    }
+    fromEvent(event, ...args) {
+        const res = new EventStream();
+        this.onElementMount.addListener((element) => element.addEventListener(event, (e) => {
+            res.add(e, ...args);
+        }));
+        return res;
+    }
+}
+
+class RefManger {
+    constructor() {
+        this.refs = {};
+    }
+    createRef(config) {
+        const ref = new Ref(config);
+        this.refs[ref.key] = ref;
+        return ref;
+    }
+    bindAll(dom) {
+        const nodeIterator = document.createNodeIterator(
+            dom,
+            NodeFilter.SHOW_ELEMENT,
+            (node) => {
+                    const refKey = node.getAttribute('ref');
+                    const ref = this.refs[refKey];
+                    if (ref)
+                        ref.apply.call(ref,node);
+                    return ref ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
+            }
+        );
+        let currentNode = null;
+        while (currentNode = nodeIterator.nextNode());
+    }
+    unbindAll(dom) {
+        const nodeIterator = document.createNodeIterator(
+            dom,
+            NodeFilter.SHOW_ELEMENT,
+            (node) => {
+                    const refKey = node.getAttribute('ref');
+                    const ref = this.refs[refKey];
+                    if (ref) {
+                        ref.destory.call(ref,node);
+                        delete this.refs[refKey];
+                    }
+                    return ref ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
+            }
+        );
+        let currentNode = null;
+        while (currentNode = nodeIterator.nextNode());
+    }
+}
+
+const REF = new RefManger();
+
+function createDomElementsFromStr(string) {
+    const fakeElement = document.createElement('div');
+    fakeElement.innerHTML = string;
+    const elements = [];
+    Array.prototype.forEach.call(fakeElement.children, (element) => {
+        element.remove();
+        elements.push(element);
+    });
+    return elements;
+}
+
+const DOM = {
+    inject: (element, string) => {
+        REF.unbindAll(element);
+        element.innerHTML = string;
+        REF.bindAll(element);
+    },
+    prepend: (element, string) => {
+        if (element.children.length === 0) {
+            DOM.inject(element, string);
+            return;
+        }
+        DOM.before(element.firstElementChild, string);
+    },
+    append: (element, string) => {
+        if (element.children.length === 0) {
+            DOM.inject(element, string);
+            return;
+        }
+        DOM.after(element.lastElementChild, string);
+    },
+    before: (element, string) => {
+        const elements = createDomElementsFromStr(string);
+        element.before(...elements);
+        elements.forEach((elm) => {
+            REF.bindAll(elm);
+        });
+    },
+    after: (element, string) => {
+        const elements = createDomElementsFromStr(string);
+        element.after(...elements);
+        elements.forEach((elm) => {
+            REF.bindAll(elm);
+        });
+    },
+    replace: (element, string) => {
+        DOM.before(element, string);
+        REF.unbindAll(element);
+        element.remove();
+    },
+    remove: (element) => {
+        REF.unbindAll(element);
+        element.remove();
+    },
+};
+function diff(oldValue, newValue, removeCallback, addCallback, getKey = item => item.toString()) {
+    if (!newValue) return;
+    if (oldValue === newValue) return;
+    if (Array.isArray(oldValue) && Array.isArray(newValue)) {
+        const newArrayMap = new Map();
+        newValue.forEach((item, index) => {
+             newArrayMap.set(getKey(item), {
+                 item: item,
+                 index: index,
+                 oldIndex: -1
+             });
+        });
+        oldValue.forEach((oldItem, index) => {
+            const oldItemKey = getKey(oldItem);
+            if (!newArrayMap.has(oldItemKey))
+                removeCallback(oldItem, index);
+            else {
+                const newEntry = newArrayMap.get(oldItemKey);
+                if (newEntry) {
+                    newEntry.oldIndex = index;
+                    newEntry.item = oldItem;
+                }
+            }
+        });
+        for (let entry of newArrayMap.entries()) {
+            addCallback(entry[1].item, entry[1].index, entry[1].oldIndex);
+        }
+    }
+}
+
+const FP = {
+    composer: (fn) => {
+        // Input function must be a currying function
+        // Composer will compose that currying function call
+        // Making a currying function fn = (a) => (b) => {....} can be called
+        // composer = FP.composer(fn);
+        // composer(a); composer(b);
+        // instead of calling it fn(a)(b);
+        console.assert(typeof fn === "function" && fn.length === 1);
+        let result = fn;
+        return (...args) => {
+            args.forEach(arg => {
+                result = result(arg);
+            });
+        }
+    },
+    currying: (fn) => {
+        // Currying input function
+        // (a, b) => {...}
+        // to
+        // (a) => (b) => {...}
+        const args = [];
+        const returnFn = (x) => {
+            args.push(x);
+            if (args.length === fn.length)
+                return fn(...args);
+            else
+                return returnFn;
+        }
+        return returnFn;
+    }
+}
+export {REF, DOM, diff, FP, EventStream, uuidv4};

Added: trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/Utils.js (0 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/Utils.js	                        (rev 0)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/Utils.js	2019-07-20 01:15:26 UTC (rev 247664)
@@ -0,0 +1,68 @@
+// Copyright (C) 2019 Apple Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1.  Redistributions of source code must retain the above copyright
+//     notice, this list of conditions and the following disclaimer.
+// 2.  Redistributions in binary form must reproduce the above copyright
+//     notice, this list of conditions and the following disclaimer in the
+//     documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS "AS IS" AND
+// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
+// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+function timeDifference(dateString) {
+    const dateDiff = new Date(new Date().getTime() - new Date(dateString).getTime());
+    const hour = dateDiff.getUTCHours();
+    const day = dateDiff.getUTCDate() - 1;
+    const month = dateDiff.getUTCMonth();
+    const year = dateDiff.getUTCFullYear() - 1970;
+    if (hour === 0 && day === 0 && month === 0 && year ===0)
+        return "less than 1 hour ago";
+    if (day === 0 && month === 0 && year === 0)
+        return `${hour} hours ago`;
+    if (month === 0 && year === 0)
+        return `${day} days ${hour} hours ago`;
+    if (year === 0)
+        return `${month} monthes ${day} days ago`;
+    return `${year} years ${month} monthes ago`;
+}
+
+class Cookie {
+    static getCookie(name) {
+        const cookie = document.cookie.match(`${name}=[\w\W]+;`);
+        if (cookie) {
+            const raw = cookie[0].split('=')[1];
+            //escape ';'
+            return decodeURIComponent(raw.substr(0, raw.length - 1));
+        }
+        return null;
+    }
+    static createCookie(name, value, expiredDays=1, path='/') {
+        let expiredTime = new Date();
+        expiredTime.setTime(expiredTime.getTime() + expireDays * 24 * 3600 * 1000);
+        document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expiredTime.toUTCString()}; path=${path}`;
+    }
+    static eraseCookie(name) {
+        if (getCookie(name))
+            document.cookie = `${name}=; Max-Age=-99999999;`
+    }
+}
+
+function isDarkMode () {
+    if (!window.matchMedia) {
+        return false;
+    }
+    const match = window.matchMedia('(prefers-color-scheme: dark)');
+    return match.matches;
+}
+export {timeDifference, isDarkMode, Cookie};

Added: trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/components/BaseComponents.js (0 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/components/BaseComponents.js	                        (rev 0)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/components/BaseComponents.js	2019-07-20 01:15:26 UTC (rev 247664)
@@ -0,0 +1,109 @@
+// Copyright (C) 2019 Apple Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1.  Redistributions of source code must retain the above copyright
+//     notice, this list of conditions and the following disclaimer.
+// 2.  Redistributions in binary form must reproduce the above copyright
+//     notice, this list of conditions and the following disclaimer in the
+//     documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS "AS IS" AND
+// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
+// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import {
+    DOM, REF, diff, EventStream, uuidv4
+}
+from '../js/Ref.js';
+
+function ApplyNewChildren(element, oldArray, newArray, childToKeyFunc, itemProcessor) {
+    const newChildren = [];
+    const needToRemoveChildren = [];
+    diff(oldArray, newArray, (item, index) => {
+            const child = element.children[index];
+            needToRemoveChildren.push(child);
+        },
+        (item, newIndex, oldIndex) => {
+            if (oldIndex !== -1) {
+                const exisitingChild = element.children[oldIndex];
+                newChildren.push(exisitingChild);
+            } else
+                newChildren.push(item);
+        }, childToKeyFunc);
+    newChildren.forEach((child, index) => {
+        if (index < element.children.length) {
+            if (child !== element.children[index]) {
+                if (child instanceof HTMLElement)
+                    element.replaceChild(child, element.children[index]);
+                else
+                    DOM.replace(element.children[index], typeof itemProcessor === "function" ? itemProcessor(child) : child);
+            }
+        } else {
+            if (child instanceof HTMLElement)
+                element.append(child);
+            else
+                DOM.append(element, typeof itemProcessor === "function" ? itemProcessor(child) : child);
+        }
+    });
+    needToRemoveChildren.forEach((child) => {
+        // Clear the ref in the removed child, trigger unmount event
+        DOM.remove(child);
+    });
+}
+
+function ListProvider(exporter, providedInterfaces, ...childrenFunctions) {
+    const ref = REF.createRef({
+        state: {childrenFunctions: childrenFunctions.map(i => i)},
+        onStateUpdate: (element, stateDiff, state) => {
+            if (stateDiff.childrenFunctions) {
+                ApplyNewChildren(element,
+                    state.childrenFunctions, stateDiff.childrenFunctions,
+                    (child) => child.toString(),
+                    (child) => child(...providedInterfaces));
+            }
+        }
+    });
+    if (exporter)
+        exporter(childrenFunctions => {
+            // Make a copy of it, so that DIFF.array works
+            ref.setState({childrenFunctions: childrenFunctions.map(i => i)});
+        });
+    return `<div ref="${ref}">${childrenFunctions.map(childrenFunction => childrenFunction(...providedInterfaces)).join("")}</div>`;
+}
+
+function ListProviderReceiver(contentFunction) {
+    const key = uuidv4();
+    const res = (...providedInterfaces) => contentFunction(...providedInterfaces);
+    // Create unique key for each List Item
+    res.toString = () => key;
+    return res;
+}
+
+// Children compoent will retrun string
+function ListComponent(exporter, ...children) {
+    const ref = REF.createRef({
+        state: {children: children},
+        onStateUpdate: (element, stateDiff, state) => {
+            if (stateDiff.children)
+                ApplyNewChildren(element, state.children, stateDiff.children, a => a);
+        },
+    });
+
+    if (exporter)
+        exporter(children => {
+            // Make a copy of it, so that DIFF.array works
+            ref.setState({children: children.map(i => i)});
+        });
+    return `<div ref="${ref}">${children.join("")}</div>`;
+}
+
+export {ListProvider, ListProviderReceiver, ListComponent};

Added: trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/components/TimelineComponents.js (0 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/components/TimelineComponents.js	                        (rev 0)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/static/library/js/components/TimelineComponents.js	2019-07-20 01:15:26 UTC (rev 247664)
@@ -0,0 +1,771 @@
+// Copyright (C) 2019 Apple Inc. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1.  Redistributions of source code must retain the above copyright
+//     notice, this list of conditions and the following disclaimer.
+// 2.  Redistributions in binary form must reproduce the above copyright
+//     notice, this list of conditions and the following disclaimer in the
+//     documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS "AS IS" AND
+// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
+// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import {
+    DOM, REF, FP, EventStream
+}
+from '../js/Ref.js';
+
+import {isDarkMode} from '../Utils.js';
+import {ListComponent, ListProvider, ListProviderReceiver} from './BaseComponents.js'
+
+function pointCircleCollisionDetact(point, circle) {
+    return Math.pow(point.x - circle.x, 2) + Math.pow(point.y - circle.y, 2) <= circle.radius * circle.radius;
+}
+
+function pointRectCollisionDetect(point, rect) {
+    const diffX = point.x - rect.topLeftX;
+    const diffY = point.y - rect.topLeftY;
+    return diffX <= rect.width && diffY <= rect.height && diffX >= 0 && diffY >= 0;
+}
+
+function getMousePosInCanvas(event, canvas) {
+    const rect = canvas.getBoundingClientRect();
+    return {
+        x: event.clientX - rect.left,
+        y: event.clientY - rect.top,
+    }
+}
+
+function getDevicePixelRatio() {
+    return window.devicePixelRatio;
+}
+
+function setupCanvasWidthWithDpr(canvas, width) {
+    const dpr = getDevicePixelRatio();
+    canvas.style.width = `${width}px`;
+    canvas.width = width * dpr;
+    canvas.logicWidth = width;
+}
+
+function setupCanvasHeightWithDpr(canvas, height) {
+    const dpr = getDevicePixelRatio();
+    canvas.style.height = `${height}px`;
+    canvas.height = height * dpr;
+    canvas.logicHeight = height;
+}
+
+function setupCanvasContextScale(canvas) {
+    const dpr = getDevicePixelRatio();
+    const context = canvas.getContext('2d');
+    context.scale(dpr, dpr);
+}
+
+function XScrollableCanvasProvider(exporter, ...childrenFunctions) {
+    const containerRef = REF.createRef({
+        state: {width: 0},
+        onStateUpdate: (element, stateDiff, state) => {
+            if (stateDiff.width)
+                element.style.width = `${stateDiff.width}px`;
+        },
+    });
+    const scrollRef = REF.createRef({});
+    const scrollEventStream = scrollRef.fromEvent('scroll');
+    const resizeEventStream = new EventStream();
+    window.addEventListener('resize', () => {
+        presenterRef.setState({resize:true});
+    });
+    const resizeContainerWidth = width => {containerRef.setState({width: width})};
+    const presenterRef = REF.createRef({
+        state: {scrollLeft: 0},
+        onElementMount: (element) => {
+            element.style.width = `${element.parentElement.parentElement.offsetWidth}px`;
+            resizeEventStream.add(element.offsetWidth);
+        },
+        onStateUpdate: (element, stateDiff, state) => {
+            if (typeof stateDiff.scrollLeft === 'number')
+                element.style.transform = `translate(${stateDiff.scrollLeft}px, 0)`;
+            if (stateDiff.resize) {
+                element.style.width = `${element.parentElement.parentElement.offsetWidth}px`;
+                resizeEventStream.add(element.offsetWidth);
+            }
+        }
+    });
+    scrollEventStream.action((e) => {
+        // Provide the logic scrollLeft
+        presenterRef.setState({scrollLeft: e.target.scrollLeft});
+    });
+    // Provide parent functions/event to children to use
+
+    return `<div class="content" ref="${scrollRef}">
+        <div ref="${containerRef}">
+            <div ref="${presenterRef}">${
+                ListProvider((updateChildrenFunctions) => {
+                    if (exporter) {
+                        exporter((children) => {
+                            updateChildrenFunctions(children);
+                            // this make sure the newly added children receive current state
+                            resizeEventStream.replayLast();
+                            scrollEventStream.replayLast();
+                        });
+                    }
+                }, [resizeContainerWidth, scrollEventStream, resizeEventStream], ...childrenFunctions)
+            }</div>
+        </div>
+    </div>`;
+}
+
+function offscreenCachedRenderFactory(padding, height) {
+    let cachedScrollLeft = 0;
+    let offscreenCanvas = document.createElement('canvas');
+
+    // This function will call redrawCache to render a offscreen cache
+    // and copy the viewport area from of it
+    // It will trigger redrawCache when cache don't have enough space
+    return (redrawCache, element, stateDiff, state) => {
+        const width = typeof stateDiff.width === 'number' ? stateDiff.width : state.width;
+        if (width <= 0)
+            // Nothing to render
+            return;
+
+        const totalWidth = width + 2 * padding;
+        const scrollLeft = typeof stateDiff.scrollLeft === 'number' ? stateDiff.scrollLeft : state.scrollLeft;
+        const context = element.getContext('2d');
+        let cachePosLeft = scrollLeft - cachedScrollLeft;
+
+        if (element.logicWidth != width) {
+            // Setup the dpr in case of blur
+            setupCanvasWidthWithDpr(element, width);
+
+            // We draw everything on cache
+            redrawCache(offscreenCanvas, element, stateDiff, state, () => {
+                cachedScrollLeft = scrollLeft < padding ? scrollLeft : scrollLeft - padding;
+                cachePosLeft = scrollLeft - cachedScrollLeft;
+                if (cachePosLeft < 0)
+                    cachePosLeft = 0;
+                context.clearRect(0, 0, element.width, element.height);
+                context.drawImage(offscreenCanvas, cachePosLeft * getDevicePixelRatio(), 0,    element.width, element.height, 0, 0, width * getDevicePixelRatio(), element.height);
+            });
+
+        } else if (cachePosLeft < 0 || cachePosLeft + width > totalWidth) {
+            if (scrollLeft < 0 )
+                return;
+            redrawCache(offscreenCanvas, element, stateDiff, state,    () => {
+                cachedScrollLeft = scrollLeft < padding ? scrollLeft : scrollLeft - padding;
+                cachePosLeft = scrollLeft - cachedScrollLeft;
+                if (cachePosLeft < 0)
+                    cachePosLeft = 0;
+                context.clearRect(0, 0, element.width, element.height);
+                context.drawImage(offscreenCanvas, cachePosLeft * getDevicePixelRatio(), 0,    element.width, element.height, 0, 0, width * getDevicePixelRatio(), element.height);
+            });
+        } else {
+            if (cachePosLeft < 0)
+                cachePosLeft = 0;
+            context.clearRect(0, 0, element.width, element.height);
+            context.drawImage(offscreenCanvas, cachePosLeft * getDevicePixelRatio(), 0,    element.width, element.height, 0, 0, width * getDevicePixelRatio(), element.height);
+        }
+    }
+}
+
+// namespace Timeline
+const Timeline = {};
+
+Timeline.CanvasSeriesComponent = (dots, scales, option = {}) => {
+    console.assert(dots.length <= scales.length);
+
+    // Get the css value, this component assume to use with webkit.css
+    const computedStyle = getComputedStyle(document.body);
+    let radius = parseInt(computedStyle.getPropertyValue('--smallSize')) / 2;
+    let fontFamily = computedStyle.getPropertyValue('font-family');
+    let defaultDotColor = computedStyle.getPropertyValue('--greenLight').trim();
+    let defaultEmptyLineColor = computedStyle.getPropertyValue('--grey').trim();
+    let defaultFontSize = computedStyle.getPropertyValue('--tinySize');
+
+    // Get configuration
+    // Default order is left is biggest
+    const reversed = typeof option.reversed === "boolean" ? option.reversed : false;
+    const getScale = typeof option.getScaleFunc === "function" ? option.getScaleFunc : (a) => a;
+    const comp = typeof option.compareFunc === "function" ? option.compareFunc : (a, b) => a - b;
+    const _onDotClick_ = typeof option._onDotClick_ === "function" ? option.onDotClick : null;
+    const _onDotHover_ = typeof option._onDotHover_ === "function" ? option.onDotHover : null;
+    const height = option.height ? option.height : 2 * radius;
+
+    // Draw dot api can be used in user defined render function
+    const drawDot = (context, x, y, isEmpty, tag = null, useRadius, color, emptylineColor) => {
+        useRadius = useRadius ? useRadius : radius;
+        color = color ? color : defaultDotColor;
+        emptylineColor = emptylineColor ? emptylineColor : defaultEmptyLineColor;
+            if (!isEmpty) {
+                //Draw the dot
+                context.arc(x + 3 * radius, y, radius, 0, 2 * Math.PI);
+                context.fillStyle = color;
+                context.fill();
+                if (typeof tag === "number" || typeof tag === "string") {
+                    context.font = `${fontFamily} ${defaultFontSize}px`;
+                    context.fillText(tag, x + 4 * radius, y + radius);
+                }
+            } else {
+                context.beginPath();
+                context.moveTo(x + 2 * radius, y);
+                context.lineTo(x + 4 * radius, y);
+                context.lineWidth = 1;
+                context.strokeStyle = defaultEmptyLineColor;
+                context.stroke();
+            }
+    };
+    const render = typeof option.renderFactory === "function" ? option.renderFactory(drawDot) : (dot, context, x, y) => drawDot(context, x, y, !dot);
+    const sortData = option.sortData === true ? option.sortData : false;
+
+    // Initialize
+    const initDots = dots.map((dot) => dot);
+    const initScales = scales.map((scale) => scale);
+    if (sortData) {
+        initDots.sort((a, b) => comp(getScale(a), getScale(b)));
+        initScales.sort(comp);
+    }
+    const filterDots = (dots) => dots.filter(dot => typeof dot._x === 'number');
+    let inCacheDots = [];
+    const getMouseEventTirggerDots = (e, scrollLeft, element) => {
+        const {x, y} = getMousePosInCanvas(e, element);
+        return inCacheDots.filter(dot => pointCircleCollisionDetact({x, y},
+            {
+                x: dot._dotCenter.x - (scrollLeft - dot._cachedScrollLeft),
+                y: dot._dotCenter.y,
+                radius: radius
+            }));
+    }
+
+    const dotWidth = 3 * 2 * radius;
+    const padding = 100 * dotWidth / getDevicePixelRatio();
+    const offscreenCachedRender = offscreenCachedRenderFactory(padding, radius * 2);
+
+    // Generate the dot cache
+    const redrawCache = (offscreenCanvas, element, stateDiff, state, notifyToRender) => {
+        const scrollLeft = typeof stateDiff.scrollLeft === 'number' ? stateDiff.scrollLeft : state.scrollLeft;
+        const width = typeof stateDiff.width === 'number' ? stateDiff.width : state.width;
+        const totalWidth = width + 2 * padding;
+        const scales = stateDiff.scales ? stateDiff.scales : state.scales;
+        const dots = stateDiff.dots ? stateDiff.dots : state.dots;
+        // This color maybe change when switch dark/light mode
+        const defaultLineColor = getComputedStyle(document.body).getPropertyValue('--borderColorInlineElement');
+        if (offscreenCanvas.logicWidth !== totalWidth) {
+            setupCanvasWidthWithDpr(offscreenCanvas, totalWidth);
+            setupCanvasContextScale(offscreenCanvas);
+        }
+        if (offscreenCanvas.logicHeight !== element.logicHeight) {
+            setupCanvasHeightWithDpr(offscreenCanvas, element.logicHeight);
+            setupCanvasContextScale(offscreenCanvas);
+        }
+
+        const context = offscreenCanvas.getContext("2d");
+        // Clear the cache
+        context.clearRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
+        // Draw the time line
+        context.beginPath();
+        context.moveTo(0, radius);
+        context.lineWidth = 1;
+        context.strokeStyle = defaultLineColor;
+        context.lineTo(totalWidth, radius);
+        context.stroke();
+
+        // Draw the dots
+        // First, Calculate the render range:
+        let startScalesIndex = Math.floor((scrollLeft - padding) / dotWidth);
+        if (startScalesIndex < 0)
+            startScalesIndex = 0;
+        let viewportStartScaleIndex = Math.floor((scrollLeft) / dotWidth);
+        if (viewportStartScaleIndex < 0)
+            viewportStartScaleIndex = 0;
+        let viewportEndScaleIndex = viewportStartScaleIndex + Math.floor((width) / dotWidth);
+        if (viewportEndScaleIndex >= scales.length)
+            viewportEndScaleIndex = scales.length - 1;
+        let endScalesIndex = startScalesIndex + Math.ceil((totalWidth) / dotWidth);
+        if (endScalesIndex >= scales.length)
+            endScalesIndex = scales.length - 1;
+        let currentDotIndex = startScalesIndex - (scales.length - dots.length);
+        if (currentDotIndex < 0)
+            currentDotIndex = 0;
+        for (let i = currentDotIndex; i <= startScalesIndex; i++) {
+            const compResult = comp(scales[startScalesIndex], getScale(dots[currentDotIndex]));
+            if (!reversed) {
+                if (compResult > 0)
+                    currentDotIndex ++;
+                else
+                    break;
+            } else {
+                if (compResult < 0)
+                    currentDotIndex ++;
+                else
+                    break;
+            }
+        }
+
+        // Use this to decrease colision search scope
+        inCacheDots = [];
+
+        // Draw the dots on cache
+        for (let i = startScalesIndex; i <= endScalesIndex; i++) {
+            let x = i * dotWidth - (scrollLeft < padding ? scrollLeft : scrollLeft - padding);
+            if (currentDotIndex < dots.length && comp(scales[i], getScale(dots[currentDotIndex])) === 0) {
+                render(dots[currentDotIndex], context, x, radius);
+                dots[currentDotIndex]._dotCenter = {x: x + 3 * radius, y: radius};
+                dots[currentDotIndex]._cachedScrollLeft = scrollLeft < padding ? scrollLeft : scrollLeft - padding;
+                inCacheDots.push(dots[currentDotIndex]);
+                currentDotIndex += 1;
+            } else
+                render(null, context, x, radius);
+            // We already drawed viewport needed, call notifyToRender to bring them to screen now
+            // this will help to elemate blink
+            if (i === viewportEndScaleIndex)
+                notifyToRender();
+        }
+    };
+
+    const canvasRef = REF.createRef({
+        state: {
+            dots: initDots,
+            scales: initScales,
+            scrollLeft: 0,
+            width: 0,
+        },
+        onElementMount: (element) => {
+            setupCanvasHeightWithDpr(element, radius * 2);
+            setupCanvasContextScale(element);
+            if (onDotClick) {
+                element.addEventListener('click', (e) => {
+                    let dots = getMouseEventTirggerDots(e, canvasRef.state.scrollLeft, element);
+                    if (dots.length)
+                        onDotClick(dots[0], e);
+                });
+            }
+
+            if (onDotClick || onDotHover) {
+                element.addEventListener('mousemove', (e) => {
+                    let dots = getMouseEventTirggerDots(e, canvasRef.state.scrollLeft, element);
+                    if (dots.length) {
+                        if (onDotHover)
+                            onDotHover(dots[0], e);
+                        element.style.cursor = "pointer";
+                    } else
+                        element.style.cursor = "default";
+                });
+            }
+        },
+        onStateUpdate: (element, stateDiff, state) => {
+            const context = element.getContext("2d");
+            if (stateDiff.scales || stateDiff.dots || typeof stateDiff.scrollLeft === 'number' || typeof stateDiff.width === 'number') {
+                console.assert(dots.length <= scales.length);
+                requestAnimationFrame(() => offscreenCachedRender(redrawCache, element, stateDiff, state));
+            }
+        }
+    });
+
+    return ListProviderReceiver((updateContainerWidth, onContainerScroll, onResize) => {
+        updateContainerWidth(scales.length * dotWidth * getDevicePixelRatio());
+        const updateData = (dots, scales) => {
+            updateContainerWidth(scales.length * dotWidth * getDevicePixelRatio());
+            canvasRef.setState({
+                dots: dots,
+                scales: scales,
+            });
+        };
+        if (typeof option.exporter === "function")
+            option.exporter(updateData);
+        onContainerScroll.action((e) => {
+            canvasRef.setState({scrollLeft: e.target.scrollLeft / getDevicePixelRatio()});
+        });
+        onResize.action((width) => {
+            canvasRef.setState({width: width});
+        });
+        return `<div class="series">
+            <canvas ref="${canvasRef}">
+        </div>`;
+    });
+}
+
+Timeline.ExpandableSeriesComponent = (mainSeries, subSerieses, exporter) => {
+    const ref = REF.createRef({
+        state: {expanded: false},
+        onStateUpdate: (element, stateDiff) => {
+            if (stateDiff.expanded === false) {
+                element.children[0].style.display = 'none';
+                element.children[1].style.display = 'block';
+                element.children[2].style.display = 'none';
+            } else if (stateDiff.expanded === true) {
+                element.children[0].style.display = 'block';
+                element.children[1].style.display = 'none';
+                element.children[2].style.display = 'block';
+            }
+        }
+    });
+    if (exporter)
+        exporter((expanded) => ref.setState({expanded: expanded}));
+    return ListProviderReceiver((updateContainerWidth, onContainerScroll, onResize) => {
+        return `<div class="groupSeries" ref="${ref}">
+            <div class="series" style="display:none;"></div>
+            <div>${mainSeries(updateContainerWidth, onContainerScroll, onResize)}</div>
+            <div style="display:none">${subSerieses.map((subSeries) => subSeries(updateContainerWidth, onContainerScroll, onResize)).join("")}</div>
+        </div>`;
+    });
+}
+
+Timeline.HeaderComponent = (label) => {
+    return `<div class="series">${label}</div>`;
+}
+
+Timeline.ExpandableHeaderComponent = (mainLabel, subLabels, exporter) => {
+    const ref = REF.createRef({
+        state: {expanded: false},
+        onStateUpdate: (element, stateDiff) => {
+            if (stateDiff.expanded === false)
+                element.children[1].style.display = "none";
+            else if (stateDiff.expanded === true)
+                element.children[1].style.display = "block";
+        }
+    });
+    if (exporter)
+        exporter((expanded) => ref.setState({expanded: expanded}));
+    return `<div ref="${ref}">
+        <div class="series">
+            ${mainLabel}
+        </div>
+        <div style="display:none">
+            ${subLabels.map(label => `<div class="series">${label}</div>`).join("")}
+        </div>
+    </div>`;
+}
+
+Timeline.SeriesWithHeaderComponent = (header, series) => {
+    return {header, series};
+}
+
+Timeline.ExpandableSeriesWithHeaderExpanderComponent = (mainSeriesWithLable, ...subSeriesWithLable) => {
+    const ref = REF.createRef({
+        state: {expanded: false},
+        onStateUpdate: (element, stateDiff) => {
+            if (stateDiff.expanded === false)
+                element.innerText = "+";
+            else if (stateDiff.expanded === true)
+                element.innerText = "-";
+        }
+    });
+    const mainLabel = mainSeriesWithLable.header;
+    const subLabels = subSeriesWithLable.map(item => item.header);
+    const mainSeries = mainSeriesWithLable.series;
+    const subSerieses = subSeriesWithLable.map(item => item.series);
+    const expandedEvent = new EventStream();
+    const clickEvent = ref.fromEvent('click').action(() => {
+        let expanded = ref.state.expanded;
+        expandedEvent.add(!expanded);
+        ref.setState({expanded: !expanded});
+    });
+    const composer = FP.composer(FP.currying((setHeaderExpand, setSeriesExpand) => {
+        expandedEvent.action((expanded) => {
+            setHeaderExpand(expanded);
+            setSeriesExpand(expanded);
+        })
+    }));
+    return {
+        header: Timeline.ExpandableHeaderComponent(`<a href="" ref="${ref}">+</a>` + mainLabel, subLabels, composer),
+        series: Timeline.ExpandableSeriesComponent(mainSeries, subSerieses, composer),
+    }
+}
+
+Timeline.CanvasXAxisComponent = (scales, option = {}) => {
+    // Get configuration
+    const getScaleKey = typeof option.getScaleFunc === "function" ? option.getScaleFunc : (a) => a;
+    const comp = typeof option.compareFunc === "function" ? option.compareFunc : (a, b) => a - b;
+    const _onScaleClick_ = typeof option._onScaleClick_ === "function" ? option.onScaleClick : null;
+    const _onScaleHover_ = typeof option._onScaleHover_ === "function" ? option.onScaleHover : null;
+    const sortData = option.sortData === true ? option.sortData : false;
+    const getLabel = typeof option.getLabelFunc === "function" ? option.getLabelFunc : (a) => a;
+    const isTop = typeof option.isTop === "boolean" ? option.isTop : false;
+
+    // Get the css value, this component assume to use with webkit.css
+    const computedStyle = getComputedStyle(document.body);
+    const fontFamily = computedStyle.getPropertyValue('font-family');
+    const fontSize = computedStyle.getPropertyValue('--tinySize');
+    const fontSizeNumber = parseInt(fontSize);
+    const fontColor = onScaleClick ? computedStyle.getPropertyValue('--linkColor') : computedStyle.getPropertyValue('color');
+    const fontRotate = 60 * Math.PI / 180;
+    const fontTopRotate = 300 * Math.PI / 180;
+    const linkColor = computedStyle.getPropertyValue('--linkColor');
+    const scaleWidth = parseInt(computedStyle.getPropertyValue('--smallSize')) * 3;
+    const scaleTagLineHeight = parseInt(computedStyle.getPropertyValue('--smallSize'));
+    const scaleTagLinePadding = 10;
+    const scaleBroadLineHeight = parseInt(computedStyle.getPropertyValue('--tinySize')) / 2;
+    const maxinumTextHeight = scaleWidth * 4.5;
+    const canvasHeight = parseInt(computedStyle.getPropertyValue('--smallSize')) * 4;
+    const sqrt3 = Math.sqrt(3);
+
+    const drawScale = (scaleLabel, group, context, x, y, isHoverable, lineColor, groupColor) => {
+        const computedStyle = getComputedStyle(document.body);
+        const usedLineColor = lineColor ? lineColor : computedStyle.getPropertyValue('--borderColorInlineElement');
+        const usedGroupColor = groupColor ? groupColor : isDarkMode() ? computedStyle.getPropertyValue('--white') : computedStyle.getPropertyValue('--black');
+        const totalWidth = group * scaleWidth;
+        const baseLineY = isTop ? y + canvasHeight - scaleBroadLineHeight : y + scaleBroadLineHeight;
+        if (group > 1) {
+            // Draw group label
+            context.beginPath();
+            context.lineWidth = 1;
+            context.strokeStyle = usedGroupColor;
+            context.moveTo(x + context.lineWidth, isTop ? canvasHeight : y);
+            context.lineTo(x + context.lineWidth, baseLineY);
+            context.stroke();
+        }
+
+        // Draw tag line
+        const middlePointX = x + totalWidth / 2;
+        context.beginPath();
+        context.moveTo(middlePointX, baseLineY);
+        if (!isTop)
+            context.lineTo(middlePointX, baseLineY + scaleTagLineHeight - scaleTagLinePadding);
+        else
+            context.lineTo(middlePointX, baseLineY - scaleTagLineHeight + scaleTagLinePadding);
+        if (group > 1)
+            context.strokeStyle = usedGroupColor;
+        else
+            context.strokeStyle = usedLineColor;
+        context.stroke();
+
+        if (group > 1) {
+                // Draw the group line
+                context.beginPath();
+                context.moveTo(x, baseLineY);
+                context.lineTo(x + totalWidth, baseLineY);
+                context.strokeStyle = usedGroupColor;
+                context.stroke();
+        }
+
+        // Draw tag
+        if (!isTop)
+            context.moveTo(middlePointX, baseLineY + scaleTagLineHeight);
+        else
+            context.moveTo(middlePointX, baseLineY - scaleTagLineHeight);
+        context.font = `${fontSize} ${fontFamily}`;
+        context.fillStyle = fontColor;
+        context.save();
+        if (!isTop) {
+            context.rotate(fontRotate);
+            context.fillText(scaleLabel, middlePointX / 2 + sqrt3 * scaleTagLineHeight / 2, baseLineY - sqrt3 * (middlePointX / 2) + scaleTagLineHeight / 2);
+        } else {
+            context.rotate(fontTopRotate);
+            context.fillText(scaleLabel, middlePointX / 2 - sqrt3 * scaleTagLineHeight - fontSizeNumber, baseLineY + sqrt3 * (middlePointX / 2) -    3 * scaleTagLineHeight / 2 - fontSizeNumber);
+        }
+        context.restore();
+
+        if (group > 1) {
+            // Draw group label
+            context.beginPath();
+            context.lineWidth = 1;
+            context.strokeStyle = usedGroupColor;
+            context.moveTo(x + totalWidth, isTop ? canvasHeight : y);
+            context.lineTo(x + totalWidth, baseLineY);
+            context.stroke();
+        }
+    };
+    const render = typeof option.renderFactory === "function" ? option.renderFactory(drawScale) : (scaleLabel, scaleGroup, context, x, y) => drawScale(scaleLabel, scaleGroup, context, x, y);
+
+    const padding = 100 * scaleWidth / getDevicePixelRatio();
+    const offscreenCachedRender = offscreenCachedRenderFactory(padding, canvasHeight);
+    let inCacheScales = [];
+
+    const getMouseEventTirggerScales = (e, scrollLeft, element) => {
+        const {x, y} = getMousePosInCanvas(e, element);
+        return inCacheScales.filter(scale => {
+            const detactBoxTopX = scale._tagTop.x - scrollLeft - fontSizeNumber * sqrt3 / 2;
+            if (detactBoxTopX < 0) return false;
+            const detactBoxTopY = scale._tagTop.y;
+            const detactBoxWidth = fontSizeNumber * sqrt3 / 2 + scale.label.toString().length * fontSizeNumber / 2;
+            const detactBoxHeight = fontSizeNumber / 2 + scale.label.toString().length * fontSizeNumber / 2 * sqrt3;
+            return pointRectCollisionDetect({x, y}, {
+                    topLeftX: detactBoxTopX,
+                    topLeftY: isTop ? detactBoxTopY - detactBoxHeight : detactBoxTopY,
+                    width: detactBoxWidth,
+                    height: detactBoxHeight
+                });
+        });
+    };
+    const redrawCache = (offscreenCanvas, element, stateDiff, state, notifyToRender) => {
+        const scrollLeft = typeof stateDiff.scrollLeft === 'number' ? stateDiff.scrollLeft : state.scrollLeft;
+        const scales = stateDiff.scales ? stateDiff.scales : state.scales;
+        const scalesMapLinkList = stateDiff.scalesMapLinkList ? stateDiff.scalesMapLinkList : state.scalesMapLinkList;
+        const width = typeof stateDiff.width === 'number' ? stateDiff.width : state.width;
+        const usedLineColor = computedStyle.getPropertyValue('--borderColorInlineElement');
+        const totalWidth = 2 * padding + width;
+        const baseLineY = isTop ? canvasHeight - scaleBroadLineHeight : scaleBroadLineHeight;
+        if (offscreenCanvas.logicWidth !== totalWidth) {
+            setupCanvasWidthWithDpr(offscreenCanvas, totalWidth);
+            setupCanvasContextScale(offscreenCanvas);
+        }
+        if (offscreenCanvas.logicHeight !== element.logicHeight) {
+            setupCanvasHeightWithDpr(offscreenCanvas, element.logicHeight);
+            setupCanvasContextScale(offscreenCanvas);
+        }
+        const context = offscreenCanvas.getContext("2d");
+        const realScrollLeft = scrollLeft > padding ? scrollLeft - padding : scrollLeft;
+        const currentStartScaleIndex = Math.floor(realScrollLeft / scaleWidth);
+        const currentStartScaleKey = getScaleKey(scales[currentStartScaleIndex]);
+        let currentEndScaleIndex = Math.ceil((realScrollLeft + totalWidth) / scaleWidth);
+        currentEndScaleIndex = currentEndScaleIndex > scales.length ? scales.length - 1 : currentEndScaleIndex;
+        const currentEndScaleKey = getScaleKey(scales[currentEndScaleIndex]);
+        let viewPortEndScaleIndex = Math.ceil((realScrollLeft + width) / scaleWidth);
+        viewPortEndScaleIndex = viewPortEndScaleIndex > scales.length ? scales.length - 1 : viewPortEndScaleIndex;
+        const viewPortEndScaleKey = getScaleKey(scales[viewPortEndScaleIndex]);
+        const currentStartNode = scalesMapLinkList.map.get(currentStartScaleKey);
+        const currentEndNode = scalesMapLinkList.map.get(currentEndScaleKey);
+        const viewPortEndNode = scalesMapLinkList.map.get(viewPortEndScaleKey);
+        let now = currentStartNode;
+        // Clear the cache
+        context.clearRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
+        context.moveTo(0, baseLineY);
+        context.lineWidth = 1;
+        context.strokeStyle = usedLineColor;
+        context.lineTo(offscreenCanvas.logicWidth, baseLineY);
+        context.stroke();
+
+        inCacheScales = [];
+        while (now != currentEndNode.next) {
+            const label = now.label;
+            const group = now.group;
+            render(label, group, context, now.x - realScrollLeft, 0);
+            if (now === viewPortEndNode)
+                notifyToRender();
+            now._tagTop = {x: now.x + group * scaleWidth / 2, y: isTop ? canvasHeight - scaleBroadLineHeight : scaleBroadLineHeight};
+            inCacheScales.push(now);
+            now = now.next;
+        }
+    };
+
+    // Initialize
+    // Do a copy, sorting will not have side effect
+    const initScales = scales.map((item) => item);
+    if (sortData)
+        initScales.sort(comp);
+
+    const getScalesMapLinkList = (scales) => {
+        const res = {
+            map: new Map(),
+            linkListHead: {next: null, group: null}
+        };
+        let now = res.linkListHead;
+        let currentX = 0;
+        scales.forEach((scale) => {
+            let key = getScaleKey(scale);
+            if (res.map.has(key))
+                res.map.get(key).group += 1;
+            else {
+                now.next = {next: null, group: 1, label: scale, x: currentX};
+                now = now.next;
+                res.map.set(key, now);
+            }
+            currentX += scaleWidth;
+        });
+        return res;
+    };
+    const initScaleGroupMapLinkList = getScalesMapLinkList(initScales);
+
+    const canvasRef = REF.createRef({
+        state: {
+            scrollLeft: 0,
+            width: 0,
+            scales: initScales,
+            scalesMapLinkList: initScaleGroupMapLinkList
+        },
+        onElementMount: (element) => {
+            setupCanvasHeightWithDpr(element, canvasHeight);
+            setupCanvasContextScale(element);
+            if (onScaleClick) {
+                element.addEventListener('click', (e) => {
+                    let scales = getMouseEventTirggerScales(e, canvasRef.state.scrollLeft, element);
+                    if (scales.length)
+                        onScaleClick(scales[0], e);
+                });
+            }
+
+            if (onScaleClick || onScaleHover) {
+                element.addEventListener('mousemove', (e) => {
+                    let scales = getMouseEventTirggerScales(e, canvasRef.state.scrollLeft, element);
+                    if (scales.length) {
+                        if (onScaleHover)
+                            onScaleHover(scales[0], e);
+                        element.style.cursor = "pointer";
+                    } else {
+                        element.style.cursor = "default";
+                    }
+                });
+            }
+        },
+        onStateUpdate: (element, stateDiff, state) => {
+            if (stateDiff.scales || typeof stateDiff.scrollLeft === 'number' || typeof stateDiff.width === 'number') {
+                if (stateDiff.scales)
+                    state.scalesMapLinkList = getScalesMapLinkList(stateDiff.scales);
+                requestAnimationFrame(() => offscreenCachedRender(redrawCache, element, stateDiff, state));
+            }
+        }
+    });
+
+    return {
+        series: ListProviderReceiver((updateContainerWidth, onContainerScroll, onResize) => {
+            updateContainerWidth(scales.length * scaleWidth * getDevicePixelRatio());
+            onContainerScroll.action((e) => {
+                canvasRef.setState({scrollLeft: e.target.scrollLeft / getDevicePixelRatio()});
+            });
+            onResize.action((width) => {
+                canvasRef.setState({width: width});
+            });
+            return `<div class="x-axis">
+                <canvas ref="${canvasRef}">
+            </div>`;
+        }),
+        isAxis: true // Mark self as an axis
+    };
+}
+
+Timeline.CanvasContainer = (exporter, ...children) => {
+    const hasTopXAxis = children[0].isAxis;
+    const upackChildren = (children) => {
+        const headers = [];
+        const serieses = [];
+        children.forEach(child => {
+            if (false === "series" in child) {
+                console.error("Please use Timeline.SeriesWithHeaderComponent or Timeline.ExpandableSeriesWithHeaderExpanderComponent or Timeline.CanvasXAxisComponent as children");
+                return;
+            }
+            if (child.header)
+                headers.push(child.header);
+            serieses.push(child.series);
+        });
+        return {headers, serieses};
+    };
+    const {headers, serieses} = upackChildren(children);
+    let composer = FP.composer(FP.currying((updateHeaders, updateSerieses) => {
+        if (exporter)
+            exporter((newChildren) => {
+                const {headers, serieses} = upackChildren(newChildren);
+                updateHeaders(headers);
+                updateSerieses(serieses);
+            });
+    }));
+    return (
+        `<div class="timeline">
+            <div class="header ${hasTopXAxis ? "with-top-x-axis" : ""}">
+                ${ListComponent(composer, ...headers)}
+            </div>
+            ${XScrollableCanvasProvider(composer, ...serieses)}
+        </div>`
+    );
+}
+
+export {
+    Timeline
+};

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/templates/base.html (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/templates/base.html	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/templates/base.html	2019-07-20 01:15:26 UTC (rev 247664)
@@ -20,7 +20,7 @@
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 -->
 
 <!DOCTYPE html>
@@ -27,7 +27,7 @@
 <html>
 <head>
 <title>{{title}}</title>
-<link rel="stylesheet" type="text/css" href=""
+<link rel="stylesheet" type="text/css" href=""
 {% block head %}{% endblock %}
 </head>
 <body>

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/templates/commits.html (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/templates/commits.html	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/templates/commits.html	2019-07-20 01:15:26 UTC (rev 247664)
@@ -29,7 +29,7 @@
 <link rel="stylesheet" type="text/css" href=""
 
 <script type="module">
-import {REF, DOM} from '/library/ref.js';
+import {REF, DOM} from '/library/js/Ref.js';
 import {ErrorDisplay} from '/assets/js/common.js';
 import {CommitTable} from '/assets/js/commit.js';
 import {Drawer, BranchSelector, LimitSlider} from '/assets/js/drawer.js';

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/templates/documentation.html (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/templates/documentation.html	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/templates/documentation.html	2019-07-20 01:15:26 UTC (rev 247664)
@@ -28,7 +28,7 @@
 
 <script type="module">
 
-import {DOM} from '/library/ref.js';
+import {DOM} from '/library/js/Ref.js';
 import {Expectations} from '/assets/js/timeline.js';
 
 function jumpIdUnderHeader(id) {

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/templates/search.html (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/templates/search.html	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/templates/search.html	2019-07-20 01:15:26 UTC (rev 247664)
@@ -34,7 +34,7 @@
 import {deepCompare, ErrorDisplay, queryToParams, paramsToQuery} from '/assets/js/common.js';
 import {Configuration} from '/assets/js/configuration.js';
 import {Drawer, BranchSelector, ConfigurationSelectors, LimitSlider} from '/assets/js/drawer.js';
-import {DOM, REF} from '/library/ref.js';
+import {DOM, REF} from '/library/js/Ref.js';
 import {SearchBar} from '/assets/js/search.js';
 import {Legend, Timeline} from '/assets/js/timeline.js';
 

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/templates/suite_results.html (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/templates/suite_results.html	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/templates/suite_results.html	2019-07-20 01:15:26 UTC (rev 247664)
@@ -34,7 +34,7 @@
 import {deepCompare, ErrorDisplay, queryToParams, paramsToQuery} from '/assets/js/common.js';
 import {Configuration} from '/assets/js/configuration.js';
 import {Drawer, BranchSelector, ConfigurationSelectors, LimitSlider} from '/assets/js/drawer.js';
-import {DOM, REF} from '/library/ref.js';
+import {DOM, REF} from '/library/js/Ref.js';
 import {SearchBar} from '/assets/js/search.js';
 import {Legend, Timeline} from '/assets/js/timeline.js';
 

Modified: trunk/Tools/resultsdbpy/resultsdbpy/view/view_routes.py (247663 => 247664)


--- trunk/Tools/resultsdbpy/resultsdbpy/view/view_routes.py	2019-07-20 00:55:51 UTC (rev 247663)
+++ trunk/Tools/resultsdbpy/resultsdbpy/view/view_routes.py	2019-07-20 01:15:26 UTC (rev 247664)
@@ -111,14 +111,8 @@
     def library(self, path):
         AssertRequest.no_query()
         AssertRequest.is_type()
-        result = {
-            # FIXME: These links are currently dead
-            'ref.js': self.cache_resource('https://build.webkit.org/dashboard/devices/Scripts/Ref.js'),
-            'webkit.css': self.cache_resource('https://build.webkit.org/dashboard/Styles/webkit.css'),
-        }.get(path, None)
-        if not result:
-            abort(404, description=f'{path} is not a known library')
-        return result
+        path_split = os.path.split(path)
+        return send_from_directory(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static/library', *path_split[:-1]), path_split[-1])
 
     def response_500(self, error=InternalServerError()):
         if isinstance(error, HTTPException):
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to