@logimaxx/kgrid 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +9 -0
- package/LICENSE +34 -0
- package/NOTICE.md +24 -0
- package/README.md +151 -0
- package/dist/kgrid.js +2051 -0
- package/dist/kgrid.min.js +2 -0
- package/docs/ai-guide.md +273 -0
- package/docs/api.md +191 -0
- package/docs/configuration.md +337 -0
- package/docs/field-types.md +92 -0
- package/docs/integration.md +81 -0
- package/docs/table-shell.md +110 -0
- package/integrations/kgrid-plugin-demo-select.js +99 -0
- package/integrations/kgrid-widgets.js +136 -0
- package/integrations/maxxops.example.js +16 -0
- package/package.json +57 -0
- package/src/cells.js +113 -0
- package/src/config.js +59 -0
- package/src/configure.js +136 -0
- package/src/constants.js +113 -0
- package/src/data-body.js +99 -0
- package/src/dom.js +123 -0
- package/src/events.js +100 -0
- package/src/field-types-builtins.js +25 -0
- package/src/field-types.js +228 -0
- package/src/filters.js +394 -0
- package/src/init.js +199 -0
- package/src/insert-row.js +172 -0
- package/src/interaction.js +43 -0
- package/src/labels.js +49 -0
- package/src/table-shell.js +152 -0
- package/styles/table.css +201 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @logimaxx/kgrid | (c) Logimaxx System SRL — proprietary | https://logimaxx.ro | built 2026-07-30T15:53:29.364Z */
|
|
2
|
+
!function(t){const e={log:function(){},onError:function(t){console.error(t)},confirm:function(t,e,n){"undefined"!=typeof window&&window.confirm(t)?e():n&&n()},deleteConfirm:null,serializeForm:function(t,e){const n=new FormData(t),r={};for(const[t,e]of n.entries())Object.prototype.hasOwnProperty.call(r,t)?(Array.isArray(r[t])||(r[t]=[r[t]]),r[t].push(e)):r[t]=e;return r},customInputTypes:null,fieldTypes:null,kviews:null,filterDebounceMs:300};t._config=Object.assign({},e),t.configure=function(e){return e&&"object"==typeof e&&Object.assign(t._config,e),"function"==typeof t._syncCustomInputTypes&&t._syncCustomInputTypes(),t},t.log=function(){t._config.log.apply(null,arguments)},t.onError=function(e){return t._config.onError(e)},t.confirm=function(e,n,r){return t._config.confirm(e,n,r)},t.DEFAULT_DELETE_CONFIRM_MESSAGE="Delete this record?",t._defaultDeleteConfirm=function(e,n,r){t.confirm(t.DEFAULT_DELETE_CONFIRM_MESSAGE,n,r)},t.runDeleteConfirm=function(e,n,r){const o=e.options&&"function"==typeof e.options.deleteConfirm?e.options.deleteConfirm:null,a="function"==typeof t._config.deleteConfirm?t._config.deleteConfirm:null;return(o||a||t._defaultDeleteConfirm)(e,n,r)},t.serializeForm=function(e,n){return t._config.serializeForm(e,n)},t.getKViews=function(e){const n=[e,t._config.kviews];for(let t=0;t<n.length;t++){const e=n[t];if(e&&"function"==typeof e.createCollectionInstance)return e}const r=("undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:{}).KViews;return r&&"function"==typeof r.createCollectionInstance?r:null},t.KVIEWS_MISSING_MSG="KGrid requires KViews: install peer @logimaxx/kviews, load it before kgrid.js (window.KViews), or call KGrid.configure({ kviews: KViews }). You can also pass kviews in table options: KGrid.init(host, { kviews, ... })."}(window.KGrid=window.KGrid||{}),function(t){t.protoOptions={url:null,type:null,filter:null,features:{filtering:!1,sorting:!1,paging:!1,create:!1,update:!1,delete:!1},defaultInteraction:"view",insertFormRow:{position:"top"},tableAttrs:{class:""},labelsRowAttrs:{},dataRowAttrs:{},filtersRowAttrs:null,pagingPageSizes:[10,25,50,75],pagingDefaultSize:10,emptyRowMessage:null,pagingFooterLabel:"records per page. Total"},t.protoColumnConfig={label:null,name:null,hidden:!1,class:null,columnClass:null,attrs:{},features:{create:!1,update:!1,filter:!1,sort:!1},display:{template:null,events:[]},input:null,insert:{type:"text",default:null,value:null,placeholder:null,disabled:!1,required:!1,options:null,events:[]},update:{type:"text",default:null,value:null,placeholder:null,disabled:!1,required:!1,options:null,template:null,events:[]},filter:{type:"text",operator:"~=~",default:null,placeholder:"",options:null,persist:!1,debounceMs:null}},t.VALID_NATIVE_INPUT_TYPES=["displayonly","text","textarea","number","date","datetime","time","checkbox","radio","file","password","email","url","search","tel","select","hidden"],t.VALID_INPUT_TYPES=t.VALID_NATIVE_INPUT_TYPES.slice(),t.VALID_NATIVE_FILTER_TYPES=t.VALID_NATIVE_INPUT_TYPES.filter(t=>"displayonly"!==t),t.VALID_FILTER_TYPES=t.VALID_NATIVE_FILTER_TYPES.concat(["multi_select","date_range"]),t.isValidInputType=function(e){return t.VALID_NATIVE_INPUT_TYPES.includes(e)||t.isPluggableFieldType(e)},t.isValidFilterType=function(e){return"displayonly"!==e&&(t.VALID_NATIVE_FILTER_TYPES.includes(e)||t.isPluggableFieldType(e))}}(window.KGrid=window.KGrid||{}),function(t){t.isPlainObject=function(t){return null!=t&&"object"==typeof t&&!Array.isArray(t)},t.setDefaultValues=function(e,n){const r={...e||{}};return Object.keys(n||{}).forEach(e=>{t.isPlainObject(n[e])&&t.isPlainObject(r[e])?r[e]=t.setDefaultValues(r[e],n[e]):t.isPlainObject(n[e])&&null==r[e]?r[e]=t.setDefaultValues({},n[e]):r[e]=n[e]}),r},t.normalizeColumnConfig=function(e){let n=e&&"object"==typeof e?{...e}:{};if(t.isPlainObject(n.input)){const e={...n.input};delete n.input,n.insert=t.setDefaultValues(e,n.insert||{}),n.update=t.setDefaultValues(e,n.update||{})}const r=t.setDefaultValues(t.protoColumnConfig,n);return null==r.class&&r.columnClass&&(r.class=r.columnClass),r.update&&"displayonly"===r.update.type&&!r.update.template&&r.display&&r.display.template&&(r.update.template=r.display.template),["display","insert","update"].forEach(t=>{r[t]&&"object"==typeof r[t]&&(Array.isArray(r[t].events)||(r[t].events=[]))}),r}}(window.KGrid),function(t){t.resolveHostElement=function(t){if(null==t)throw new TypeError("KGrid.init(host, opts): host is required");if("object"==typeof t&&t.jquery){if(!t.length)throw new Error("KGrid.init(host, opts): empty jQuery selection");return t}if("object"==typeof t&&1===t.nodeType&&"string"==typeof t.nodeName)return $(t);throw new TypeError("KGrid.init(host, opts): host must be a DOM Element or jQuery object")},t.uuid=function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)},t.hasActionColumn=function(t){const e=t&&t.features;return!!e&&!!(e.delete||e.update||e.create)},t.syncActionColumnColgroup=function(t,e,n){let r=t.children("colgroup.kgrid-colgroup");r.length||(r=$("<colgroup>").addClass("kgrid-colgroup").prependTo(t)),r.empty();for(let t=0;t<e;t++)r.append($("<col>"));n&&r.append($("<col>").addClass("kgrid-row-actions-col"))},t.anchorRowForm=function(t,e){if(!(t&&t.length&&e&&e.length))return t;t.attr("hidden","hidden").attr("aria-hidden","true");const n=e.children("td").first();return n.length&&t.prependTo(n),t},t.filterFormField=function(t,e){if(!t||!e)return $();const n=t.elements&&t.elements.namedItem(e);if(n)return $(n);if(t.id){const n=document.querySelector(`[form="${t.id}"][name="${e}"]`);if(n)return $(n)}return $()},t.columnClassName=function(t){if(!t)return null;const e=null!=t.class&&""!==t.class?t.class:t.columnClass;return null!=e&&""!==e?String(e):null},t.applyColumnCellMeta=function(e,n){if(!e||!e.length||!n)return e;n.name&&e.attr("data-name",n.name);const r=t.columnClassName(n);return r&&e.addClass(r),e}}(window.KGrid),function(t){t.DEFAULT_EMPTY_ROW_MESSAGE="No records match your search.",t.TABLE_SHELL_TEMPLATE='\n<table class="custom-table" style="table-layout: fixed;">\n <thead class="thead-labels">\n <tr>\n <th class="align-top">\n <a class="sort" data-sortfld="" style="cursor: pointer;">\n <span class="column-label"></span>\n <i class="fas fa-sort-up sort-up" style="display: none"></i>\n <i class="fas fa-sort-down sort-down" style="display: none"></i>\n <i class="fas fa-sort sort-default"></i>\n </a>\n </th>\n </tr>\n </thead>\n <thead class="thead-filters"></thead>\n <tbody class="before-main-tbody"></tbody>\n <tbody class="main-tbody"></tbody>\n <tbody class="after-main-tbody"></tbody>\n <tbody class="no-data-tbody">\n <tr><td>{{EMPTY_ROW_MESSAGE}}</td></tr>\n </tbody>\n <tfoot class="paging-footer">\n <tr>\n <td>\n <div class="btn-group pages" data-pagesize="{{PAGES_DATA_PAGESIZE}}">\n <button type="button" name="first" class="btn btn-sm btn-outline-secondary"><<</button>\n <button type="button" name="prev" class="btn btn-sm btn-outline-secondary"><</button>\n <button type="button" name="page" class="btn btn-sm btn-outline-secondary">1</button>\n <button type="button" name="next" class="btn btn-sm btn-outline-secondary">></button>\n <button type="button" name="last" class="btn btn-sm btn-outline-secondary">>></button>\n </div>\n <select class="pagesize">\n{{PAGE_SIZE_OPTIONS}}\n </select>\n {{PAGING_FOOTER_LABEL}} <span class="totalrecscount"></span>\n </td>\n </tr>\n </tfoot>\n</table>'.trim(),t._escapeTableShellText=function(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")},t._renderPageSizeOptions=function(t,e){return t.map(t=>{const n=String(t);return` <option value="${n}"${n===String(e)?" selected":""}>${n}</option>`}).join("\n")},t.renderTableShellHtml=function(e,n){const r=Array.isArray(e.pagingPageSizes)?e.pagingPageSizes:[10,25,50,75],o=null!=e.pagingDefaultSize?e.pagingDefaultSize:r[0],a=t._escapeTableShellText(e.emptyRowMessage||t.DEFAULT_EMPTY_ROW_MESSAGE),l=t._escapeTableShellText(e.pagingFooterLabel||"records per page. Total");return(n||t.TABLE_SHELL_TEMPLATE).replace(/\{\{EMPTY_ROW_MESSAGE\}\}/g,a).replace(/\{\{PAGES_DATA_PAGESIZE\}\}/g,String(o)).replace(/\{\{PAGE_SIZE_OPTIONS\}\}/g,t._renderPageSizeOptions(r,o)).replace(/\{\{PAGING_FOOTER_LABEL\}\}/g,l)},t.createTableShell=function(e){const n=t.renderTableShellHtml(e),r=$.parseHTML(n,document,!0),o=$(r).filter("table").first();if(!o.length)throw new Error("KGrid TABLE_SHELL_TEMPLATE must contain a root <table> element");return e.tableAttrs&&t.isPlainObject(e.tableAttrs)&&(Object.keys(e.tableAttrs).forEach(t=>{"class"!==t&&o.attr(t,e.tableAttrs[t])}),"string"==typeof e.tableAttrs.class&&e.tableAttrs.class&&o.addClass(e.tableAttrs.class)),o},t.mountTableShell=function(e,n){const r=e.find("table.custom-table, table").first();if(r.length)return r;const o=t.getTableInteractionHost(e);o.hasClass("custom-table-shell")||o.addClass("custom-table-shell");const a=t.createTableShell(n);return o.append(a),a}}(window.KGrid),function(t){t._fieldTypes=Object.create(null),t._configuredCustomInputTypeNames=[],t.registerFieldType=function(e,n,r){if(!e||"string"!=typeof e)throw new TypeError("registerFieldType(name, plugin): name must be a string");if(!n||"function"!=typeof n.create)throw new TypeError("registerFieldType("+e+"): plugin.create is required");if(t._fieldTypes[e]&&(!r||!r.overwrite))throw new Error("Field type already registered: "+e);return t._fieldTypes[e]=Object.assign({name:e},n),t},t.unregisterFieldType=function(e){return e&&t._fieldTypes[e]&&delete t._fieldTypes[e],t},t.getFieldType=function(e){return e&&t._fieldTypes[e]||null},t.listFieldTypes=function(){return Object.keys(t._fieldTypes)},t.createFieldInput=function({mode:e,col:n,config:r}){const o=r.type??"text",a=t.getFieldType(o);if(!a)return null;"function"==typeof a.validate&&a.validate(r,e,n);const l=a.create({mode:e,col:n,config:r});if(!l||!l.$input||!l.$input.length)throw new Error('Field type "'+o+'" create() must return { $input: jQuery }');return l.$input.attr("data-type",o),l},t.mountField=function(e){const n=e.config?.type??e.type,r=t.getFieldType(n);r&&"function"==typeof r.mount&&r.mount(e)},t.resolveFilterEvents=function({plugin:t,$input:e,createResult:n}){let r;return n&&Object.prototype.hasOwnProperty.call(n,"filterEvents")?r=n.filterEvents:t&&Object.prototype.hasOwnProperty.call(t,"filterEvents")&&(r=t.filterEvents),!1===r||null===r?null:"string"==typeof r&&r.trim()?r.trim():e.is("select")?"change":"input"},t.normalizeFilterDebounceMs=function(t,e){if(!1===t)return 0;if(void 0===t)return e;if(null===t)return e;const n=Number(t);return!Number.isFinite(n)||n<0?0:n},t.resolveFilterDebounceMs=function({filterConfig:e,plugin:n}){return e&&Object.prototype.hasOwnProperty.call(e,"debounceMs")&&null!==e.debounceMs?t.normalizeFilterDebounceMs(e.debounceMs,0):n&&Object.prototype.hasOwnProperty.call(n,"filterDebounceMs")&&null!==n.filterDebounceMs?t.normalizeFilterDebounceMs(n.filterDebounceMs,0):t.normalizeFilterDebounceMs(t._config.filterDebounceMs,0)},t.shouldDebounceFilterSubmit=function(t,e){return!(!e||e<=0)&&!!t},t.bindFieldFilterSubmit=function(e,n,r){const o=t.getFieldType(e);o&&"function"==typeof o.bindFilterSubmit&&o.bindFilterSubmit(n,r)},t.bindFilterInputEvents=function({type:e,$input:n,onSubmit:r,createResult:o,filterConfig:a}){const l=e?t.getFieldType(e):null,i=t.resolveFilterEvents({plugin:l,$input:n,createResult:o}),s=t.resolveFilterDebounceMs({filterConfig:a,plugin:l}),u=t.wrapFilterSubmitHandler(n,r,i,s);i&&n.on(i,u),t.bindFieldFilterSubmit(e,n,u)},t.isPluggableFieldType=function(e){return!!t.getFieldType(e)},t.inputType=function(t,e){if("function"!=typeof t)throw new TypeError("inputType(mount, opts): mount must be a function");if(!e||"string"!=typeof e.element)throw new TypeError("inputType(mount, opts): opts.element is required (HTML string)");return{filterEvents:e.filterEvents,filterDebounceMs:e.filterDebounceMs,validate:e.validate,create({mode:t}){const n=$(e.element);return!e.formInputClass||"insert"!==t&&"update"!==t||n.addClass(e.formInputClass),{$input:n,skipValueAttr:!!e.skipValueAttr}},mount(e){t(e.$input,e.config?.options??e.config,e)},bindFilterSubmit:e.bindFilterSubmit}},t._getCustomInputTypesConfig=function(){return t._config.customInputTypes??t._config.fieldTypes??null},t._syncCustomInputTypes=function(){const e=t._getCustomInputTypesConfig(),n=e&&"object"==typeof e?Object.keys(e).filter(t=>null!=e[t]):[];t._configuredCustomInputTypeNames.forEach(e=>{n.includes(e)||t.unregisterFieldType(e)}),n.forEach(n=>{const r=e[n];if(!r||"object"!=typeof r||"function"!=typeof r.create){if("function"==typeof r)throw new Error("customInputTypes."+n+' is a function — use a plugin, e.g. KGrid.select2(fn) or KGrid.inputType(fn, { element: "..." })');throw new TypeError("customInputTypes."+n+" must be a plugin with create()")}t.registerFieldType(n,r,{overwrite:!0})}),t._configuredCustomInputTypeNames=n.slice()}}(window.KGrid),function(t){t.registerFieldType("multi_select",{create({config:t}){const e=$("<select class='form-select form-select-sm' multiple>");return Array.isArray(t.options)&&t.options.forEach(t=>{$("<option>").text(t.label).attr("value",t.value).appendTo(e)}),{$input:e,skipValueAttr:!0}}}),t.registerFieldType("date_range",{create:()=>({$input:$("<input autocomplete='off' type='date' class='form-control form-control-sm'/>")})})}(window.KGrid),function(t){t.resolveDefaultInteraction=function(t){return"edit"===t.defaultInteraction||"view"===t.defaultInteraction?t.defaultInteraction:!0===t.editmode?"edit":(t.editmode,"view")},t.getTableInteractionHost=function(t){if(t.hasClass("custom-table-shell"))return t;const e=t.find(".custom-table-shell").first();return e.length?e:t},t.applyInteraction=function(e,n,r){const o=t.getTableInteractionHost(e),a="edit"===n?"edit":"view";o.attr("data-interaction",a),r&&"object"==typeof r?(void 0!==r.create&&o.attr("data-allow-insert",r.create?"true":"false"),void 0!==r.update&&o.attr("data-allow-update",r.update?"true":"false"),void 0!==r.delete&&o.attr("data-allow-delete",r.delete?"true":"false")):"edit"===a&&o.removeAttr("data-allow-insert data-allow-update data-allow-delete")}}(window.KGrid),function(t){t.setupLabelsHeader=function(e,n){const r=e.children("tr"),o=r.children(),a=o.first().clone(!0);o.remove();return[...n.columns].forEach(e=>{if(e.hidden)return;let n=a.clone(!0);if(e.attrs&&"object"==typeof e.attrs&&Object.keys(e.attrs).forEach(t=>n.attr(t,e.attrs[t])),t.applyColumnCellMeta(n,e),!e.features?.sort){const o=n.empty().html(e.label??"");return t.applyColumnCellMeta(o,e),void r.append(o)}if(!e.name)throw new Error("Column must have a name when column.sortable is true: \n"+JSON.stringify(e,null,2));n.find("span.column-label").text(e.label??""),n.children("a").attr("data-sortfld",e.name),n.appendTo(r)}),t.hasActionColumn(n)&&$("<th>").addClass("kgrid-row-actions").attr("aria-label","Actions").appendTo(r),r}}(window.KGrid),function(t){const e="kgridFilterDebounceTimer";t.cancelFilterSubmit=function(t){const n=t.data(e);n&&(clearTimeout(n),t.removeData(e))},t.cancelFilterDebounces=function(e){const n=$(e).attr("id");n&&$(document).find("[form='"+n+"']").each(function(){t.cancelFilterSubmit($(this))})},t.flushFilterSubmit=function(t){const n=t.data(e);if(!n)return;clearTimeout(n),t.removeData(e);const r=t[0]&&t[0].form;r&&$(r).trigger("submit")},t.wrapFilterSubmitHandler=function(n,r,o,a){if(!t.shouldDebounceFilterSubmit(o,a))return r;const l=a;return function(){t.cancelFilterSubmit(n);const o=setTimeout(function(){n.removeData(e),r.call(this)}.bind(this),l);n.data(e,o)}},t.filterDefaultValue=function(t){return null!=t&&"object"==typeof t&&null!=t.value?t.value:t},t.columnFilterPersisted=function(t){const e=t&&t.filter?t.filter:{};return!(!t||!t.hidden&&"hidden"!==e.type&&!e.persist)},t.ensureFilterField=function(t,e,n,r){if(!t||!e||null==n||""===n)return null;let o=t.elements&&t.elements.namedItem(e);return o&&null!=o.length&&!o.tagName&&(o=o[0]),o&&o.tagName||(o=document.createElement("input"),o.type="hidden",o.name=e,t.appendChild(o)),o.setAttribute("data-operator",r||"="),o.value=String(n),o.defaultValue=String(n),o},t.applyColumnDefaultFilters=function(e,n){e&&n&&n.forEach(function(n){if(!n.name||n.features&&!1===n.features.filter)return;const r=n.filter;if(!r||null==r.default||""===r.default)return;const o=t.filterDefaultValue(r.default);if(null==o||""===o)return;const a=r.operator||(t.columnFilterPersisted(n)?"=":"~=~"),l=t.filterFormField(e,n.name);!n.hidden&&"hidden"!==r.type&&l.length?l.val()||(l.val(String(o)),l.attr("data-operator",a)):t.ensureFilterField(e,n.name,o,a)})},t.setupDefaultFilters=function(e,n,r){const o=$(e)[0];if(!(o&&n&&n.features&&n.features.filtering))return;const a=n.columns||[];if(t.applyColumnDefaultFilters(o,a),a.some(t.columnFilterPersisted)){let e=!1;$(o).off("reset.kgridDefaultFilters").on("reset.kgridDefaultFilters",function(n){if(!e){n.preventDefault(),t.cancelFilterDebounces(o),e=!0;try{o.reset(),t.applyColumnDefaultFilters(o,a),r&&r.filtering&&"function"==typeof r.filtering.handleSubmit?r.filtering.handleSubmit(o):$(o).trigger("submit")}finally{e=!1}}})}if(!r||!r.filtering)return;const l=a.filter(function(e){return e.name&&e.filter&&null!=e.filter.default&&""!==e.filter.default&&t.columnFilterPersisted(e)});if(!l.length)return;const i=String(r.url&&r.url.parameters&&r.url.parameters.filter||"");l.some(function(t){return-1===i.indexOf(t.name+"=")})&&r.filtering.handleSubmit(o)},t.setupFilterHeader=function(e,n){if(!n.features||!n.features.filtering)return null;const r=e.find(".thead-filters");r.empty();const o=[...n.columns],a=$("<tr>");a.appendTo(r);const l="filter_form_"+t.uuid(),i=$("<form>").attr("id",l).attr("hidden","hidden").attr("aria-hidden","true").addClass("table-filter-form").insertBefore(e);return o.forEach(e=>{const n=e.filter||{};if(e.hidden||"hidden"===n.type){if(e.features&&!1===e.features.filter)return;if(!e.name)return;const r=t.filterDefaultValue(n.default);return void(null!=r&&""!==r?t.ensureFilterField(i[0],e.name,r,n.operator||"="):t.columnFilterPersisted(e)&&t.ensureFilterField(i[0],e.name,"",n.operator||"="))}let r,o=$("<th>").appendTo(a).attr("data-label",e.label);if(t.applyColumnCellMeta(o,e),!1===e.features.filter)return;if(!e.name)throw new Error("Column must have a name when column.features.filter is true: \n"+JSON.stringify(e,null,2));let s=null;const u=t.createFieldInput({mode:"filter",col:e,config:n});if(u)s=u,r=u.$input,r.appendTo(o),t.mountField({mode:"filter",$input:r,col:e,config:n});else if("select"===n.type){if(!n.options)throw new Error("Column must have a filter.options array when column.filter.type is select: \n"+JSON.stringify(e,null,2));if(r=$("<select>").addClass("form-select form-select-sm"),!Array.isArray(n.options))throw new Error("Column must have a filter.options array when column.filter.type is select: \n"+JSON.stringify(e,null,2));n.options.forEach(t=>{if(!t.label||"string"!=typeof t.value)throw new Error("Column must have an filter.options object with label and value when column.filter.type is select: \n"+JSON.stringify(e,null,2));$("<option>").text(t.label).attr("value",t.value).appendTo(r)}),r.appendTo(o)}else{if(!t.isValidFilterType(n.type))throw new Error("Unknown filter type: "+n.type);r=$(`<input autocomplete='off' type='${n.type}' class='form-control form-control-sm'/>`),r.appendTo(o)}r.attr("data-operator",n.operator),r.attr("form",l),r.attr("name",e.name);const c=t.filterDefaultValue(n.default);null==c||""===c||r.val()||(r.val(String(c)),r.attr("data-default",String(c)),r[0]&&(r[0].defaultValue=String(c)));t.bindFilterInputEvents({type:n.type,$input:r,onSubmit:function(){const t=this.form;t&&$(t).trigger("submit")},createResult:s,filterConfig:n})}),t.hasActionColumn(n)&&$("<th>").addClass("kgrid-row-actions").attr("data-label","Actions").appendTo(a),i},t.FilterForm=function(e){this.form=$(e)[0],this.filter=(e,n,r="~=~")=>{if(!this.form)return this;let o=t.filterFormField(this.form,e);if(o.length||(t.ensureFilterField(this.form,e,n,r),o=t.filterFormField(this.form,e)),!o.length)return this;t.flushFilterSubmit(o),o.val(n);const a=o.attr("data-operator");return o.attr("data-operator",r),$(this.form).trigger("submit"),o.attr("data-operator",a),this},this.ensure=(e,n,r="=")=>(t.ensureFilterField(this.form,e,n,r),this),this.reset=()=>(this.form&&(t.cancelFilterDebounces(this.form),this.form.reset()),this)}}(window.KGrid),function(t){t.setupCell=function(e,n){const r=n?n.attr("id"):null,o={...e},a=$("<td>").attr("data-label",e.label);t.applyColumnCellMeta(a,e);const l=o.attrs&&"object"==typeof o.attrs?o.attrs:{};Object.keys(l).forEach(t=>a.attr(t,l[t]));let i=$("<div>").addClass("cell-content");if(i.html(o.display.template??`{{${o.name}}}`),i.appendTo(a),null==n||!e.features.update)return i.clone(!0).removeClass("cell-content").addClass("cell-input").appendTo(a),a;if(!o.name)throw new Error("Column must have a name when column.features.update is true: \n"+JSON.stringify(e,null,2));const s=o.update,u=s.type??"text";let c,f=!1;const d=t.createFieldInput({mode:"update",col:e,config:s});if(d)c=d.$input,f=!!d.skipValueAttr;else{switch(u){case"textarea":c=$(`<textarea class='form-input form-control form-control-sm'>{{${s.value??o.name}}}</textarea>`),f=!0;break;case"select":if(c=$("<select class='form-input form-control form-control-sm'/>"),!Array.isArray(s.options))throw new Error("Select column must have an update.options array when column.features.update is true: \n"+JSON.stringify(e,null,2));s.options.forEach(t=>{if("string"!=typeof t.label||void 0===t.value)throw new Error("Select update.options entries need label and value: \n"+JSON.stringify(e,null,2));$("<option>").text(t.label).attr("value",t.value).appendTo(c)}),f=!0;break;case"hidden":c=$("<input type='hidden' class='form-input form-control form-control-sm'/>");break;case"displayonly":{const t=s.template||o.display.template||`{{${o.name}}}`;return $("<div>").addClass("cell-input").append(t).appendTo(a),a}default:if(!t.isValidInputType(u))throw new Error("Invalid update updateConfig type: "+JSON.stringify(s,null,2));c=$(`<input autocomplete='off' type='${u}' class='form-input form-control form-control-sm'/>`)}c.attr("data-type",u)}if(s.attrs&&"object"==typeof s.attrs&&Object.keys(s.attrs).forEach(t=>c.attr(t,s.attrs[t])),c.attr("form",r),c.attr("name",o.name),!f&&"textarea"!==u){const t=s.value??`{{${o.name}}}`;null!=t&&"object"!=typeof t&&c.attr("value",t)}return o.hidden?(c.attr("type","hidden").appendTo(n),a):(s.disabled&&c.attr("disabled",!0),s.readonly&&c.attr("readonly",!0),s.required&&c.attr("required",!0),s.attrs&&"object"==typeof s.attrs&&Object.keys(s.attrs).forEach(t=>c.attr(t,s.attrs[t])),s.disabled||s.readonly||c.attr("onchange","$(this).parents('tr').addClass('editing')"),$("<div>").addClass("cell-input").append(c).appendTo(a),a)}}(window.KGrid),function(t){t.setupNoDataTbody=function(t,e,n){const r=t.find("td").attr("colspan",n);return e.noDataTemplate&&r.html(e.noDataTemplate),r},t.setupDataBody=function(e,n,r,o,a,l){const i=[...n.columns],s=$("<tr>").appendTo(e);if(n.dataRowAttrs&&"object"!=typeof n.dataRowAttrs)throw new Error("options.dataRowAttrs must be an object");const u={...n.dataRowAttrs??{}};Object.keys(u).forEach(t=>s.attr(t,u[t])),e.data("emptyview",l),n?.features?.sorting&&e.data("sort",r),a&&e.data("paging",a.find(".pages")).data("pagesizeinp",a.find(".pagesize")).data("totalrecscount",a.find(".totalrecscount")),o&&e.data("filter",o),n.type&&e.data("type",n.type);const c="data_row_form_"+t.uuid()+"_{{this.id}}",f=n.features.update?$("<form class='edit-form table-row-form'>").attr("id",c):null;if(i.forEach(e=>{const n=t.setupCell(e,f);e.hidden||n.appendTo(s)}),t.hasActionColumn(n)){const t=$("<td>").addClass("kgrid-row-actions").appendTo(s);if(n.features.delete&&$("<div>").addClass("btn-group delete-item-grp").appendTo(t).append($("<button>").addClass("btn btn-sm btn-danger delete-item").attr("type","button").attr("title","Delete item").append("<i class='fas fa-trash'></i>")),n.features.update){const e=$("<div>").addClass("btn-group edit-item-grp").appendTo(t);$("<button>").addClass("btn btn-sm btn-success save-item").attr("type","submit").attr("name","save").attr("title","Save item").attr("form",c).html("<i class='fas fa-save'></i>").appendTo(e),$("<button>").addClass("btn btn-sm btn-secondary cancel-edit").attr("type","button").attr("name","cancel").attr("title","Cancel edit").attr("form",c).attr("onclick","$(this).parents('[data-type=item]').data().instance.loadFromRemote()").html("<i class='fas fa-undo'></i>").appendTo(e)}}return f&&t.anchorRowForm(f,s),e},t.setupPagingFooter=function(e,n,r){return t.log("setupPagingFooter",e,n,r),n.pagingFooterAttrs&&t.isPlainObject(n.pagingFooterAttrs)&&Object.keys(n.pagingFooterAttrs).forEach(t=>e.attr(t,n.pagingFooterAttrs[t])),t.log("noVisibleCols",r),e.find("td").attr("colspan",r),e}}(window.KGrid),function(t){t.setupNewRecordForm=function(e,n,r){if(!n.insertFormRow||!t.isPlainObject(n.insertFormRow))return e.find(".before-main-tbody").remove(),void e.find(".after-main-tbody").remove();const o=[...n.columns],a=$("<tr>").addClass("new-record-row");"top"===(n.insertFormRow?.position??"top")?(e.find(".after-main-tbody").remove(),a.appendTo(e.find(".before-main-tbody"))):(e.find(".before-main-tbody").remove(),a.appendTo(e.find(".after-main-tbody")));const l="new_record_row_form_"+t.uuid(),i=$("<form class='table-row-form'>").attr("id",l).off("submit").on("submit",e=>{e.preventDefault();const a=t.serializeForm(e.target,o);Object.keys(a).forEach(t=>{o.find(e=>e.name===t)?.insert?.dontsave&&delete a[t]}),r.instance.newItem(a).then(()=>{e.target.reset(),"function"==typeof n.onNewItemCreated&&n.onNewItemCreated(a)}).catch(t.onError)});o.forEach(e=>{if(e.hidden){if(n.features?.create&&e.features?.create){const t=$("<input type='hidden'>").attr("name",e.name).attr("form",l).appendTo(i);e.insert.default&&t.val(e.insert.default)}return}if(!e.features.create){const n=$("<td>").appendTo(a).attr("data-label",e.label);return void t.applyColumnCellMeta(n,e)}const r=e.insert;if(!r||!t.isPlainObject(r))throw new Error("Column must have an insert config object when column.features.create is true: \n"+JSON.stringify(e,null,2));if(!r.type)throw new Error("Column must have an insert.type when column.features.insert is true: \n"+JSON.stringify(e,null,2));let o;const s=r.type??"text",u=t.createFieldInput({mode:"insert",col:e,config:r});if(u)o=u.$input;else switch(s){case"textarea":o=$("<textarea class='form-input form-control form-control-sm'>");break;case"select":if(o=$("<select class='form-input form-control form-control-sm'/>"),!r.options||!Array.isArray(r.options))throw new Error("Column must have an insert.options array when column.features.insert is true: \n"+JSON.stringify(e,null,2));r.options.forEach(t=>{if("string"!=typeof t.label||void 0===t.value)throw new Error("Column must have an insert.options object with label and value when column.features.insert is true: \n"+JSON.stringify(e,null,2));$("<option>").text(t.label).attr("value",t.value).appendTo(o)});break;case"hidden":o=$("<input type='hidden' class='form-input form-control form-control-sm'/>");break;default:if(!t.isValidInputType(s))throw new Error("Invalid type: "+JSON.stringify(r,null,2));o=$(`<input autocomplete='off' type='${s}' class='form-input form-control form-control-sm'/>`),o.attr("data-type",s)}if(null!=r.default&&""!==r.default&&!o.val()){const t="object"==typeof r.default&&null!=r.default.value?r.default.value:r.default;String(t).trim()&&o.val(t).trigger("change")}if(r.attrs&&"object"==typeof r.attrs&&Object.keys(r.attrs).forEach(t=>o.attr(t,r.attrs[t])),o.attr("form",l).attr("name",e.name),r.disabled&&o.attr("disabled",!0),r.readonly&&o.attr("readonly",!0),r.required&&o.attr("required",!0),r.attrs&&"object"==typeof r.attrs&&Object.keys(r.attrs).forEach(t=>o.attr(t,r.attrs[t])),"hidden"!==r.type){const n=$("<td>").append(o).appendTo(a).attr("data-label",e.label);t.applyColumnCellMeta(n,e)}t.mountField({mode:"insert",$input:o,col:e,config:r,formEl:i[0],rowEl:a[0]}),r.events&&Array.isArray(r.events)&&r.events.forEach(t=>{o.off(t.event).on(t.event,function(e,...n){"function"==typeof t.callback&&t.callback(e,i[0],a[0],...n)})})}),t.anchorRowForm(i,a);const s=$("<td>").addClass("kgrid-row-actions").appendTo(a).attr("data-label","action"),u=$("<div>").addClass("btn-group").appendTo(s);return $("<button>").addClass("btn btn-sm btn-primary new-item-btn").html("<i class='fas fa-plus-square'></i>").attr("form",l).attr("type","submit").appendTo(u),"function"==typeof n.onInsertRowReady&&n.onInsertRowReady(i[0],a[0]),a}}(window.KGrid),function(t){t.setupEvents=function(e,n,r,o){const a=e.views[0];r.columns.forEach(n=>{n.display.events.forEach(t=>{if(!t.selector||!t.event||!t.callback)throw new Error("Invalid event: "+JSON.stringify(t,null,2));a.el.find(t.selector).off(t.event).on(t.event,n=>{if("function"!=typeof t.callback)throw new Error("Event callback must be a function: "+JSON.stringify(t,null,2));t.callback(n,e,a)})}),r.features.update&&n.update.events.forEach(r=>{if(!r.event||!r.callback)throw new Error("Invalid event: "+JSON.stringify(r,null,2));a.el.find("[name='"+n.name+"']").off(r.event).on(r.event,function(n,...o){if(t.log("event",r,n,this,o),"function"!=typeof r.callback)throw new Error("Event callback must be a function: "+JSON.stringify(r,null,2));r.callback(n,e,a,...o)})})}),r.features.update&&(a.el.find("[data-type]").each((n,r)=>{const l=r.getAttribute("data-type");if(!t.isPluggableFieldType(l))return;const i=o.get(r.name);i?.update&&t.mountField({mode:"update",$input:$(r),col:i,config:i.update,item:e,view:a})}),a.el.find("select[data-type='select']").each((t,n)=>{const r=o.get(n.name);if(!r)return;const a=e.attributes[r.name];null!=a&&""!==a&&$(n).val("boolean"==typeof a?String(a):a)}),a.el.find("form.edit-form").off("submit").on("submit",e=>{const n=e.target;e.preventDefault();const o=$(n).parents("[data-type=item]").data().instance,a=t.serializeForm(n);Object.keys(a).forEach(t=>{r.columns.find(e=>e.name===t)?.update?.dontsave&&delete a[t]}),o.update(a).catch(t.onError)})),r.features.delete&&a.el.find("button.delete-item").off("click").on("click",n=>{n.preventDefault(),a.el.addClass("confirm-delete");const o=()=>a.el.removeClass("confirm-delete");t.runDeleteConfirm({item:e,view:a,options:r},()=>{e.delete().catch(t.onError).finally(o)},o)}),"function"==typeof r.onRowFields&&r.onRowFields(e,a,n)}}(window.KGrid),function(t){t.init=async function(e,n){const r=t.resolveHostElement(e),o={...t.protoOptions,...n},a=t.mountTableShell(r,o);t.log("table config options",o);const l=t.resolveDefaultInteraction(o);t.applyInteraction(r,l);const i={$host:r,instance:null,filterForm:null,find:t=>r.find(t),setInteraction:(e,n)=>(t.applyInteraction(r,e,n),i),getInteraction:()=>"edit"===t.getTableInteractionHost(r).attr("data-interaction")?"edit":"view",setEditMode(t){if("boolean"!=typeof t)throw new TypeError("setEditMode(editMode) expects a boolean (true = edit, false = view)");return i.setInteraction(t?"edit":"view")},toggleEditMode:t=>(null!=t&&"object"==typeof t&&"function"==typeof t.preventDefault&&(t=void 0),"boolean"==typeof t?i.setInteraction(t?"edit":"view"):i.setInteraction("edit"===i.getInteraction()?"view":"edit"))};o.columns=o.columns.map(e=>t.normalizeColumnConfig(e));const s=o.handlers??{};delete o.handlers,o.columns.forEach(t=>{["insert","update","display"].forEach(e=>{const n=t[e].events;if(!n||!Array.isArray(n))throw new Error("Column "+t.name+" events are not an array");n.forEach(e=>{if("string"==typeof e.callback){const n=s[e.callback]||o.functions&&o.functions[e.callback];if(!n||"function"!=typeof n)throw new Error("Event callback function "+e.callback+" not found for column "+t.name+" or is not a function");e.callback=n}else if("function"!=typeof e.callback)throw new Error("Event callback must be a function for column "+t.name)})});const e=t.display;e&&e.events&&Array.isArray(e.events)&&e.events.forEach(t=>{if("string"==typeof t.callback){const e=s[t.callback]||o.functions&&o.functions[t.callback];e&&"function"==typeof e&&(t.callback=e)}})});const u=new Map;o.columns.forEach(t=>{u.set(t.name,t)});const c=t.setupLabelsHeader(a.find(".thead-labels"),o),f=t.hasActionColumn(o),d=c.find("th").length,p=d-(f?1:0);t.syncActionColumnColgroup(a,p,f);const m=o.filterForm??t.setupFilterHeader(a,o);let y;o.features&&o.features.paging?y=t.setupPagingFooter(a.find(".paging-footer"),o,d):(y=null,a.find(".paging-footer").remove());const b=t.setupNoDataTbody(a.find(".no-data-tbody"),o,d);o.features&&o.features.create&&t.setupNewRecordForm(a,o,i),i.filterForm=new t.FilterForm(m);const g=t.setupDataBody(a.find(".main-tbody"),o,c,m,y,b),h={dontload:!0,setAttrAsId:o.setAttrAsId??!1,itemListeners:{afterrender:e=>t.setupEvents(e,i.find("table"),o,u)}},w=t.getKViews(o.kviews);if(!w)throw new Error(t.KVIEWS_MISSING_MSG);if(i.instance=await w.createCollectionInstance(g,h),o.url){i.instance.setUrl(o.url),o.deleteUrl&&(t.log("set deleteUrl",o.deleteUrl),i.instance.setUrl(o.deleteUrl,"delete")),o.updateUrl&&(t.log("set updateUrl",o.updateUrl),i.instance.setUrl(o.updateUrl,"update")),o.insertUrl&&i.instance.setUrl(o.insertUrl,"insert");try{await i.instance.loadFromRemote()}catch(e){t.onError(e)}}else{if(!o.data||o.data.constructor!==Array)throw new Error("Invalid data: missing datasource url or data for table");{const t=o.data.map(t=>({attributes:t}));i.instance.loadFromData(t)}}return t.setupDefaultFilters(m,o,i.instance),i}}(window.KGrid);
|
package/docs/ai-guide.md
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
# KGrid — AI integration guide
|
|
2
|
+
|
|
3
|
+
Use this document when implementing or modifying **@logimaxx/kgrid** in a host application. It is optimized for AI assistants: facts, constraints, and patterns that prevent common mistakes.
|
|
4
|
+
|
|
5
|
+
Human-readable references: [README](../README.md), [configuration.md](configuration.md), [api.md](api.md), [integration.md](integration.md), [field-types.md](field-types.md), [table-shell.md](table-shell.md).
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## What KGrid is
|
|
10
|
+
|
|
11
|
+
- **Declarative JSON table** on top of **KViews** (JSON:API collections, Handlebars row templates).
|
|
12
|
+
- **jQuery** DOM; global entry point `window.KGrid` (IIFE bundle `dist/kgrid.js`).
|
|
13
|
+
- Features: filter, sort, paging, inline create/update/delete, view/edit interaction modes.
|
|
14
|
+
- **Does not** fetch data by itself beyond wiring KViews URLs — CRUD goes through `grid.instance` (KViews collection).
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Hard requirements
|
|
19
|
+
|
|
20
|
+
| Requirement | Notes |
|
|
21
|
+
|-------------|--------|
|
|
22
|
+
| jQuery `>= 3.7.0` | Peer dependency |
|
|
23
|
+
| `@logimaxx/kviews` | Peer; must expose `createCollectionInstance` |
|
|
24
|
+
| `styles/table.css` | **Required** — view/edit modes, row-actions column collapse, cell visibility |
|
|
25
|
+
| Load order | jQuery → KViews → `kgrid.js` → (optional `kgrid-widgets.js`) → `configure({ customInputTypes })` → `init()` |
|
|
26
|
+
| Bootstrap + Font Awesome | Recommended (default template uses `btn-*`, `fa-sort-*`) |
|
|
27
|
+
|
|
28
|
+
Without `table.css`, row-actions width, view/edit toggling, and inline edit display break.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Minimal integration (copy pattern)
|
|
33
|
+
|
|
34
|
+
```html
|
|
35
|
+
<link rel="stylesheet" href="node_modules/@logimaxx/kgrid/styles/table.css">
|
|
36
|
+
<script src="jquery.min.js"></script>
|
|
37
|
+
<script src="node_modules/@logimaxx/kviews/dist/kviews.min.js"></script>
|
|
38
|
+
<script src="node_modules/@logimaxx/kgrid/dist/kgrid.js"></script>
|
|
39
|
+
<div id="grid-host"></div>
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
KGrid.configure({
|
|
44
|
+
onError: function (err) { console.error(err); },
|
|
45
|
+
deleteConfirm: function (ctx, ok, cancel) {
|
|
46
|
+
if (confirm("Delete?")) ok(); else if (cancel) cancel();
|
|
47
|
+
},
|
|
48
|
+
// customInputTypes: { select2: KGrid.select2(fn), autosuggest: KGrid.autosuggest(fn) }
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const grid = await KGrid.init(document.getElementById("grid-host"), {
|
|
52
|
+
url: "/api/products",
|
|
53
|
+
updateUrl: "/api/products",
|
|
54
|
+
deleteUrl: "/api/products",
|
|
55
|
+
insertUrl: "/api/products",
|
|
56
|
+
type: "products",
|
|
57
|
+
defaultInteraction: "view",
|
|
58
|
+
features: {
|
|
59
|
+
filtering: true,
|
|
60
|
+
sorting: true,
|
|
61
|
+
paging: true,
|
|
62
|
+
create: true,
|
|
63
|
+
update: true,
|
|
64
|
+
delete: true,
|
|
65
|
+
},
|
|
66
|
+
columns: [/* see column shape below */],
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// grid.instance — KViews collection
|
|
70
|
+
// grid.filterForm.filter(name, value, operator)
|
|
71
|
+
// grid.setInteraction("edit" | "view")
|
|
72
|
+
// grid.getInteraction()
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## `KGrid.configure()` hooks (call once before any `init`)
|
|
78
|
+
|
|
79
|
+
| Hook | When to override |
|
|
80
|
+
|------|------------------|
|
|
81
|
+
| `kviews` | ES modules / no `window.KViews` |
|
|
82
|
+
| `onError` | Always in production apps |
|
|
83
|
+
| `deleteConfirm(context, onConfirm, onCancel)` | Row delete UI (preferred over hardcoded messages) |
|
|
84
|
+
| `confirm(message, onConfirm, onCancel)` | Generic dialogs; default delete flow uses this if `deleteConfirm` unset |
|
|
85
|
+
| `serializeForm(form, columns?)` | Non-flat APIs, checkbox coercion, etc. |
|
|
86
|
+
| `customInputTypes` | Map of type name → plugin (`KGrid.select2(fn)`, `KGrid.inputType(…)`, or `{ create, … }`) |
|
|
87
|
+
|
|
88
|
+
Per-table override: pass `deleteConfirm` in `init(host, { deleteConfirm, ... })`.
|
|
89
|
+
|
|
90
|
+
`deleteConfirm` context: `{ item, view, options }`. Call `onConfirm()` to run `item.delete()`; `onCancel()` to clear `confirm-delete` styling.
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Table options (essential)
|
|
95
|
+
|
|
96
|
+
**Data:** exactly one of:
|
|
97
|
+
|
|
98
|
+
- Remote: `url` (+ optional `updateUrl`, `deleteUrl`, `insertUrl`) + `type` (JSON:API resource type)
|
|
99
|
+
- Local: `data: [{ id, name, ... }]` (plain objects; KGrid wraps as `{ attributes }`)
|
|
100
|
+
|
|
101
|
+
**Features** (all default `false`):
|
|
102
|
+
|
|
103
|
+
```javascript
|
|
104
|
+
features: { filtering, sorting, paging, create, update, delete }
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
**Interaction:**
|
|
108
|
+
|
|
109
|
+
- `defaultInteraction: "view" | "edit"` (prefer over deprecated `editmode`)
|
|
110
|
+
- `grid.setInteraction("edit", { create, update, delete })` — optional per-feature overrides via `data-allow-*` on `.custom-table-shell`
|
|
111
|
+
|
|
112
|
+
**Shell / empty state:**
|
|
113
|
+
|
|
114
|
+
- `emptyRowMessage`, `pagingPageSizes`, `pagingDefaultSize`, `pagingFooterLabel`
|
|
115
|
+
- `noDataTemplate` — HTML for empty tbody (often `colspan` large, e.g. `99`)
|
|
116
|
+
|
|
117
|
+
**Insert row:** `insertFormRow: { position: "top" | "bottom" }`, `onNewItemCreated(data)`, `onInsertRowReady(form, row)`
|
|
118
|
+
|
|
119
|
+
**Row lifecycle:** `onRowFields(item, view, table)` — called after each data row’s `afterrender` / field mount (per-row enable/disable, show/hide).
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## Column shape (minimal)
|
|
124
|
+
|
|
125
|
+
Each column in `columns: []` is normalized via `KGrid.normalizeColumnConfig` (proto merge + shortcuts):
|
|
126
|
+
|
|
127
|
+
```javascript
|
|
128
|
+
{
|
|
129
|
+
name: "sku", // required for filter/sort/update
|
|
130
|
+
label: "SKU",
|
|
131
|
+
hidden: false,
|
|
132
|
+
class: "col-sku", // CSS on th/td (alias: columnClass); also sets data-name
|
|
133
|
+
features: { create, update, filter, sort }, // per-column flags
|
|
134
|
+
// Shared insert+update defaults (explicit insert/update win):
|
|
135
|
+
// input: { type: "number", required: true },
|
|
136
|
+
display: {
|
|
137
|
+
template: "{{sku}}", // Handlebars; keep simple {{field}}
|
|
138
|
+
events: [ // optional; defaults to []
|
|
139
|
+
{ selector: ".x", event: "click", callback: "onSkuClick" }
|
|
140
|
+
],
|
|
141
|
+
},
|
|
142
|
+
filter: {
|
|
143
|
+
type: "text",
|
|
144
|
+
operator: "~=~",
|
|
145
|
+
default: null, // initial value
|
|
146
|
+
persist: false, // keep across filter reset (also implied by hidden / type hidden)
|
|
147
|
+
},
|
|
148
|
+
insert: { type: "text", required: true }, // events optional
|
|
149
|
+
update: { type: "text" },
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**Event callbacks:** string names resolve from `handlers: { onSkuClick: fn }` or `functions` on table options. Insert/update **must** resolve to functions or `init` throws. Display events: missing handler leaves string (runtime error on click).
|
|
154
|
+
|
|
155
|
+
**Hidden / persist filters:** columns with `hidden: true` or `filter.type: "hidden"` get a hidden form field (no filter-row cell). `filter.persist` (or hidden) re-applies `filter.default` on form reset.
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## Row actions column (do not break)
|
|
160
|
+
|
|
161
|
+
When `features.delete || features.update || features.create`:
|
|
162
|
+
|
|
163
|
+
- Trailing column: `.kgrid-row-actions` on `th`/`td`
|
|
164
|
+
- `<colgroup>` with `col.kgrid-row-actions-col` (synced at init)
|
|
165
|
+
- **View mode:** column collapsed — full width for data columns
|
|
166
|
+
- **Edit mode:** column visible (~100px) — delete, save/cancel; insert row submit in `.new-record-row`
|
|
167
|
+
|
|
168
|
+
Rule: `KGrid.hasActionColumn(options)` — use the same logic if extending DOM; do not add action `<th>` only in header or only in body.
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
## DOM contract (if customizing HTML)
|
|
173
|
+
|
|
174
|
+
Host: empty `<div>` or div containing `table.custom-table`. KGrid adds `.custom-table-shell` on the interaction host.
|
|
175
|
+
|
|
176
|
+
Required regions inside `table.custom-table`:
|
|
177
|
+
|
|
178
|
+
| Selector | Purpose |
|
|
179
|
+
|----------|---------|
|
|
180
|
+
| `.thead-labels` | Column headers (one `<th>` template cloned) |
|
|
181
|
+
| `.thead-filters` | Filter row |
|
|
182
|
+
| `.before-main-tbody` / `.after-main-tbody` | Insert row top/bottom |
|
|
183
|
+
| `.main-tbody` | KViews data rows |
|
|
184
|
+
| `.no-data-tbody` | Empty state |
|
|
185
|
+
| `.paging-footer` | Removed if `features.paging` false |
|
|
186
|
+
|
|
187
|
+
Template placeholders: `{{EMPTY_ROW_MESSAGE}}`, `{{PAGE_SIZE_OPTIONS}}`, `{{PAGES_DATA_PAGESIZE}}`, `{{PAGING_FOOTER_LABEL}}` — see `KGrid.TABLE_SHELL_TEMPLATE` / [table-shell.md](table-shell.md).
|
|
188
|
+
|
|
189
|
+
**Forms:** Row/filter inputs cannot sit inside `<tr><form>`. KGrid uses hidden `<form>` + `form="id"` on controls. Do not remove this pattern.
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## `init` return value
|
|
194
|
+
|
|
195
|
+
```javascript
|
|
196
|
+
const grid = await KGrid.init(host, opts);
|
|
197
|
+
grid.$host // jQuery
|
|
198
|
+
grid.instance // KViews collection — loadFromRemote, newItem, item.update/delete
|
|
199
|
+
grid.filterForm // .filter(name, value, op), .reset()
|
|
200
|
+
grid.find(sel) // search under $host
|
|
201
|
+
grid.setInteraction(mode, overrides?)
|
|
202
|
+
grid.getInteraction() // "view" | "edit"
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Deprecated: `setEditMode`, `toggleEditMode` — use `setInteraction`.
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## Common tasks
|
|
210
|
+
|
|
211
|
+
| Task | Approach |
|
|
212
|
+
|------|----------|
|
|
213
|
+
| Toggle edit UI | `grid.setInteraction("edit")` / `"view"` |
|
|
214
|
+
| Programmatic filter | `grid.filterForm.filter("name", "x", "~=~")` |
|
|
215
|
+
| Reload data | `grid.instance.loadFromRemote()` |
|
|
216
|
+
| Custom delete modal | `KGrid.configure({ deleteConfirm })` |
|
|
217
|
+
| Custom field widget | `KGrid.registerFieldType("myType", { create({ mode, col, config }) { return { $input }; } })` |
|
|
218
|
+
| Pass KViews from bundle | `KGrid.configure({ kviews: KViews })` or `init(host, { kviews: KViews })` |
|
|
219
|
+
| Empty host | Default — KGrid builds table from template |
|
|
220
|
+
| Existing table in host | `init` detects `table` and skips shell generation; colgroup still synced |
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## Mistakes to avoid (AI checklist)
|
|
225
|
+
|
|
226
|
+
1. **Omitting `table.css`** — broken layout and interaction modes.
|
|
227
|
+
2. **Initializing before `configure`** — `customInputTypes` / deleteConfirm not set when needed.
|
|
228
|
+
3. **No KViews** — `init` throws `KVIEWS_MISSING_MSG`; set `configure({ kviews })` or `window.KViews`.
|
|
229
|
+
4. **Both `url` and `data` missing** — `init` throws.
|
|
230
|
+
5. **Column with `features.filter` but no `name`** — throws at setup.
|
|
231
|
+
6. **Mismatched action column** — different conditions for header vs body (always use `hasActionColumn`).
|
|
232
|
+
7. **Expecting action buttons in view mode** — row-actions column is collapsed; switch to edit or use `defaultInteraction: "edit"`.
|
|
233
|
+
8. **Column `type` not in `customInputTypes`** — field type not registered; mount/create fails or falls back to native handling.
|
|
234
|
+
9. **Display event handler string without `handlers` map** — fails at runtime on click.
|
|
235
|
+
10. **Editing `dist/kgrid.js` in node_modules** — change `src/` in the package or fork; rebuild with `npm run build`.
|
|
236
|
+
11. **Assuming cancel edit reloads local `data`** — cancel button calls `loadFromRemote()`; local-only grids need a custom approach.
|
|
237
|
+
12. **Breaking class names** — `custom-table-shell`, `data-interaction`, `main-tbody`, `kgrid-row-actions` are required by CSS and KViews wiring.
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## Package layout (npm)
|
|
242
|
+
|
|
243
|
+
```
|
|
244
|
+
@logimaxx/kgrid/
|
|
245
|
+
dist/kgrid.js # main bundle
|
|
246
|
+
dist/kgrid.min.js
|
|
247
|
+
styles/table.css # required stylesheet
|
|
248
|
+
src/ # source modules (concatenated in build)
|
|
249
|
+
docs/ # human + this AI guide
|
|
250
|
+
integrations/ # host examples (e.g. maxxops)
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
Peers: `jquery`, `@logimaxx/kviews`.
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## In a consumer repo (for Cursor / Copilot / etc.)
|
|
258
|
+
|
|
259
|
+
Add to the project’s `AGENTS.md` or rules:
|
|
260
|
+
|
|
261
|
+
```markdown
|
|
262
|
+
When working with KGrid tables, read:
|
|
263
|
+
node_modules/@logimaxx/kgrid/docs/ai-guide.md
|
|
264
|
+
(or the copy in docs/kgrid-ai-guide.md if vendored)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Run demo locally: `npm run demo` in the kgrid package → `http://localhost:5173/demo/`.
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
## Version
|
|
272
|
+
|
|
273
|
+
This guide matches **@logimaxx/kgrid@0.2.1** (row lifecycle hooks, `column.class`, persist filters, `input` shorthand). If APIs differ in another version, prefer `docs/api.md` in the installed package.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# API reference
|
|
2
|
+
|
|
3
|
+
## Global: `window.KGrid`
|
|
4
|
+
|
|
5
|
+
### `KGrid.configure(overrides)`
|
|
6
|
+
|
|
7
|
+
Merge host integration hooks. Call before initializing tables.
|
|
8
|
+
|
|
9
|
+
| Hook | Signature | Default |
|
|
10
|
+
|------|-----------|---------|
|
|
11
|
+
| `log` | `(...args) => void` | No-op |
|
|
12
|
+
| `onError` | `(err) => void` | `console.error` |
|
|
13
|
+
| `confirm` | `(message, onConfirm, onCancel?) => void` | `window.confirm` |
|
|
14
|
+
| `deleteConfirm` | `(context, onConfirm, onCancel?) => void` | `null` — falls back to `confirm` + `DEFAULT_DELETE_CONFIRM_MESSAGE` |
|
|
15
|
+
| `serializeForm` | `(form, columns?) => object` | `FormData` → plain object |
|
|
16
|
+
| `kviews` | KViews module | `window.KViews` |
|
|
17
|
+
| `customInputTypes` | `Record<string, FieldTypePlugin>` | Each value: `{ create, mount?, … }` (use `KGrid.select2(fn)` etc.) |
|
|
18
|
+
| `filterDebounceMs` | `number` | Default delay (ms) before filter API submit on the resolved submit event (`input` or `change`); `0` = immediate (default `300`) |
|
|
19
|
+
| `fieldTypes` | same as `customInputTypes` | **Deprecated** alias |
|
|
20
|
+
|
|
21
|
+
Returns `KGrid` (chainable). Re-syncs `customInputTypes` on every call.
|
|
22
|
+
|
|
23
|
+
### `KGrid.getKViews(override?)`
|
|
24
|
+
|
|
25
|
+
Resolves KViews in order:
|
|
26
|
+
|
|
27
|
+
1. `override` (e.g. `opts.kviews` from `init`)
|
|
28
|
+
2. `KGrid._config.kviews` from `configure`
|
|
29
|
+
3. `window.KViews`
|
|
30
|
+
|
|
31
|
+
Returns `null` if missing. `init` throws `KGrid.KVIEWS_MISSING_MSG`.
|
|
32
|
+
|
|
33
|
+
### Field type registry
|
|
34
|
+
|
|
35
|
+
| Symbol | Description |
|
|
36
|
+
|--------|-------------|
|
|
37
|
+
| `KGrid.registerFieldType(name, plugin, { overwrite? })` | Register pluggable widget |
|
|
38
|
+
| `KGrid.unregisterFieldType(name)` | Remove a registered type |
|
|
39
|
+
| `KGrid.inputType(mount, { element, … })` | Build a simple plugin (core) |
|
|
40
|
+
| `KGrid.select2(wrapper)` / `KGrid.autosuggest(wrapper)` | Build plugins (`integrations/kgrid-widgets.js`) |
|
|
41
|
+
| `KGrid.getFieldType(name)` | Lookup or `null` |
|
|
42
|
+
| `KGrid.listFieldTypes()` | Registered type names |
|
|
43
|
+
| `KGrid.createFieldInput({ mode, col, config })` | Build DOM (`mode`: `filter` \| `insert` \| `update`) |
|
|
44
|
+
| `KGrid.mountField(opts)` | Run plugin `mount` |
|
|
45
|
+
| `KGrid.bindFilterInputEvents({ type, $input, onSubmit, createResult? })` | Bind filter submit (uses `filterEvents` + `bindFilterSubmit`) |
|
|
46
|
+
| `KGrid.resolveFilterEvents({ plugin, $input, createResult? })` | Resolve event string for a filter control |
|
|
47
|
+
| `KGrid.bindFieldFilterSubmit(type, $input, onSubmit)` | Plugin-only extra filter events |
|
|
48
|
+
| `KGrid.isPluggableFieldType(type)` | Registered plugin? |
|
|
49
|
+
| `KGrid.isValidInputType(type)` | Native or plugin (insert/update) |
|
|
50
|
+
| `KGrid.isValidFilterType(type)` | Native or plugin (filter) |
|
|
51
|
+
|
|
52
|
+
See [field-types.md](field-types.md).
|
|
53
|
+
|
|
54
|
+
**Internal helpers:**
|
|
55
|
+
|
|
56
|
+
- `KGrid.log`, `onError`, `confirm`, `runDeleteConfirm`, `serializeForm`
|
|
57
|
+
- `KGrid.DEFAULT_DELETE_CONFIRM_MESSAGE` — default text when `deleteConfirm` is not set
|
|
58
|
+
|
|
59
|
+
`KGrid.select2.helpers` — Select2 option helpers (after loading `kgrid-widgets.js`).
|
|
60
|
+
|
|
61
|
+
### `KGrid.resolveHostElement(host)`
|
|
62
|
+
|
|
63
|
+
Normalizes the mount target: **DOM `Element`** or **jQuery** collection (non-empty). Throws otherwise.
|
|
64
|
+
|
|
65
|
+
### `KGrid.init(host, opts)`
|
|
66
|
+
|
|
67
|
+
Async table initializer.
|
|
68
|
+
|
|
69
|
+
**Parameters**
|
|
70
|
+
|
|
71
|
+
- `host` — empty DOM element or jQuery node (KGrid builds the table), or a host that already contains `<table>` (see [configuration.md](configuration.md#shell--dom-generated-by-kgrid))
|
|
72
|
+
- `opts` — table config; optional `opts.kviews`
|
|
73
|
+
|
|
74
|
+
**Returns:** `Promise<KGridTable>` with:
|
|
75
|
+
|
|
76
|
+
| Property / method | Description |
|
|
77
|
+
|-------------------|-------------|
|
|
78
|
+
| `$host` | jQuery root |
|
|
79
|
+
| `instance` | KViews collection |
|
|
80
|
+
| `filterForm` | `FilterForm` or setup result |
|
|
81
|
+
| `find(sel)` | ` $host.find(sel)` |
|
|
82
|
+
| `setInteraction`, `getInteraction`, `toggleEditMode`, `setEditMode` | Interaction mode |
|
|
83
|
+
|
|
84
|
+
### Prototypes
|
|
85
|
+
|
|
86
|
+
| Symbol | Description |
|
|
87
|
+
|--------|-------------|
|
|
88
|
+
| `KGrid.protoOptions` | Default table options |
|
|
89
|
+
| `KGrid.protoColumnConfig` | Default column |
|
|
90
|
+
| `KGrid.VALID_NATIVE_INPUT_TYPES` | Native HTML types |
|
|
91
|
+
| `KGrid.VALID_NATIVE_FILTER_TYPES` | Native filter types |
|
|
92
|
+
| `KGrid.VALID_INPUT_TYPES` | **Deprecated** — use `isValidInputType()` |
|
|
93
|
+
| `KGrid.VALID_FILTER_TYPES` | **Deprecated** — use `isValidFilterType()` |
|
|
94
|
+
| `KGrid.setDefaultValues(proto, partial)` | Deep-merge |
|
|
95
|
+
| `KGrid.normalizeColumnConfig(col)` | Proto merge + `input` shorthand + events defaults |
|
|
96
|
+
| `KGrid.isPlainObject(value)` | Realm-safe plain-object check |
|
|
97
|
+
| `KGrid.FilterForm` | Programmatic filter helper (`.filter`, `.ensure`, `.reset`) |
|
|
98
|
+
|
|
99
|
+
### Table shell template
|
|
100
|
+
|
|
101
|
+
See **[table-shell.md](table-shell.md)** for structure, placeholders, and customization.
|
|
102
|
+
|
|
103
|
+
| Symbol | Description |
|
|
104
|
+
|--------|-------------|
|
|
105
|
+
| `KGrid.TABLE_SHELL_TEMPLATE` | Default HTML string (`src/table-shell.js`) |
|
|
106
|
+
| `KGrid.renderTableShellHtml(options, template?)` | Replace `{{EMPTY_ROW_MESSAGE}}`, `{{PAGE_SIZE_OPTIONS}}`, `{{PAGES_DATA_PAGESIZE}}`, `{{PAGING_FOOTER_LABEL}}` |
|
|
107
|
+
| `KGrid.createTableShell(options)` | Render template → jQuery `<table>`; applies `tableAttrs` |
|
|
108
|
+
| `KGrid.mountTableShell($host, options)` | Append generated table when host is empty |
|
|
109
|
+
|
|
110
|
+
### Row actions column
|
|
111
|
+
|
|
112
|
+
| Symbol | Description |
|
|
113
|
+
|--------|-------------|
|
|
114
|
+
| `KGrid.hasActionColumn(options)` | `true` when `features.delete`, `features.update`, or `features.create` is enabled |
|
|
115
|
+
| `KGrid.syncActionColumnColgroup($table, dataColumnCount, hasActions)` | Prepends `<colgroup>` so the actions column can collapse in view mode without reserving width |
|
|
116
|
+
|
|
117
|
+
Requires `styles/table.css` for view/edit visibility rules on `.kgrid-row-actions` and `col.kgrid-row-actions-col`.
|
|
118
|
+
|
|
119
|
+
### Low-level setup (advanced / tests)
|
|
120
|
+
|
|
121
|
+
`setupLabelsHeader`, `setupFilterHeader`, `setupPagingFooter`, `setupNoDataTbody`, `setupNewRecordForm`, `setupDataBody`, `setupCell`, `setupEvents`, `resolveDefaultInteraction`, `getTableInteractionHost`, `applyInteraction`, `uuid`, `anchorRowForm`, `filterFormField`
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## Table instance (`KGrid.init` return value)
|
|
126
|
+
|
|
127
|
+
### Properties
|
|
128
|
+
|
|
129
|
+
| Property | Description |
|
|
130
|
+
|----------|-------------|
|
|
131
|
+
| `grid.instance` | KViews collection (`loadFromRemote`, `insert` / `newItem`, items) |
|
|
132
|
+
| `grid.filterForm` | `FilterForm` |
|
|
133
|
+
| `grid.$host` | jQuery host |
|
|
134
|
+
|
|
135
|
+
### Methods
|
|
136
|
+
|
|
137
|
+
#### `grid.setInteraction(mode, overrides?)`
|
|
138
|
+
|
|
139
|
+
`mode`: `'view'` | `'edit'`. Optional `{ create, update, delete }` → `data-allow-*`.
|
|
140
|
+
|
|
141
|
+
Toggling view ↔ edit also shows or hides the row-actions column (see [configuration.md](configuration.md#row-actions-column)).
|
|
142
|
+
|
|
143
|
+
#### `grid.getInteraction()`
|
|
144
|
+
|
|
145
|
+
`'view'` or `'edit'`.
|
|
146
|
+
|
|
147
|
+
#### `grid.setEditMode(boolean)` — deprecated
|
|
148
|
+
|
|
149
|
+
Use `setInteraction`.
|
|
150
|
+
|
|
151
|
+
#### `grid.toggleEditMode(editMode?)` — deprecated
|
|
152
|
+
|
|
153
|
+
- `boolean` → set mode
|
|
154
|
+
- no arg / DOM event → toggle view ↔ edit
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## `KGrid.FilterForm`
|
|
159
|
+
|
|
160
|
+
```javascript
|
|
161
|
+
grid.filterForm.filter(name, value, operator = "~=~")
|
|
162
|
+
grid.filterForm.reset()
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## KViews integration
|
|
168
|
+
|
|
169
|
+
`createCollectionInstance` options:
|
|
170
|
+
|
|
171
|
+
```javascript
|
|
172
|
+
{
|
|
173
|
+
dontload: true,
|
|
174
|
+
setAttrAsId: options.setAttrAsId ?? false,
|
|
175
|
+
itemListeners: {
|
|
176
|
+
afterrender: (item) => KGrid.setupEvents(item, table, options, colMap),
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`.main-tbody` jQuery `.data()`:
|
|
182
|
+
|
|
183
|
+
| Key | When |
|
|
184
|
+
|-----|------|
|
|
185
|
+
| `emptyview` | Always |
|
|
186
|
+
| `sort` | `features.sorting` |
|
|
187
|
+
| `paging`, `pagesizeinp`, `totalrecscount` | `features.paging` |
|
|
188
|
+
| `filter` | `features.filtering` |
|
|
189
|
+
| `type` | `options.type` |
|
|
190
|
+
|
|
191
|
+
Per-item URLs: `{base}/{id}` for update/delete.
|