ondras / wwwsqldesigner

WWW SQL Designer, your online SQL diagramming tool
https://sql.toad.cz/?keyword=online_library
BSD 3-Clause "New" or "Revised" License
2.86k stars 722 forks source link

Tables auto-arrange #266

Open cedricfrancoys opened 6 years ago

cedricfrancoys commented 6 years ago

Hello Ondřej,

Thank you for this powerful tool !

I needed a quick auto-layout feature. So, in case it helps someone else, here the code snippet I came up with:

SQL.Designer.prototype.arrangeTables = function() {
    var win = OZ.DOM.win();

    var viewport = {
        ratio: 16/9,
        current: {
            width: 100,
            height: 100
        },
        max: {
            width: 3000,
            height: 3000
        }
    };

    var column = function () {
        return {
            width: 280, // fixed width
            height: 0
        };
    };

    var columns = [];

    function increase_viewport() {
        if( (viewport.current.width / viewport.current.height) < viewport.ratio) {
            viewport.current.width += 300;
            columns[columns.length] = new column;
        }
        else {
            viewport.current.height += 300;
        }
    }

    function add(table) {
        var set = false;
        while(!set) {
            for(var i = 0; i < columns.length; ++i) {
                if((i+1)*280 > viewport.current.width) {
                    break;
                }
                if(columns[i].height + table.dom.container.offsetHeight < viewport.current.height) {
                    table.moveTo((i*280), columns[i].height);
                    columns[i].height += table.dom.container.offsetHeight + 20;
                    // we're done
                    set = true;
                    break;
                }
            }        
            if(!set) {
                // increase viewport and retry
                increase_viewport();
            }
        }
    }

    for (var i = 0; i < this.tables.length; i++) {
        add(this.tables[i]);
    }  

    this.sync();
}