diff --git a/HISTORY.md b/HISTORY.md index 595d738c..77b25b89 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -15,6 +15,12 @@ http://visjs.org on screen. - Implemented an option `focus` for `setSelection(ids, options)`, to immediately focus selected nodes. +- Implemented animated range change for functions `fit`, `focus`, `setSelection`, + and `setWindow`. +- Implemented functions `setCurrentTime(date)` and `getCurrentTime()`. +- Fixed the `change` event sometimes being fired twice on IE10. +- Fixed canceling moving an item to another group did not move the item + back to the original group. ### Network @@ -32,6 +38,7 @@ http://visjs.org - Added 'customRange' for the Y axis and an example showing how it works. - Added localization support. - Implemented option `clickToUse`. +- Implemented functions `setCurrentTime(date)` and `getCurrentTime()`. - Fixed bugs. - Added groups.visibility functionality and an example showing how it works. diff --git a/docs/graph2d.html b/docs/graph2d.html index 2c9b7726..b479b993 100644 --- a/docs/graph2d.html +++ b/docs/graph2d.html @@ -3,9 +3,9 @@ vis.js | Graph2d documentation @@ -35,15 +35,15 @@
  • Loading
  • Data Format
  • Configuration Options - +
  • Methods
  • Events
  • @@ -127,12 +127,12 @@ Data points must have properties x, y, and z, and can optionally have a property style and filter.

    - Graph2d can be provided with two types of data: + Graph2d can be provided with two types of data:

    Items

    @@ -179,14 +179,14 @@ var items = [

    Groups

    - Like the items, groups are regular JavaScript Arrays and Objects. - Using groups, items can be grouped together. - Items are filtered per group, and displayed as individual graphs. Groups can contain the properties id, - content, className (optional) and options (optional). + Like the items, groups are regular JavaScript Arrays and Objects. + Using groups, items can be grouped together. + Items are filtered per group, and displayed as individual graphs. Groups can contain the properties id, + content, className (optional) and options (optional).

    - Groups can be applied to a timeline using the method setGroups. - A table with groups can be created like: + Groups can be applied to a timeline using the method setGroups. + A table with groups can be created like:

    @@ -205,51 +205,51 @@ groups.add({
     
     
     

    - Groups can have the following properties: + Groups can have the following properties:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeRequiredDescription
    idString | NumberyesAn id for the group. The group will display all items having a - property group which matches the id - of the group.
    contentStringyesThe contents of the group. This can be plain text or html code.
    classNameStringnoThis field is optional. A className can be used to give groups - an individual css style. -
    optionsJSON objectnoThis field is optional. The options can be used to give a group a specific draw style. - Any options that are colored green in the Configuration Options can be used as options here. -
    visibleBooleantrueThis field is optional. If false, this group will not be drawn. -
    NameTypeRequiredDescription
    idString | NumberyesAn id for the group. The group will display all items having a + property group which matches the id + of the group.
    contentStringyesThe contents of the group. This can be plain text or html code.
    classNameStringnoThis field is optional. A className can be used to give groups + an individual css style. +
    optionsJSON objectnoThis field is optional. The options can be used to give a group a specific draw style. + Any options that are colored green in the Configuration Options can be used as options here. +
    visibleBooleantrueThis field is optional. If false, this group will not be drawn. +

    Configuration Options

    @@ -270,217 +270,217 @@ var options = { The options colored in green can also be used as options for the groups. All options are optional. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameTypeDefaultDescription
    yAxisOrientationString'left'This defines with which axis, left or right, the graph is coupled. Example 5 shows groups with different Y axis. If no groups are coupled - with an axis, it will not be shown.
    defaultGroupString'default'This is the label for the default, ungrouped items when shown in a legend.
    sortBooleantrueThis determines if the items are sorted automatically. - They are sorted by the x value. If sort is enabled, more optimizations are possible, increasing the performance.
    samplingBooleantrueIf sampling is enabled, Graph2d will automatically determine the amount of points per pixel. - If there are more than 1 point per pixel, not all points will be drawn. Disabling sampling will cause a decrease in performance.
    graphHeightNumber | String'400px'This is the height of the graph SVG canvas. - If it is larger than the height of the outer frame, you can drag up and down - the vertical direction as well as the usual horizontal direction.
    shadedBoolean | ObjectfalseToggle a shaded area with the default settings.
    shaded.enabledBooleanfalseThis toggles the shading.
    shaded.orientationString'bottom'This determines if the shaded area is at the bottom or at the top of the curve. The options are 'bottom' or 'top'.
    styleString'line'This allows the user to define if this should be a linegraph or a barchart. The options are: 'line' or 'bar'.
    barChart.widthNumber50The width of the bars.
    barChart.alignString'center'The alignment of the bars with regards to the coordinate. The options are 'left', 'right' or 'center'.
    barChart.handleOverlapString'overlap'You can choose how graph2d handles the case where barcharts are occupying the same datapoint. The possible options are: - overlap, sideBySide, stack. - See example 10 for more information. - When using groups, see example 11. -
    catmullRomBoolean | ObjecttrueToggle the interpolation with the default settings. For more customization use the JSON format.
    catmullRom.enabledBooleantrueToggle the interpolation.
    catmullRom.parametrizationString'centripetal'Define the type of parametrizaion. Example 7 shows the different methods. The options are 'centripetal' (best results), 'chordal' and 'uniform'. Uniform is the computationally cheapest variant. - If catmullRom is disabled, linear interpolation is used.
    drawPointsBoolean | ObjecttrueToggle the drawing of the datapoints with the default settings.
    drawPoints.enabledBooleantrueToggle the drawing of the datapoints.
    drawPoints.sizeNumber6Determine the size at which the data points are drawn.
    drawPoints.styleString'square'Determine the shape of the data points. The options are 'square' or 'circle'.
    dataAxis.showMinorLabelsBooleantrueToggle the drawing of the minor labels on the Y axis.
    dataAxis.showMajorLabelsBooleantrueToggle the drawing of the major labels on the Y axis.
    dataAxis.iconsBooleanfalseToggle the drawing of automatically generated icons the Y axis.
    dataAxis.widthNumber | String'40px'Set the (minimal) width of the yAxis. The axis will resize to accomodate the labels of the Y values.
    dataAxis.visibleBooleantrueShow or hide the data axis.
    groups.visibilityObjectYou can use this to toggle the visibility of groups per graph2D instance. This is different from setting the visibility flag of the groups since - this is not communicated across instances of graph2d. Take a look at Example 14 - for more explaination. -
    legendBooleanfalseToggle the legend with the default settings.
    legend.enabledBooleanfalseToggle the legend.
    legend.iconsBooleantrueShow automatically generated icons on the legend.
    legend.left.visibleBooleantrueBoth axis, left and right, have a corresponding legend. This toggles the visibility of the legend that is coupled with the left axis.
    legend.left.positionString'top-left'Determine the position of the legend coupled to the left axis. Options are 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.
    legend.right.visibleBooleantrueThis toggles the visibility of the legend that is coupled with the right axis.
    legend.right.positionString'top-right'Determine the position of the legend coupled to the right axis. Options are 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.
    NameTypeDefaultDescription
    yAxisOrientationString'left'This defines with which axis, left or right, the graph is coupled. Example 5 shows groups with different Y axis. If no groups are coupled + with an axis, it will not be shown.
    defaultGroupString'default'This is the label for the default, ungrouped items when shown in a legend.
    sortBooleantrueThis determines if the items are sorted automatically. + They are sorted by the x value. If sort is enabled, more optimizations are possible, increasing the performance.
    samplingBooleantrueIf sampling is enabled, Graph2d will automatically determine the amount of points per pixel. + If there are more than 1 point per pixel, not all points will be drawn. Disabling sampling will cause a decrease in performance.
    graphHeightNumber | String'400px'This is the height of the graph SVG canvas. + If it is larger than the height of the outer frame, you can drag up and down + the vertical direction as well as the usual horizontal direction.
    shadedBoolean | ObjectfalseToggle a shaded area with the default settings.
    shaded.enabledBooleanfalseThis toggles the shading.
    shaded.orientationString'bottom'This determines if the shaded area is at the bottom or at the top of the curve. The options are 'bottom' or 'top'.
    styleString'line'This allows the user to define if this should be a linegraph or a barchart. The options are: 'line' or 'bar'.
    barChart.widthNumber50The width of the bars.
    barChart.alignString'center'The alignment of the bars with regards to the coordinate. The options are 'left', 'right' or 'center'.
    barChart.handleOverlapString'overlap'You can choose how graph2d handles the case where barcharts are occupying the same datapoint. The possible options are: + overlap, sideBySide, stack. + See example 10 for more information. + When using groups, see example 11. +
    catmullRomBoolean | ObjecttrueToggle the interpolation with the default settings. For more customization use the JSON format.
    catmullRom.enabledBooleantrueToggle the interpolation.
    catmullRom.parametrizationString'centripetal'Define the type of parametrizaion. Example 7 shows the different methods. The options are 'centripetal' (best results), 'chordal' and 'uniform'. Uniform is the computationally cheapest variant. + If catmullRom is disabled, linear interpolation is used.
    drawPointsBoolean | ObjecttrueToggle the drawing of the datapoints with the default settings.
    drawPoints.enabledBooleantrueToggle the drawing of the datapoints.
    drawPoints.sizeNumber6Determine the size at which the data points are drawn.
    drawPoints.styleString'square'Determine the shape of the data points. The options are 'square' or 'circle'.
    dataAxis.showMinorLabelsBooleantrueToggle the drawing of the minor labels on the Y axis.
    dataAxis.showMajorLabelsBooleantrueToggle the drawing of the major labels on the Y axis.
    dataAxis.iconsBooleanfalseToggle the drawing of automatically generated icons the Y axis.
    dataAxis.widthNumber | String'40px'Set the (minimal) width of the yAxis. The axis will resize to accomodate the labels of the Y values.
    dataAxis.visibleBooleantrueShow or hide the data axis.
    groups.visibilityObjectYou can use this to toggle the visibility of groups per graph2D instance. This is different from setting the visibility flag of the groups since + this is not communicated across instances of graph2d. Take a look at Example 14 + for more explaination. +
    legendBooleanfalseToggle the legend with the default settings.
    legend.enabledBooleanfalseToggle the legend.
    legend.iconsBooleantrueShow automatically generated icons on the legend.
    legend.left.visibleBooleantrueBoth axis, left and right, have a corresponding legend. This toggles the visibility of the legend that is coupled with the left axis.
    legend.left.positionString'top-left'Determine the position of the legend coupled to the left axis. Options are 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.
    legend.right.visibleBooleantrueThis toggles the visibility of the legend that is coupled with the right axis.
    legend.right.positionString'top-right'Determine the position of the legend coupled to the right axis. Options are 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.

    Timeline Options

    @@ -665,146 +665,161 @@ The options colored in green can also be used as options for the groups. All opt

    Methods

    - The Graph2d supports the following methods. + The Graph2d supports the following methods.

    - - - - - - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    MethodReturn TypeDescription
    clear([what])none - Clear the Graph2d. An object can be passed specifying which sections to clear: items, groups, - and/or options. By Default, items, groups and options are cleared, i.e. what = {items: true, groups: true, options: true}. Example usage: +
    MethodReturn TypeDescription
    clear([what])none + Clear the Graph2d. An object can be passed specifying which sections to clear: items, groups, + and/or options. By Default, items, groups and options are cleared, i.e. what = {items: true, groups: true, options: true}. Example usage:
    Graph2d.clear();                // clear items, groups, and options
     Graph2d.clear({options: true}); // clear options only
     
    -
    destroy()noneDestroy the Graph2d. The Graph2d is removed from memory. all DOM elements and event listeners are cleaned up. -
    getCustomTime()DateRetrieve the custom time. Only applicable when the option showCustomTime is true. -
    setCustomTime(time)noneAdjust the custom time bar. Only applicable when the option showCustomTime is true. time is a Date object. -
    getLegend(groupId, iconWidth, iconHeight)SVGelement, String, StringReturns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). -
    getWindow()ObjectGet the current visible window. Returns an object with properties start: Date and end: Date.
    getItemRange()ObjectGet the range of all the items as an object containing min: Date and max: Date.
    fit()noneAdjust the visible window such that it fits all items. -
    on(event, callback)noneCreate an event listener. The callback function is invoked every time the event is triggered. Avialable events: rangechange, rangechanged, select. The callback function is invoked as callback(properties), where properties is an object containing event specific properties. See section Events for more information.
    off(event, callback)noneRemove an event listener created before via function on(event, callback). See section Events for more information.
    redraw()noneForce a redraw of the Graph2d. Can be useful to manually redraw when option autoResize=false. -
    isGroupVisible(groupId)BooleanThis checks if the visible option of the supplied group (by ID) is true or false. -
    setGroups(groups)noneSet a data set with groups for the Graph2d. - groups can be an Array with Objects, - a DataSet, or a DataView. For each of the groups, the items of the - Graph2d are filtered on the property group, which - must correspond with the id of the group. -
    setItems(items)noneSet a data set with items for the Graph2d. - items can be an Array with Objects, - a DataSet, or a DataView. -
    setOptions(options)noneSet or update options. It is possible to change any option of the Graph2d at any time. You can for example switch orientation on the fly. -
    setWindow(start, end)noneSet the current visible window. The parameters start and end can be a Date, Number, or String. If the parameter value of start or end is null, the parameter will be left unchanged.
    destroy()noneDestroy the Graph2d. The Graph2d is removed from memory. all DOM elements and event listeners are cleaned up. +
    getCurrentTime()DateGet the current time. Only applicable when option showCurrentTime is true. +
    getCustomTime()DateRetrieve the custom time. Only applicable when the option showCustomTime is true. +
    setCurrentTime(time)noneSet a current time. This can be used for example to ensure that a client's time is synchronized with a shared server time. + time can be a Date object, numeric timestamp, or ISO date string. + Only applicable when option showCurrentTime is true.
    setCustomTime(time)noneAdjust the custom time bar. Only applicable when the option showCustomTime is true. time can be a Date object, numeric timestamp, or ISO date string. +
    getLegend(groupId, iconWidth, iconHeight)SVGelement, String, StringReturns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). +
    getWindow()ObjectGet the current visible window. Returns an object with properties start: Date and end: Date.
    getItemRange()ObjectGet the range of all the items as an object containing min: Date and max: Date.
    fit()noneAdjust the visible window such that it fits all items. +
    on(event, callback)noneCreate an event listener. The callback function is invoked every time the event is triggered. Avialable events: rangechange, rangechanged, select. The callback function is invoked as callback(properties), where properties is an object containing event specific properties. See section Events for more information.
    off(event, callback)noneRemove an event listener created before via function on(event, callback). See section Events for more information.
    redraw()noneForce a redraw of the Graph2d. Can be useful to manually redraw when option autoResize=false. +
    isGroupVisible(groupId)BooleanThis checks if the visible option of the supplied group (by ID) is true or false. +
    setGroups(groups)noneSet a data set with groups for the Graph2d. + groups can be an Array with Objects, + a DataSet, or a DataView. For each of the groups, the items of the + Graph2d are filtered on the property group, which + must correspond with the id of the group. +
    setItems(items)noneSet a data set with items for the Graph2d. + items can be an Array with Objects, + a DataSet, or a DataView. +
    setOptions(options)noneSet or update options. It is possible to change any option of the Graph2d at any time. You can for example switch orientation on the fly. +
    setWindow(start, end)noneSet the current visible window. The parameters start and end can be a Date, Number, or String. If the parameter value of start or end is null, the parameter will be left unchanged.

    Events

    - Graph2d fires events when changing the visible window by dragging, when - selecting items, and when dragging the custom time bar. + Graph2d fires events when changing the visible window by dragging, when + selecting items, and when dragging the custom time bar.

    - Here an example on how to listen for a rangeChanged event. + Here an example on how to listen for a rangeChanged event.

    @@ -814,7 +829,7 @@ Graph2d.on('select', function (properties) {
     

    - A listener can be removed via the function off: + A listener can be removed via the function off:

    @@ -833,68 +848,68 @@ Graph2d.off('rangechanged', onChange);
     
     
     

    - The following events are available. + The following events are available.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    nameDescriptionProperties
    rangechangeFired repeatedly when the user is dragging the Graph2d window. - -
      -
    • start (Number): timestamp of the current start of the window.
    • -
    • end (Number): timestamp of the current end of the window.
    • -
    -
    rangechangedFired once after the user has dragged the Graph2d window. - -
      -
    • start (Number): timestamp of the current start of the window.
    • -
    • end (Number): timestamp of the current end of the window.
    • -
    -
    timechangeFired repeatedly when the user is dragging the custom time bar. - Only available when the custom time bar is enabled. - -
      -
    • time (Date): the current time.
    • -
    -
    timechangedFired once after the user has dragged the custom time bar. - Only available when the custom time bar is enabled. - -
      -
    • time (Date): the current time.
    • -
    -
    nameDescriptionProperties
    rangechangeFired repeatedly when the user is dragging the Graph2d window. + +
      +
    • start (Number): timestamp of the current start of the window.
    • +
    • end (Number): timestamp of the current end of the window.
    • +
    +
    rangechangedFired once after the user has dragged the Graph2d window. + +
      +
    • start (Number): timestamp of the current start of the window.
    • +
    • end (Number): timestamp of the current end of the window.
    • +
    +
    timechangeFired repeatedly when the user is dragging the custom time bar. + Only available when the custom time bar is enabled. + +
      +
    • time (Date): the current time.
    • +
    +
    timechangedFired once after the user has dragged the custom time bar. + Only available when the custom time bar is enabled. + +
      +
    • time (Date): the current time.
    • +
    +
    @@ -956,20 +971,20 @@ Graph2d comes with support for the following locales:

    Styles

    - All parts of the Graph2d have a class name and a default css style just like the Graph2d. - The styles can be overwritten, which enables full customization of the layout - of the Graph2d. + All parts of the Graph2d have a class name and a default css style just like the Graph2d. + The styles can be overwritten, which enables full customization of the layout + of the Graph2d.

    - Additionally, Graph2d has 10 preset styles for graphs, which are cycled through when loading groups. These styles can be overwritten - as well, along with defining your own classes to style the graphs! Example 4 and - example 5 show the usage of custom styles. + Additionally, Graph2d has 10 preset styles for graphs, which are cycled through when loading groups. These styles can be overwritten + as well, along with defining your own classes to style the graphs! Example 4 and + example 5 show the usage of custom styles.

    Data Policy

    - All code and data is processed and rendered in the browser. - No data is sent to any server. + All code and data is processed and rendered in the browser. + No data is sent to any server.

    diff --git a/docs/timeline.html b/docs/timeline.html index aa0b89f3..9c1542c1 100644 --- a/docs/timeline.html +++ b/docs/timeline.html @@ -737,16 +737,30 @@ timeline.clear({options: true}); // clear options only - fit() + fit([options]) none Adjust the visible window such that it fits all items. See also function focus(id). + Available options: + - focus(id | ids) + focus(id | ids [, options]) none - Adjust the visible window such that the selected item (or multiple items) are centered on screen. See also function fit(). + Adjust the visible window such that the selected item (or multiple items) are centered on screen. See also function fit(). Available options: + + + + + + getCurrentTime() + Date + Get the current time. Only applicable when option showCurrentTime is true. @@ -757,10 +771,18 @@ timeline.clear({options: true}); // clear options only + + setCurrentTime(time) + none + Set a current time. This can be used for example to ensure that a client's time is synchronized with a shared server time. + time can be a Date object, numeric timestamp, or ISO date string. + Only applicable when option showCurrentTime is true. + + setCustomTime(time) none - Adjust the custom time bar. Only applicable when the option showCustomTime is true. time is a Date object. + Adjust the custom time bar. Only applicable when the option showCustomTime is true. time can be a Date object, numeric timestamp, or ISO date string. @@ -829,19 +851,24 @@ timeline.clear({options: true}); // clear options only - setSelection([ids [, options]]) + setSelection(id | ids [, options]) none Select one or multiple items by their id. The currently selected items will be unselected. To unselect all selected items, call `setSelection([])`. Available options: - setWindow(start, end) + setWindow(start, end [, options]) none - Set the current visible window. The parameters start and end can be a Date, Number, or String. If the parameter value of start or end is null, the parameter will be left unchanged. + Set the current visible window. The parameters start and end can be a Date, Number, or String. If the parameter value of start or end is null, the parameter will be left unchanged. Available options: + + diff --git a/lib/timeline/Core.js b/lib/timeline/Core.js index 7c33be50..37b22513 100644 --- a/lib/timeline/Core.js +++ b/lib/timeline/Core.js @@ -325,8 +325,14 @@ Core.prototype.clear = function(what) { /** * Set Core window such that it fits all items + * @param {Object} [options] Available options: + * `animate: boolean | number` + * If true (default), the range is animated + * smoothly to the new window. + * If a number, the number is taken as duration + * for the animation. Default duration is 500 ms. */ -Core.prototype.fit = function() { +Core.prototype.fit = function(options) { // apply the data range as range var dataRange = this.getItemRange(); @@ -348,7 +354,8 @@ Core.prototype.fit = function() { return; } - this.range.setRange(start, end); + var animate = (options && options.animate !== undefined) ? options.animate : true; + this.range.setRange(start, end, animate); }; @@ -363,15 +370,22 @@ Core.prototype.fit = function() { * object with properties start and end. * * @param {Date | Number | String | Object} [start] Start date of visible window - * @param {Date | Number | String} [end] End date of visible window + * @param {Date | Number | String} [end] End date of visible window + * @param {Object} [options] Available options: + * `animate: boolean | number` + * If true (default), the range is animated + * smoothly to the new window. + * If a number, the number is taken as duration + * for the animation. Default duration is 500 ms. */ -Core.prototype.setWindow = function(start, end) { +Core.prototype.setWindow = function(start, end, options) { + var animate = (options && options.animate !== undefined) ? options.animate : true; if (arguments.length == 1) { var range = arguments[0]; - this.range.setRange(range.start, range.end); + this.range.setRange(range.start, range.end, animate); } else { - this.range.setRange(start, end); + this.range.setRange(start, end, animate); } }; @@ -536,6 +550,34 @@ Core.prototype.repaint = function () { throw new Error('Function repaint is deprecated. Use redraw instead.'); }; +/** + * Set a current time. This can be used for example to ensure that a client's + * time is synchronized with a shared server time. + * Only applicable when option `showCurrentTime` is true. + * @param {Date | String | Number} time A Date, unix timestamp, or + * ISO date string. + */ +Core.prototype.setCurrentTime = function(time) { + if (!this.currentTime) { + throw new Error('Option showCurrentTime must be true'); + } + + this.currentTime.setCurrentTime(time); +}; + +/** + * Get the current time. + * Only applicable when option `showCurrentTime` is true. + * @return {Date} Returns the current time. + */ +Core.prototype.getCurrentTime = function() { + if (!this.currentTime) { + throw new Error('Option showCurrentTime must be true'); + } + + return this.currentTime.getCurrentTime(); +}; + /** * Convert a position on screen (pixels) to a datetime * @param {int} x Position on the screen in pixels diff --git a/lib/timeline/Range.js b/lib/timeline/Range.js index 20e9abff..98349baa 100644 --- a/lib/timeline/Range.js +++ b/lib/timeline/Range.js @@ -35,6 +35,7 @@ function Range(body, options) { this.props = { touch: {} }; + this.animateTimer = null; // drag listeners for dragging this.body.emitter.on('dragstart', this._onDragStart.bind(this)); @@ -76,7 +77,7 @@ Range.prototype = new Component(); Range.prototype.setOptions = function (options) { if (options) { // copy the options that we know - var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable']; + var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate']; util.selectiveExtend(fields, this.options, options); if ('start' in options || 'end' in options) { @@ -101,16 +102,69 @@ function validateDirection (direction) { * Set a new start and end range * @param {Number} [start] * @param {Number} [end] + * @param {boolean | number} [animate=false] If true, the range is animated + * smoothly to the new window. + * If animate is a number, the + * number is taken as duration + * Default duration is 500 ms. + * */ -Range.prototype.setRange = function(start, end) { - var changed = this._applyRange(start, end); - if (changed) { - var params = { - start: new Date(this.start), - end: new Date(this.end) - }; - this.body.emitter.emit('rangechange', params); - this.body.emitter.emit('rangechanged', params); +Range.prototype.setRange = function(start, end, animate) { + this._cancelAnimation(); + + if (animate) { + var me = this; + var initStart = this.start; + var initEnd = this.end; + var duration = typeof animate === 'number' ? animate : 500; + var initTime = new Date().valueOf(); + var anyChanged = false; + function next() { + if (!me.props.touch.dragging) { + var now = new Date().valueOf(); + var time = now - initTime; + var s = util.easeInOutQuad(time, initStart, start, duration); + var e = util.easeInOutQuad(time, initEnd, end, duration); + changed = me._applyRange(s, e); + anyChanged = anyChanged || changed; + if (changed) { + me.body.emitter.emit('rangechange', {start: new Date(s), end: new Date(e)}); + } + + if (time <= duration) { + // animate with as high as possible frame rate, leave 20 ms in between + // each to prevent the browser from blocking + me.animateTimer = setTimeout(next, 20); + } + else { + // done + if (anyChanged) { + me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end)}); + } + } + } + } + + return next(); + } + else { + var changed = this._applyRange(start, end); + if (changed) { + var params = {start: new Date(this.start), end: new Date(this.end)}; + this.body.emitter.emit('rangechange', params); + this.body.emitter.emit('rangechanged', params); + } + } +}; + +/** + * Stop an animation + * @private + */ +Range.prototype._cancelAnimation = function () { + if (this.animateTimer) { + clearTimeout(this.animateTimer); + this.animateTimer = null; } }; @@ -284,6 +338,7 @@ Range.prototype._onDragStart = function(event) { this.props.touch.start = this.start; this.props.touch.end = this.end; + this.props.touch.dragging = true; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'move'; @@ -327,6 +382,7 @@ Range.prototype._onDragEnd = function (event) { // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; + this.props.touch.dragging = false; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'auto'; } diff --git a/lib/timeline/Timeline.js b/lib/timeline/Timeline.js index adb93774..a95c6f90 100644 --- a/lib/timeline/Timeline.js +++ b/lib/timeline/Timeline.js @@ -139,7 +139,7 @@ Timeline.prototype.setItems = function(items) { var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null; var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null; - this.setWindow(start, end); + this.setWindow(start, end, false); } }; @@ -172,14 +172,20 @@ Timeline.prototype.setGroups = function(groups) { * selected. If ids is an empty array, all items will be * unselected. * @param {Object} [options] Available options: - * `focus: boolean` If true, focus will be set - * to the selected item(s) + * `focus: boolean` + * If true, focus will be set to the selected item(s) + * `animate: boolean | number` + * If true (default), the range is animated + * smoothly to the new window. + * If a number, the number is taken as duration + * for the animation. Default duration is 500 ms. + * Only applicable when option focus is true. */ Timeline.prototype.setSelection = function(ids, options) { this.itemSet && this.itemSet.setSelection(ids); if (options && options.focus) { - this.focus(ids); + this.focus(ids, options); } }; @@ -195,8 +201,15 @@ Timeline.prototype.getSelection = function() { * Adjust the visible window such that the selected item (or multiple items) * are centered on screen. * @param {String | String[]} id An item id or array with item ids + * @param {Object} [options] Available options: + * `animate: boolean | number` + * If true (default), the range is animated + * smoothly to the new window. + * If a number, the number is taken as duration + * for the animation. Default duration is 500 ms. + * Only applicable when option focus is true */ -Timeline.prototype.focus = function(id) { +Timeline.prototype.focus = function(id, options) { if (!this.itemsData || id == undefined) return; var ids = Array.isArray(id) ? id : [id]; @@ -229,7 +242,8 @@ Timeline.prototype.focus = function(id) { var middle = (start + end) / 2; var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1); - this.range.setRange(middle - interval / 2, middle + interval / 2); + var animate = (options && options.animate !== undefined) ? options.animate : true; + this.range.setRange(middle - interval / 2, middle + interval / 2, animate); }; /** diff --git a/lib/timeline/component/CurrentTime.js b/lib/timeline/component/CurrentTime.js index f3193da8..2cbb4f70 100644 --- a/lib/timeline/component/CurrentTime.js +++ b/lib/timeline/component/CurrentTime.js @@ -22,6 +22,7 @@ function CurrentTime (body, options) { locale: 'en' }; this.options = util.extend({}, this.defaultOptions); + this.offset = 0; this._create(); @@ -83,7 +84,7 @@ CurrentTime.prototype.redraw = function() { this.start(); } - var now = new Date(); + var now = new Date(new Date().valueOf() + this.offset); var x = this.body.util.toScreen(now); var locale = this.options.locales[this.options.locale]; @@ -138,4 +139,25 @@ CurrentTime.prototype.stop = function() { } }; +/** + * Set a current time. This can be used for example to ensure that a client's + * time is synchronized with a shared server time. + * @param {Date | String | Number} time A Date, unix timestamp, or + * ISO date string. + */ +CurrentTime.prototype.setCurrentTime = function(time) { + var t = util.convert(time, 'Date').valueOf(); + var now = new Date().valueOf(); + this.offset = t - now; + this.redraw(); +}; + +/** + * Get the current time. + * @return {Date} Returns the current time. + */ +CurrentTime.prototype.getCurrentTime = function() { + return new Date(new Date().valueOf() + this.offset); +}; + module.exports = CurrentTime; diff --git a/lib/timeline/component/CustomTime.js b/lib/timeline/component/CustomTime.js index 85f04fcf..44c2a4da 100644 --- a/lib/timeline/component/CustomTime.js +++ b/lib/timeline/component/CustomTime.js @@ -125,10 +125,10 @@ CustomTime.prototype.redraw = function () { /** * Set custom time. - * @param {Date} time + * @param {Date | number | string} time */ CustomTime.prototype.setCustomTime = function(time) { - this.customTime = new Date(time.valueOf()); + this.customTime = util.convert(time, 'Date'); this.redraw(); }; diff --git a/lib/util.js b/lib/util.js index f2a5fd4c..03fcbe2c 100644 --- a/lib/util.js +++ b/lib/util.js @@ -1243,4 +1243,21 @@ exports.binarySearchGeneric = function(orderedItems, target, field, sidePreferen } } return guess; +}; + +/** + * Quadratic ease-in-out + * http://gizma.com/easing/ + * @param {number} t Current time + * @param {number} start Start value + * @param {number} end End value + * @param {number} duration Duration + * @returns {number} Value corresponding with current time + */ +exports.easeInOutQuad = function (t, start, end, duration) { + var change = end - start; + t /= duration/2; + if (t < 1) return change/2*t*t + start; + t--; + return -change/2 * (t*(t-2) - 1) + start; }; \ No newline at end of file