Giter Site home page Giter Site logo

torrobinson / datatables-contextual-actions Goto Github PK

View Code? Open in Web Editor NEW
15.0 2.0 4.0 106 KB

๐Ÿ–ฑ๏ธ A DataTables javascript plugin for adding context menus and buttons to your selected rows

Home Page: https://www.npmjs.com/package/datatables-contextual-actions

License: MIT License

JavaScript 50.30% CSS 4.14% HTML 45.56%
datatables datatable datatables-plugin jquery context menu buttons right-click datatables-js-extension contextual-options context-menu datatables-contextual-actions

datatables-contextual-actions's Introduction

datatables-contextual-actions

๐Ÿ‘‰View Example๐Ÿ‘ˆ

A DataTables JS extension for adding contextual options to one or many selected rows. Ideal if you want synchronized buttons and context-menu actions defined in a single place.

Context Menu

Button List

Button List Icon Only

This will alter your DataTables table in the following ways:

  • Your actions will be rendered as a row of buttons above your table
  • Right-clicking a row will select it and present the user with a context menu of your actions

Both can be individually enabled/disabled.

Dependencies:

  • DataTables, the world's most comprehensive jQuery-based table component

Getting Started:

  • Use DataTables in your project
  • Include the javascript and css in your project:
<!-- For example, use a CDN: -->
<link rel="stylesheet" href="https://unpkg.com/datatables-contextual-actions@latest/dist/dataTables.contextualActions.min.css"/>
<script src="https://unpkg.com/datatables-contextual-actions@latest/dist/dataTables.contextualActions.min.js"></script>
  • Initialize with a configuration (see the Configuration section below)
$(document).ready(function () {
	// Set up our table in standard DataTables fashion (with selection enabled)
	var myTable = $('#dt').DataTable({
		select: {
			style: 'os',
			selector: 'td:first-child',
		},
	});

	// And initialize our plugin.
	myTable.contextualActions({
		// Configuration options as described above
	});
});

Configuration:

options

Property Type Description Default
classes string[] CSS classes to apply to both the dropdown-menu and the button container []
iconPrefix string CSS class that icons will all start with.
For example, providing 'fas' will default an icon to
<i class="fas"></i>

...before it's assigned its actual icon class.
''
contextMenu contextMenu (see below) required
showConfirmationMethod function(confirmation) A function taking in a confirmation object (see the documentation on item's confirmation attribute) that handles how to render and show the confirmation to the user. By default this uses the super basic window.confirm but the incoming confirmation parameter matches the config of BootBox, a plugin for showing confirmations using Bootstrap's modals. If using Bootbox, replace with function(confirmation){bootbox.confirm(confirmation)} function(confirmation){ confirmation.callback( window.confirm( confirmation.message)); }
buttonList buttonList (see below) required
items item[] (see below) An array of item objects that represent the options that will be both rendered as buttons, and as options in a context menu. required
deselectAfterAction bool Whether or not to deselect all table rows after an item's action takes place. Note: if your action's code clears and redraws the table anyway, the selection state will be lost regardless of this option. Modify row data in the table itself using the DataTables API if you don't want to accidentally lose the selection state. true

options.contextMenu

Property Type Description Default
enabled bool Whether or not to display a context menu when the user right-clicks a row true
isMulti bool If true, multiple rows can be selected and then acted upon by right-clicking. If false, right-clicking will de-select all other rows before showing the context menu (default behaviour) false
xoffset int The horizontal distance away, in pixels, to render the drop-down context menu from the mouse -10
yoffset int The vertical distance away, in pixels, to render the drop-down context menu from the mouse -10
showSpeed string A CSS duration describing how quickly the context menu should displayed '0.30s'
headerRenderer string
or
function(rows)
or
false (bool)
What to display as the context menu's header.

Can be a static string or a function of the rows selected.

Set to false to skip rendering a header.
''
headerIsFollowedByDivider bool Controls if a divider is automatically added next to the header. (Ignored, if header is set to false.) false
showStaticOptions bool Whether or not to display static items in the context menu false
startsNewSelection bool Whether or not to start a new selection (deselect other rows) when isMulti is true and a non-selected row is right-clicked false

options.buttonList

Property Type Description Default
enabled bool Whether or not to render the options out into an external container as a series of button groups true
containerSelector string The CSS selector of the container element that the buttons will be rendered into.

For example, '#my-button-bar'
required
iconOnly bool Whether or not to only display icons in the buttons.

If true, buttons will only contain icons, and the option titles are turned into tooltips.
true
disabledOpacity decimal The opacity of a disabled button or context menu icon 0.5
dividerSpacing int The number of pixels between divided groups of buttons 10
groupClass string The class to give to the groups of buttons in the button list. Groups are the groupings of buttons separated with divider typed items. For example, with bootstrap, use btn-group ``

options.item[]

Property Type Description Default
type string
Items can be of the following types:


  • option is the standard type. It means the option is row-scoped and relies on row data to determine its action.


  • static means its action will not receive any data, and it mimics a DataTables button in that it is always visible and is table-scoped, not row-scoped.


  • divider acts simply as a divider item that splits up the above types when being rendered.

required
multi bool Whether or not to enable this button when more than 1 rows are selected false
title string
What the option is named.
The title is rendered as:

  • In buttons: the button text

  • In buttons when iconOnly is true: the button's tooltip


  • In context menus: the dropdown option's text


    ''
    multiTitle string The title (above) to render when more than 1 rows are selected ''
    iconClass string The class of the <i></i> styled icon to render.
    For example, if iconPrefix is 'fa fa-fw' and iconClass is 'fa-eye', then <i class="fa fa-fw fa-eye"></i> is rendered.

    Leave blank to render no icon.
    ''
    classes string[] An array of CSS classes to add onto the rendered item (either the button or the
    dropdown option)
    []
    contextMenuClasses string[] An array of CSS classes to add onto the rendered item (ONLY the
    dropdown version)
    []
    buttonClasses string[] An array of CSS classes to add onto the rendered item (ONLY the button version) []
    id string Optionally you may assign an id to the item's rendered element if you wish to target it with any custom code later on ''
    confirmation object
    or
    function(rows)
    The confirmation configuration object.

    Include a title and a message that will appear in the default browser confirm dialogue

    OR you may provide a confirmation object that matches that of Bootbox.js, and then override the default confirmation behavior by passing bootbox.confirm to options.showConfirmationMethod

    Example (default behavior):

    {
    title:'Foo',
    message:'Are you sure you want to Bar?'
    }


    Example (if using Bootbox):

    {
    title: 'Delete Item(s)',
    message: 'Do you want to delete the item(s)?',
    buttons: {
    cancel: {
    className: 'btn-link',
    label: 'Cancel'
    },
    confirm: {
    className: 'btn-danger',
    label: 'Delete'
    }
    }
    {}
    action function(rows) The action to execute against the 1 or more rows selected when the action was executed required
    isDisabled bool
    or
    function(row)
    Whether or not to totally disable the option.

    If a function of row is provided, this becomes a test to run against every selected row.
    If ANY of the rows pass this test, the option will be disabled

    For example, to disable the button for "John" rows:
    (row) => row.FirstName === 'John'
    {}
    isDisabledStrictMode bool Modifies the behavior of isDisabled (see above). If specified and is true, then rather than allowing a multi-enabled button to be clicked when ANY selected row is enabled/applicable, ONLY enable the option if ALL selected rows are enabled/applicable.

    isDisabledStrictMode ensures that ALL selected rows fail the isDisabled check (in other words, are ALL enabled) before allowing an action to be confirmed or executed
    false
    isHidden bool
    or
    function(row)
    Similar to the above isDisabled but renders an option hidden/invisible instead of just being disabled (greyed out) {}

    Please see the example page referred to above for a demo of how to use all these options together.

    Refreshing:

    If you change underlying data that some renderers rely on (isDisabled on a static-typed action, for example), and want to update the controls without having the user manually select/deselect rows, you can force-update contextualActions like so:

    $(document).ready(function () {
    	var myTable = $('#dt').DataTable({
    		// ...
    	});
    
    	// And initialize our plugin.
    	var myContextActions = myTable.contextualActions({
    		// ...
    	});
    
    	// Manually refresh the control and force all actions to be re-evaluated
    	myContextActions.update();
    });

    Development & Building:

    • Launch the included VSCode workspace file (datatables-contextual-actions.code-workspace)
    • Run npm i to install any dependencies
    • Perform any development and test in the ~/index.html file
    • When you're ready to build, execute the default build task (Ctrl + Shift + B)
    • Test the built changes in the ~/docs/index.html documentation/demo file

    datatables-contextual-actions's People

    Contributors

    kantorge avatar torrobinson avatar

    Stargazers

     avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

    Watchers

     avatar  avatar

    datatables-contextual-actions's Issues

    New option: allow the item's "isDisabled" to be ignored on multi

    Add a new option ignoreDisabledOnMulti: if true, when multiple rows are selected, skip over the isDisabled check.

    This could make it less confusing for users who, say, want to just select every row in a table/page and perform an action without having to filter invalid rows out first.

    Add UI tests with Playwright

    • Implement Playwright as a dev dependency
    • Add tests to validation options:
      • deselectAfterAction
      • contextMenu
        • enabled
        • isMulti
        • headerRenderer
        • showStaticOptions
      • buttonList
        • enabled
        • iconOnly
      • options
        • multi
        • title
        • multiTitle
        • isDisabled
        • isDisabledStrictMode
        • isHidden
    • Add to CI/CD to gate PRs

    MultiSelect on item behaviour question

    Hi,

    Great work!

    I've a question about multiselect on a context item. I've set all but one item to multi:false, then the one item I'd like to show when more than one item is selected.

    The functionality works if it's one or more, not more than one. The documentation says "More than one" .... Is this a bug in my stuff or the actual behaviour?

    Many thanks,

    Pete

    Remove Bootbox dependency

    Create a customization confirmation function so that any library could be used.
    Fallback on native js confirm().

    Combined with #2 , we can kill Bootstrap entirely.

    Make right-clicking a not-selected row, unselect all other rows with 'isMulti:true'

    First of all: really great extension!

    We have two main use-cases where we would like to make use of it, but it seems that only either of them can work, but not both together.

    1) Selecting multiple rows and then right-click on a selected row to execute an action on all selected rows
    This can be achieved when configuring isMulti: true on the contextMenu, and multi: true on the item(s).

    2) Selecting multiple rows and then right-click on an unselected row to only execute an action on that single row
    This can be achieved when configuring isMulti: false on the context Menu.

    However, we would like to have both use-cases work at the same time. Therefore we first thought we can achieve this by setting isMulti: false on the contextMenu, but keeping multi: true on the items. Unfortunately, it does not work and right-clicking on a selected row will unselect all other selected rows.

    Would there be a possibility to extend the configuration to allow for both use-cases to work simultaneously?

    Add an option to make the dropdown-menu unique on a page with multiple dataTables

    When we have multiple DataTables on the same page; each dataTable can have it's own dropdown-menu open at the same time.
    We woud like to avoid this and make sure there is only ever one dropdown-menu open across all dataTables.

    A workaround I have found for this is to "misuse" the headerRenderer function to count the number of div.dropdown-menu elements present on the page. If there is >1, then I compare the dataTable-Id with the Id of the dropdown (since it starts with that) and then remove the not-matching div.dropdown-menu.

    headerRenderer: () => {
        if ($('div.dropdown-menu').length > 1) {
            $('div.dropdown-menu').each((k, v) => {
                if (!v.id.startsWith(tableId)) $(v).remove();
            });
        }
        return 'header label';
    }

    Maybe this behaviour could be added as a configuration option?

    Remove Bootstrap dependency

    Write own dropdown js + css that uses Bootstrap's styling, but falls back on our own if Bootstrap doesn't exist.

    Combined with #1 , we can kill Bootstrap entirely.

    Improvement Request - Menu Max Bounds

    Hello,

    We have a feature request to bound to the menu so that it will not extend past the bottom of the page. We are currently using a large menu with a 100vh datatable and when you open the menu near a bottom row, it extends past the bottom and activates the page scroll. I was hoping you could implement a way for the menu to be bound to the bottom of the current page at max and then extend upward based on the size of the menu. I have attached a picture, the black background is hidden and not scrollable until the menu is opened.

    Overall, this is nearly perfect and a great addition to our end product.

    2023-03-27_19-52-47

    Cannot get 'static' Context Menu Item to Display

    Attempting to display a table-level context menu item disassociated from the row and cannot get any attempt of type: 'static' to display.

    items: [
      {
        type: 'static',
        title: 'Static Button',
        iconClass: 'fa-lock',
        buttonClasses: ['btn', 'btn-outline-primary'],
        action: function () {
          bootbox.alert(
            "I am a static button that doesn't care about what row is selected. I'm always clickable!"
          );
        }
    }
    

    Per reviewing the CSS it seems like an empty h6 object is there without any text.

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google โค๏ธ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.