/**
 * Copyright 2018 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{html as t,css as e}from"../../../lit/index.js";import{DDD as o}from"../../d-d-d/d-d-d.js";import{displayBehaviors as i,editBehaviors as l,editableTableStyles as a}from"./editable-table-behaviors.js";import"../../rich-text-editor/rich-text-editor.js";import"../../rich-text-editor/lib/toolbars/rich-text-editor-toolbar-mini.js";import"../../simple-toolbar/simple-toolbar.js";import"../../simple-tooltip/simple-tooltip.js";import"../../simple-icon/lib/simple-icon-lite.js";import"../../simple-icon/lib/simple-icons.js";import"../../hax-iconset/lib/simple-hax-iconset.js";import"./editable-table-editor-rowcol.js";import"../../simple-toolbar/lib/simple-toolbar-button.js";import"../../simple-toolbar/lib/simple-toolbar-button-group.js";import{ReplaceWithPolyfill as r}from"../../utils/utils.js";Element.prototype.replaceWith||(Element.prototype.replaceWith=r),CharacterData.prototype.replaceWith||(CharacterData.prototype.replaceWith=r),DocumentType.prototype.replaceWith||(DocumentType.prototype.replaceWith=r);class EditableTableEdit extends(l(o)){static get styles(){return[...super.styles||[],...a,e`
        :host {
          --paper-listbox-background-color: var(
            --editable-table-rowcol-bg-color
          );
        }
        :host([disabled]) {
          display: none;
          pointer-events: none;
          cursor: not-allowed;
        }
        .filter-icon,
        .sortable-icon {
          display: none;
          opacity: 0.4;
          width: var(--ddd-icon-xxs);
          height: var(--ddd-icon-xxs);
        }
        :host([sort]) tbody .tr:first-child .sortable-icon,
        :host([filter]) tbody .tr:not(:first-of-type) .filter-icon {
          display: inline-block;
          opacity: 0.25;
        }
        table {
          min-width: calc(100% - 2.3px);
          width: unset;
          height: 1px;
        }
        caption {
          width: 100%;
          padding: 0;
          margin: 0;
          color: var(
            --editable-table-caption-color,
            var(--editable-table-color, #222)
          );
        }
        table *[data-expanded="true"] {
          z-index: 2;
        }
        rich-text-editor:not([contenteditable]) {
          z-index: 1 !important;
        }
        caption,
        .th-or-td {
          border: var(--ddd-border-xs);
          border-color: var(--ddd-theme-default-limestoneGray);
        }
        label,
        .label {
          color: var(--editable-table-secondary-text-color, #444);
          font-size: var(
            --editable-table-secondary-font-size,
            var(--ddd-font-size-4xs)
          );
          font-family: var(
            --editable-table-secondary-font-family,
            var(--ddd-font-primary)
          );
          margin-right: 0.5em;
        }
        simple-toolbar {
          width: 100%;
          --simple-toolbar-button-bg: var(--editable-table-bg-color, #fff);
          --simple-toolbar-button-toggled-bg: var(
            --editable-table-stripe-bg-color,
            #f0f0f0
          );
          --simple-toolbar-button-hover-bg: var(
            --editable-table-bg-color,
            #fff
          );
          --simple-toolbar-button-border-color: var(
            --editable-table-border-color,
            #999
          );
          --simple-toolbar-button-toggled-border-color: var(
            --editable-table-color,
            #222
          );
          --simple-toolbar-button-hover-border-color: unset;
        }
        simple-toolbar::part(buttons) {
          align-items: stretch;
          justify-content: space-between;
        }
        .group {
          padding: 0;
          margin: 0;
          transition: all 2s;
          color: var(
            --editable-table-caption-color,
            var(--editable-table-color, #222)
          );
        }
        .group:not([hidden]) {
          display: flex;
          flex: 0 0 auto;
          justify-content: space-around;
          align-items: center;
          margin: 0 var(--ddd-spacing-1);
        }
        caption {
          position: relative;
        }
        caption > * {
          margin: 0 var(--ddd-spacing-1);
        }
        #caption {
          flex: 1 1 auto;
        }
        .caption-flex {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .icons {
          flex: 0 0 auto;
          opacity: 0.25;
        }
        th {
          padding: 0;
          border-width: var(--editable-table-border-width, 1px);
          border-style: var(--editable-table-border-style, solid);
          border-color: var(--editable-table-border-color, #999);
        }
        td {
          margin: 0;
          padding: 0;
          position: relative;
        }
        rich-text-editor-toolbar-mini {
          position: absolute;
          min-width: 200px;
          height: 0;
        }
        rich-text-editor {
          margin-bottom: 1px;
          padding: var(
              --editable-table-cell-vertical-padding,
              var(--ddd-spacing-3)
            )
            var(--editable-table-cell-horizontal-padding, var(--ddd-spacing-2));
          border: none !important;
          margin-right: var(--ddd-spacing-6);
          --rich-text-editor-min-height: 12px;
        }
        rich-text-editor[contenteditable="true"].heightmax {
          overflow-y: auto;
        }
        rich-text-editor:hover,
        rich-text-editor:focus,
        rich-text-editor:focus-within {
          border: none !important;
          outline: none !important;
        }
        td .icon-container {
          position: absolute;
          right: 0;
          top: calc(50% - 12px);
          width: var(--ddd-icon-xxs);
        }
        td simple-icon-lite {
          width: var(--ddd-icon-xxs);
        }
        td:focus-within {
          outline: 1px dotted currentColor;
        }
        .th:first-child {
          width: 96px;
        }
        :host([responsive]) thead th:nth-of-type(3),
        :host([responsive]) .tr td:nth-of-type(2) {
          border-right-width: calc(var(--editable-table-border-width) + 5px);
          border-right-style: double;
        }
        :host(:hover),
        *:hover {
          z-index: 3;
        }
        :host(:focus-within),
        *:focus-within {
          z-index: 4;
        }
        editable-table-editor-rowcol:hover,
        editable-table-editor-rowcol:focus-within {
          z-index: 10000000;
        }
      `]}get textEditorToolbar(){return t`
      <rich-text-editor-toolbar-mini
        id="editable-table-toolbar"
        .config="${this.config}"
        show="selection"
        part="text-editor-toolbar"
      ></rich-text-editor-toolbar-mini>
    `}get columnHeaderButton(){return t`
      <simple-toolbar-button
        id="columnHeader"
        icon="editable-table:column-headers"
        label="First row has column headers."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.columnHeader}"
        toggles
      >
      </simple-toolbar-button>
    `}get rowHeaderButton(){return t`
      <simple-toolbar-button
        id="rowHeader"
        icon="editable-table:row-headers"
        label="First column has row headers."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.rowHeader}"
        toggles
      >
      </simple-toolbar-button>
    `}get footerButton(){return t`
      <simple-toolbar-button
        id="footer"
        icon="editable-table:footer"
        label="Last row is a footer."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.footer}"
        toggles
      >
      </simple-toolbar-button>
    `}get footerButton(){return t`
      <simple-toolbar-button
        id="footer"
        icon="editable-table:footer"
        label="Last row is a footer."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.footer}"
        toggles
      >
      </simple-toolbar-button>
    `}get headersFootersGroup(){return t`
      <div class="group" part="simple-toolbar-section">
        <div class="label" part="simple-toolbar-section-label">
          Headers and footers
        </div>
        ${this.columnHeaderButton} ${this.rowHeaderButton} ${this.footerButton}
      </div>
    `}get borderButton(){return t`
      <simple-toolbar-button
        id="bordered"
        ?disabled="${this.hideBordered}"
        ?hidden="${this.hideBordered}"
        icon="image:grid-on"
        label="Borders."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.bordered}"
        toggles
      >
      </simple-toolbar-button>
    `}get stripeButton(){return t`
      <simple-toolbar-button
        id="striped"
        ?disabled="${this.hideStriped}"
        ?hidden="${this.hideStriped}"
        icon="editable-table:row-striped"
        label="Alternating rows."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.striped}"
        toggles
        radio
      >
      </simple-toolbar-button>
    `}get columnStripeButton(){return t`
      <simple-toolbar-button
        id="columnStriped"
        ?disabled="${this.hideStriped}"
        ?hidden="${this.hideStriped}"
        icon="editable-table:col-striped"
        label="Alternating columns."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.columnStriped}"
        toggles
        radio
      >
      </simple-toolbar-button>
    `}get condenseButton(){return t`
      <simple-toolbar-button
        id="condensed"
        ?disabled="${this.hideCondensed}"
        ?hidden="${this.hideCondensed}"
        icon="editable-table:row-condensed"
        label="Condensed rows."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.condensed}"
        toggles
      >
      </simple-toolbar-button>
    `}get numericStylesButton(){return t`
      <simple-toolbar-button
        id="numericStyles"
        ?disabled="${this.hideNumericStyles}"
        ?hidden="${this.hideNumericStyles}"
        icon="editable-table:numbers"
        label="Style numeric cells."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.numericStyles}"
        toggles
      >
      </simple-toolbar-button>
    `}get responsiveButton(){return t`
      <simple-toolbar-button
        id="responsive"
        ?disabled="${this.hideResponsive}"
        ?hidden="${this.hideResponsive}"
        icon="device:devices"
        label="Adjust width to screen size."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.responsive}"
        toggles
      >
      </simple-toolbar-button>
    `}get displayGroup(){return t`
      <div
        class="group"
        ?hidden="${this.hideDisplay}"
        part="simple-toolbar-section"
      >
        <div class="label" part="simple-toolbar-section-label">Display</div>
        ${this.borderButton} ${this.condenseButton}
        <simple-toolbar-button-group>
          ${this.stripeButton} ${this.columnStripeButton}
        </simple-toolbar-button-group>
        ${this.numericStylesButton} ${this.responsiveButton}
      </div>
    `}get sortButton(){return t`
      <simple-toolbar-button
        id="sort"
        ?disabled="${this._isSortDisabled(this.hideSort,this.columnHeader)}"
        ?hidden="${this._isSortDisabled(this.hideSort,this.columnHeader)}"
        label="Column sorting (for tables with column headers)."
        icon="editable-table:sortable"
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.sort}"
        toggles
      >
      </simple-toolbar-button>
    `}get filterButton(){return t`
      <simple-toolbar-button
        id="filter"
        ?disabled="${this.hideFilter}"
        ?hidden="${this.hideFilter}"
        icon="editable-table:filter"
        label="Column filtering."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.filter}"
        toggles
      >
      </simple-toolbar-button>
    `}get downloadButton(){return t`
      <simple-toolbar-button
        id="downloadable"
        ?disabled="${this.hideDownloadable}"
        ?hidden="${this.hideDownloadable}"
        icon="file-download"
        label="Allow downloading as CSV."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.downloadable}"
        toggles
      >
      </simple-toolbar-button>
    `}get printButton(){return t`
      <simple-toolbar-button
        id="printable"
        ?disabled="${this.hidePrintable}"
        ?hidden="${this.hidePrintable}"
        icon="print"
        label="Allow printing."
        @button-toggled="${this._onTableSettingChange}"
        part="simple-toolbar-button"
        ?toggled="${this.printable}"
        toggles
      >
      </simple-toolbar-button>
    `}get dataGroup(){return t`
      <div
        class="group"
        ?hidden="${this.hideSortFilter}"
        part="simple-toolbar-section"
      >
        <div class="label" part="simple-toolbar-section-label">Data</div>
        ${this.sortButton} ${this.filterButton} ${this.downloadButton}
        ${this.printButton}
      </div>
    `}get settingsToolbar(){return t`
      <simple-toolbar part="simple-toolbar">
        ${this.headersFootersGroup} ${this.displayGroup} ${this.dataGroup}
      </simple-toolbar>
    `}get editableCaption(){return t`
      <caption>
        <p class="offscreen">Edit Mode for</p>
        <div class="caption-flex">
          <rich-text-editor
            autofocus
            @blur="${this._captionChanged}"
            id="caption"
            label="Caption"
            placeholder="Name your table by adding a caption here."
            rawhtml="${this.caption}"
            toolbar="editable-table-toolbar"
            type="rich-text-editor-toolbar-mini"
          >
          </rich-text-editor>
          <div class="icons">
            ${this.downloadable?t`
                  <simple-icon-lite
                    class="downloadable-icon"
                    icon="file-download"
                    aria-hidden="true"
                  >
                  </simple-icon-lite>
                `:""}
            ${this.printable?t`
                  <simple-icon-lite
                    calss="printable-icon"
                    icon="print"
                    aria-hidden="true"
                  >
                  </simple-icon-lite>
                `:""}
          </div>
        </div>
      </caption>
    `}columnMenuButton(e){return t`
      <editable-table-editor-rowcol
        ?condensed="${this.condensed}"
        index="${e}"
        @rowcol-action="${this._handleRowColumnMenu}"
        @rowcol-menu-toggle="${this._handleMenuToggle}"
        part="rowcol-menu-button"
      >
      </editable-table-editor-rowcol>
    `}editableColumn(e){return t`
      <th
        class="col-${e}"
        scope="col"
        ?numeric="${this._isNumericColumn(e)}"
      >
        ${this.columnMenuButton(e)}
      </th>
    `}rowMenuButton(e){return t`
      <editable-table-editor-rowcol
        class="cell"
        ?condensed="${this.condensed}"
        index="${e}"
        row
        @rowcol-action="${this._handleRowColumnMenu}"
        part="rowcol-menu-button"
      >
      </editable-table-editor-rowcol>
    `}editableRow(e,o){return t`
      <tr
        class="tr ${0==e&&this.columnHeader?"thead-tr":e==this.data.length-1&&this.footer?"tfoot-tr":"tbody-tr"}"
      >
        <th scope="row">${this.rowMenuButton(e)}</th>
        ${(o||[]).map(((t,o)=>this.editableCell(e,o,t)))}
      </tr>
    `}cellEditor(e,o,i){return t`
      <rich-text-editor
        autofocus
        @blur="${t=>this._onCellValueChange(t,e,o)}"
        class="cell"
        disable-mouseover
        toolbar="editable-table-toolbar"
        id="cell-${e}-${o}"
        label="${`Cell ${this._getLabel(o,!1)}${e}`}"
        rawhtml="${i}"
        type="rich-text-editor-toolbar-mini"
        contenteditable="true"
        role="textbox"
      >
      </rich-text-editor>
    `}editableCell(e,o,i){return t`
      <td
        class="${0===o&&this.rowHeader||0==e&&this.columnHeader?"th":"td"} th-or-td"
        ?negative="${this._isNegative(i)}"
        ?numeric="${this._isNumericColumn(o)}"
        @click="${this._onCellClick}"
      >
        ${this.cellEditor(e,o,i)}
        <div class="icon-container">
          <simple-icon-lite
            class="sortable-icon"
            icon="editable-table:sortable"
            aria-hidden="true"
          ></simple-icon-lite>
          <simple-icon-lite
            class="filter-icon"
            icon="editable-table:filter-off"
            aria-hidden="true"
          ></simple-icon-lite>
        </div>
      </td>
    `}get editableColumns(){return t`
      <thead>
        <tr class="tr">
          <th scope="row">
            <span class="offscreen">Insert/Delete Controls</span>
          </th>
          ${(this.data[0]||[]).map(((t,e)=>this.editableColumn(e)))}
        </tr>
      </thead>
    `}get editableRows(){return t`
      <tbody id="tbody" class="tbody">
        ${this.data.map(((t,e)=>this.editableRow(e,t)))}
      </tbody>
    `}render(){return t`
      ${this.textEditorToolbar}
      <p class="offscreen">Table Editor</p>
      <table
        id="table-editmode"
        ?bordered="${this.bordered}"
        ?column-header="${this.columnHeader}"
        ?column-striped="${this.columnStriped}"
        ?condensed="${this.condensed}"
        ?downloadable="${this.downloadable}"
        ?filter="${this.filter}"
        ?footer="${this.footer}"
        ?numeric-styles="${this.numericStyles}"
        ?printable="${this.printable}"
        ?responsive="${this.responsive}"
        ?row-header="${this.rowHeader}"
        ?sort="${this.sort}"
        ?striped="${this.striped}"
        part="table"
      >
        ${this.editableCaption} ${this.editableColumns} ${this.editableRows}
      </table>
      ${this.settingsToolbar}
    `}static get tag(){return"editable-table-edit"}constructor(){super()}static get properties(){return{...super.properties}}get hideSortFilter(){return this.hideSort&&this.hideFilter}get hideDisplay(){return this.hideBordered&&this.hideCondensed&&this.hideStriped&&this.hideNumericStyles&&this.hideResponsive}updated(t){super.updated&&super.updated(t),t.forEach(((t,e)=>{"disabled"!==e&&"hidden"!==e||this.disableEditing()}))}disableEditing(){this.shadowRoot.querySelectorAll("rich-text-editor-toolbar-mini").forEach((t=>{t.disableEditing()})),this.dispatchEvent(new CustomEvent("editing-disabled",{bubbles:!0,composed:!0,cancelable:!1,detail:{editor:this}}))}_isSortDisabled(t,e){return t||!e}_getLabel(t){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),o=this._getLetter(t).split("-").reverse(),i="";for(let t=0;t<o.length;t++)""!==o[t]&&(i+=e[o[t]]);return i}_getLetter(t){let e=Math.floor(t/26),o="";return o+=t-26*e+"-",e>0&&e<26?o+=e-1+"-":e>=26&&(o+=this._getLetter(e-1)),o}deleteColumn(t){let e=[...this.data];for(let o=0;o<e.length;o++)e[o].splice(t,1);this.data=e,this._handleChange("data"),this.dispatchEvent(new CustomEvent("column-deleted",{bubbles:!0,composed:!0,cancelable:!1,detail:{editor:this,data:this.data,colNum:t}}))}deleteRow(t){let e=[...this.data];e.splice(t,1),this.data=e,this._handleChange("data"),this.dispatchEvent(new CustomEvent("row-deleted",{bubbles:!0,composed:!0,cancelable:!1,detail:{editor:this,data:this.data,rowNum:t}}))}insertColumn(t){let e=[...this.data];for(let o=0;o<e.length;o++)e[o].splice(t,0," ");this.data=e,this._handleChange("data"),this.dispatchEvent(new CustomEvent("column-inserted",{bubbles:!0,composed:!0,cancelable:!1,detail:{editor:this,data:this.data,colNum:t}}))}insertRow(t){let e=[...this.data],o=new Array;for(let t=0;t<e[0].length;t++)o.push(" ");e.splice(t+1,0,o),this.data=e,this._handleChange("data"),this.dispatchEvent(new CustomEvent("row-inserted",{bubbles:!0,composed:!0,cancelable:!1,detail:{editor:this,data:this.data,rowNum:t}}))}changeCell(t,e,o){let i=this.data.slice();i[t][e]=o,this.data=[],this.data=i,this._handleChange("data"),this.dispatchEvent(new CustomEvent("cell-changed",{bubbles:!0,composed:!0,cancelable:!1,detail:{editor:this,data:this.data,rowNum:t,colNum:e}}))}_onCellClick(t){t.model&&t.model.root&&t.model.root.nodeList[0]&&t.model.root.nodeList[0].focus()}_onCellValueChange(t,e,o){let i=this.shadowRoot&&this.shadowRoot.querySelector(`#cell-${e}-${o}`)?this.shadowRoot.querySelector(`#cell-${e}-${o}`).innerHTML:void 0;this.changeCell(e,o,i)}_captionChanged(){let t=this.shadowRoot&&this.shadowRoot.querySelector("#caption")?this.shadowRoot.querySelector("#caption").innerHTML:void 0;this.caption=t,this._handleChange("caption"),this.dispatchEvent(new CustomEvent("caption-changed",{bubbles:!0,composed:!0,cancelable:!1,detail:{editor:this,caption:this.caption}}))}_onTableSettingChange(t){this[t.detail.id]=t.detail.toggled,this._handleChange(t.detail.id)}_dataChanged(t,e){(t&&t.length<1||t[0].length<1)&&(this.data=[["","",""],["","",""],["","",""]]),this._handleChange("data")}_handleChange(t){this.dispatchEvent(new CustomEvent("change",{bubbles:!0,composed:!0,cancelable:!1,detail:t}))}_handleRowColumnMenu(t){t.detail.insert&&t.detail.row?this.insertRow(t.detail.index):t.detail.insert&&!t.detail.row?this.insertColumn(t.detail.index):!t.detail.insert&&t.detail.row?this.deleteRow(t.detail.index):this.deleteColumn(t.detail.index)}_handleMenuToggle(t){t.detail&&(t.detail.closest("thead,tbody").setAttribute("data-expanded",t.detail.expanded),t.detail.closest("tr").setAttribute("data-expanded",t.detail.expanded),t.detail.closest("th").setAttribute("data-expanded",t.detail.expanded))}_getCurrentRow(t,e){let o=null;return null!=e&&void 0!==e[t]&&null!==e[t]&&(o=e[t]),o}_isFirstRow(t){return 0===t}}customElements.define(EditableTableEdit.tag,EditableTableEdit);export{EditableTableEdit};