count), so repeated tables get unique HTML ids. */ private static $instances = array(); /* --------------------------------------------------------------------- * Column types * ------------------------------------------------------------------ */ /** Is the string a date we understand (31.12.2026, 2026-12-31, 12/31/2026, 31 December 2026, December 31, 2026)? */ public static function looks_like_date( $s ) { $s = trim( wp_strip_all_tags( (string) $s ) ); return (bool) preg_match( '/^(\d{1,2}[.\/]\d{1,2}[.\/]\d{4}|\d{4}-\d{2}-\d{2}|\d{1,2}\s+\p{L}{3,}\.?\s+\d{4}|\p{L}{3,}\.?\s+\d{1,2},?\s+\d{4})$/u', $s ); } /** A plain number with optional thousands separators, decimals, sign, percent or currency. */ public static function looks_like_number( $s ) { $s = trim( wp_strip_all_tags( (string) $s ) ); return (bool) preg_match( '/^[-+\x{2212}]?[$€£¥₺]?\s?(\d{1,3}([.,\s]\d{3})+|\d+)([.,]\d+)?\s?%?$/u', $s ); } /** * Column kind: title (first column), key, number, date, link or text. * $type is the per-column setting; 'auto' detects from the cells (80% rule). * * @param string[] $cells Visible data cells of the column. */ public static function column_kind( $type, $index, array $cells ) { if ( 'auto' !== $type && in_array( $type, Store::COL_TYPES, true ) ) { return $type; } if ( 0 === (int) $index ) { return 'title'; } $vals = array_values( array_filter( array_map( 'trim', $cells ), 'strlen' ) ); if ( ! $vals ) { return 'text'; } $need = count( $vals ) * 0.8; $link = count( array_filter( $vals, function ( $v ) { return false !== stripos( $v, '= $need ) { return 'link'; } if ( count( array_filter( $vals, array( __CLASS__, 'looks_like_date' ) ) ) >= $need ) { return 'date'; } if ( count( array_filter( $vals, array( __CLASS__, 'looks_like_number' ) ) ) >= $need ) { return 'number'; } return 'text'; } /* --------------------------------------------------------------------- * HTML * ------------------------------------------------------------------ */ /** Default cell processing: shortcodes, safe HTML, line breaks. */ public static function cell( $v ) { $v = (string) $v; if ( false !== strpos( $v, '[' ) ) { $v = do_shortcode( $v ); } $v = wp_kses_post( $v ); if ( false !== strpos( $v, "\n" ) ) { $v = nl2br( $v ); } return $v; } /** * Table HTML. $t has the shape of nitida_tables_get() (unsaved data is fine, e.g. for previews). * $ctx: 'cell' => callable for cell content (default: self::cell), 'context' => 'shortcode'|'block'|'preview'. */ public static function render_table( array $t, array $ctx = array() ) { $id = isset( $t['id'] ) ? (int) $t['id'] : 0; $data = Store::normalize_data( isset( $t['data'] ) ? $t['data'] : array() ); if ( class_exists( '\NitidaTables\Formula' ) ) { $data = Formula::evaluate( $data ); } // Results are safe HTML. $vis = Store::normalize_visibility( isset( $t['visibility'] ) ? $t['visibility'] : array(), count( $data ), count( $data[0] ) ); $opt = Store::normalize_options( isset( $t['options'] ) ? $t['options'] : array(), count( $data[0] ) ); $cell = ( isset( $ctx['cell'] ) && is_callable( $ctx['cell'] ) ) ? $ctx['cell'] : array( __CLASS__, 'cell' ); $head = 1 === (int) $opt['table_head']; $cols = array(); foreach ( array_keys( $data[0] ) as $c ) { if ( 1 === (int) $vis['columns'][ $c ] ) { $cols[] = $c; } } if ( ! $cols ) { return ''; } $rows = array(); $row_data = array(); // Data row index of each body row. foreach ( $data as $r => $row ) { if ( ( $head && 0 === $r ) || 1 !== (int) $vis['rows'][ $r ] ) { continue; } $rows[] = $row; $row_data[] = $r; } // Merged cells: spans of the visible grid. Without placeholders everything below stays as before. $merged = Merge::has_any( $data ); $sp = array( 'anchors' => array(), 'covered' => array() ); $flat = $rows; $vspan = false; if ( $merged ) { $grid_rows = $head ? array_merge( array( 0 ), $row_data ) : $row_data; $sp = Merge::spans( $data, $grid_rows, $cols, $head ); $flat = array_map( function ( $row ) { return array_map( function ( $v ) { return Merge::is_placeholder( $v ) ? '' : $v; }, $row ); }, $rows ); foreach ( $sp['anchors'] as $ar => $list ) { if ( $head && 0 === $ar ) { continue; } foreach ( $list as $a ) { if ( $a['rs'] > 1 ) { $vspan = true; } } } } $kinds = array(); $labels = array(); $heads = array(); foreach ( $cols as $i => $c ) { $raw = $head ? (string) $data[0][ $c ] : ''; $hc = $head && isset( $sp['covered'][0][ $c ] ) ? $sp['covered'][0][ $c ] : null; // Covered by a header cell: that cell's text is the label. if ( $hc ) { $raw = (string) $data[0][ $hc[1] ]; } if ( $head && Merge::is_placeholder( $raw ) ) { $raw = ''; } // Orphan placeholder: an empty header cell. $heads[ $i ] = $hc ? '' : trim( (string) call_user_func( $cell, $raw ) ); $kind = self::column_kind( $opt['column_types'][ $c ], $i, array_column( $flat, $c ) ); /** * Filters the kind of a column (title, key, number, date, link, text). * * @param string $kind Detected or configured kind. * @param string $header Header cell text. * @param int $index Visible column index. * @param array $t Table. */ $kinds[ $i ] = (string) apply_filters( 'nitida_tables_column_kind', $kind, wp_strip_all_tags( $raw ), $i, $t ); /** * Filters the card label of a column (defaults to the header text). * * @param string $label Label. * @param int $index Visible column index. * @param array $t Table. */ $labels[ $i ] = (string) apply_filters( 'nitida_tables_cell_label', trim( wp_strip_all_tags( $raw ) ), $i, $t ); } // The same table can appear more than once on a page: the repeats get unique ids (-2, -3) after the body cache. $inst = 1; if ( $id > 0 && 'rest' !== ( isset( $ctx['context'] ) ? $ctx['context'] : '' ) ) { self::$instances[ $id ] = isset( self::$instances[ $id ] ) ? self::$instances[ $id ] + 1 : 1; $inst = self::$instances[ $id ]; } $n = count( $rows ); $str = self::strings( $t, $n ); $badge = $opt['highlight'] ? ( '' !== $opt['highlight_label'] ? $opt['highlight_label'] : $str['highlight'] ) : ''; $tid = (string) apply_filters( 'nitida_tables_table_html_id', 'nitida-table-' . $id . '-grid', $t ); $wrap = self::wrapper_classes(); if ( $vspan ) { $wrap[] = 'nitida-table--spans'; } if ( '' !== $opt['extra_css_classes'] ) { $wrap[] = $opt['extra_css_classes']; } /** * Filters the wrapper attributes (class is an array of classes). Add data-* attributes for scripts here. * * @param array $attrs Attributes. * @param array $t Table. * @param array $ctx Render context. */ $wattrs = (array) apply_filters( 'nitida_tables_wrapper_attributes', array( 'class' => $wrap, 'id' => 'nitida-table-' . $id, 'style' => '--tt-card-h:' . self::card_height( count( $cols ) ) . 'px', 'data-empty' => $str['empty'], 'data-clear' => $str['clear'], 'data-sortby' => $str['sort_by'], 'data-sort-order' => $str['sort_order'], 'data-sort-asc' => $str['sort_asc'], 'data-sort-desc' => $str['sort_desc'], 'data-tt-spans' => $vspan ? 'row' : null, ), $t, $ctx ); $html = ''; /** * Filters HTML printed inside the wrapper before the search bar (for example filters or buttons). Must be escaped. * * @param string $html HTML. * @param array $t Table. * @param array $ctx Render context. * @param array $info Visible columns, kinds, labels, header cells and data rows. */ $info = array( 'cols' => $cols, 'kinds' => $kinds, 'labels' => $labels, 'heads' => $heads, 'rows' => $flat ); $html .= (string) apply_filters( 'nitida_tables_before_table', '', $t, $ctx, $info ); if ( ! $vspan && $opt['search_min'] > 0 && $n >= $opt['search_min'] ) { $html .= '
'; if ( Settings::get( 'show_count' ) ) { $html .= '' . esc_html( sprintf( $str['rows'], $n ) ) . ''; } $html .= '
'; } $html .= '
'; if ( $head ) { $html .= ''; foreach ( $cols as $i => $c ) { if ( isset( $sp['covered'][0][ $c ] ) ) { continue; } $ta = array( 'scope' => 'col', 'role' => 'columnheader', 'class' => array( 'tt-col--' . $kinds[ $i ] ) ); if ( $opt['sortable'] && ! $vspan ) { $ta['aria-sort'] = 'none'; } $ta['data-col'] = $i; if ( isset( $sp['anchors'][0][ $c ] ) && $sp['anchors'][0][ $c ]['cs'] > 1 ) { $ta['colspan'] = $sp['anchors'][0][ $c ]['cs']; } /** * Filters header cell attributes. * * @param array $ta Attributes. * @param int $c Data column index. * @param int $i Visible column index. * @param array $t Table. */ $ta = (array) apply_filters( 'nitida_tables_header_cell_attributes', $ta, $c, $i, $t ); $html .= '' . $heads[ $i ] . ''; } $html .= ''; } $html .= ''; /** * Filters the data rows printed in the table body (for example only the first page). Column kinds, labels, * the row count and $info['rows'] still use all rows. * * @param array $rows Data rows (data column index => stored HTML). * @param array $t Table. * @param array $ctx Render context. * @param array $info Visible columns, kinds, labels, header cells and data rows. */ $body_rows = array_values( (array) apply_filters( 'nitida_tables_body_rows', $rows, $t, $ctx, $info ) ); $ckey = self::body_cache_key( $t, $ctx, $body_rows, $cols, $kinds, $labels, $badge, $merged ? $sp : null ); $cached = '' !== $ckey ? get_transient( $ckey ) : false; if ( is_string( $cached ) && '' !== $cached ) { $html .= $cached . '
'; } else { $body = ''; $dynamic = false; $ptr = 0; foreach ( $body_rows as $ri => $row ) { // Spans of this row: from the table grid when the row can be found there, else from the row alone. $rsp = null; $rdi = null; if ( $merged ) { $n_rows = count( $rows ); for ( $k = 0; $k < $n_rows; $k++ ) { $j = ( $ptr + $k ) % $n_rows; if ( $rows[ $j ] === $row ) { $rdi = $row_data[ $j ]; $ptr = $j + 1; break; } } if ( null === $rdi ) { $rsp = Merge::spans( array( $row ), array( 0 ), $cols ); $rdi = 0; } else { $rsp = $sp; } } /** * Filters row attributes (for example an id for deep links). * * @param array $ra Attributes. * @param array $row Raw row cells (data column index => stored HTML). * @param int $ri Body row index. * @param array $t Table. * @param array $info Visible columns, kinds, labels. */ $ra = (array) apply_filters( 'nitida_tables_row_attributes', array( 'role' => 'row' ), $row, $ri, $t, $info ); $body .= ''; foreach ( $cols as $i => $c ) { $raw = isset( $row[ $c ] ) ? (string) $row[ $c ] : ''; if ( $merged && isset( $rsp['covered'][ $rdi ][ $c ] ) ) { // Covered by a merged block. Card mode has no rowspan, so the first covered cell of a row under a // vertical span keeps a copy of the anchor's value (hidden in table mode by CSS). $cv = $rsp['covered'][ $rdi ][ $c ]; if ( $cv[0] !== $rdi && $cv[1] === $c && isset( $data[ $cv[0] ][ $c ] ) ) { $araw = (string) $data[ $cv[0] ][ $c ]; if ( false !== strpos( $araw, '[' ) ) { $dynamic = true; } $cp = array( 'role' => 'cell', 'class' => array( 'tt-col--' . $kinds[ $i ], 'tt-span-copy' ), 'data-col' => $i ); if ( '' !== $labels[ $i ] ) { $cp['data-label'] = $labels[ $i ]; } $body .= '' . trim( (string) call_user_func( $cell, $araw ) ) . ''; } continue; } if ( $merged && Merge::is_placeholder( $raw ) ) { $raw = ''; } if ( ! $dynamic && false !== strpos( $raw, '[' ) ) { $dynamic = true; } // Shortcodes can change per request. $v = trim( (string) call_user_func( $cell, $raw ) ); $ca = array( 'role' => 'cell', 'class' => array( 'tt-col--' . $kinds[ $i ] ) ); if ( '' !== $labels[ $i ] ) { $ca['data-label'] = $labels[ $i ]; } if ( 0 === $ri && 0 === $i && '' !== $badge ) { $ca['data-highlight'] = $badge; } $ca['data-col'] = $i; if ( $merged && isset( $rsp['anchors'][ $rdi ][ $c ] ) ) { if ( $rsp['anchors'][ $rdi ][ $c ]['cs'] > 1 ) { $ca['colspan'] = $rsp['anchors'][ $rdi ][ $c ]['cs']; } if ( $rsp['anchors'][ $rdi ][ $c ]['rs'] > 1 ) { $ca['rowspan'] = $rsp['anchors'][ $rdi ][ $c ]['rs']; } } /** * Filters cell attributes (for example classes for conditional formatting). * * @param array $ca Attributes. * @param string $raw Stored cell HTML. * @param int $c Data column index. * @param int $i Visible column index. * @param array $row Raw row cells. * @param string $kind Column kind. * @param array $t Table. */ $ca = (array) apply_filters( 'nitida_tables_cell_attributes', $ca, $raw, $c, $i, $row, $kinds[ $i ], $t ); /** * Filters the cell content HTML (already sanitized). Must stay escaped. * * @param string $v Cell HTML. * @param string $raw Stored cell HTML. * @param int $c Data column index. * @param string $kind Column kind. * @param array $t Table. */ $v = (string) apply_filters( 'nitida_tables_cell_html', $v, $raw, $c, $kinds[ $i ], $t ); $body .= '' . $v . ''; } $body .= ''; } if ( '' !== $ckey && ! $dynamic && '' !== $body && strlen( $body ) <= self::CACHE_MAX_BYTES ) { self::cache_store( isset( $t['id'] ) ? (int) $t['id'] : 0, $ckey, $body ); } $html .= $body . ''; } /** Filters HTML printed inside the wrapper after the table (for example a footer or "last updated"). Must be escaped. */ $html .= (string) apply_filters( 'nitida_tables_after_table', '', $t, $ctx, $info ); $html .= ''; /** * Filters the final table HTML. * * @param string $html Table HTML. * @param array $t Table. * @param array $ctx Render context. */ $html = (string) apply_filters( 'nitida_tables_table_html', $html, $t, $ctx ); return $inst > 1 ? self::uniquify_ids( $html, '-' . $inst ) : $html; } /** Forgets how often each table was rendered (a new page in a long-running process, and tests). */ public static function reset_instances() { self::$instances = array(); } /** * Adds a suffix to every id in a table's HTML and to the attributes and inline selectors that point at them * (for, aria-*, href="#...", "#id" in style blocks). Used for the second and later copies of a table on a page. * * @param string $html Table HTML. * @param string $suffix Suffix, for example "-2". */ public static function uniquify_ids( $html, $suffix ) { if ( ! preg_match_all( '/\sid="([^"]+)"/', $html, $m ) ) { return $html; } $map = array(); foreach ( array_unique( $m[1] ) as $old ) { $map[ $old ] = $old . $suffix; } $html = (string) preg_replace_callback( '/(\s)(id|for|aria-controls|aria-labelledby|aria-describedby|aria-owns|aria-details|aria-activedescendant)="([^"]*)"/', function ( $a ) use ( $map ) { $parts = preg_split( '/\s+/', trim( $a[3] ) ); foreach ( $parts as $k => $p ) { if ( isset( $map[ $p ] ) ) { $parts[ $k ] = $map[ $p ]; } } return $a[1] . $a[2] . '="' . implode( ' ', $parts ) . '"'; }, $html ); $html = (string) preg_replace_callback( '/href="#([^"]+)"/', function ( $a ) use ( $map ) { return isset( $map[ $a[1] ] ) ? 'href="#' . $map[ $a[1] ] . '"' : $a[0]; }, $html ); return (string) preg_replace_callback( '#]*>.*?#s', function ( $a ) use ( $map ) { return (string) preg_replace_callback( '/#([A-Za-z0-9_\-]+)/', function ( $b ) use ( $map ) { return isset( $map[ $b[1] ] ) ? '#' . $map[ $b[1] ] : $b[0]; }, $a[0] ); }, $html ); } /** * Visitor-facing strings. Multilingual sites can swap them per page with the nitida_tables_front_strings filter. * * @return array{search:string,rows:string,rows_filtered:string,highlight:string,empty:string,clear:string} */ /** * Locale of the page being shown, from (multilingual plugins and themes set it per page), when it * differs from WordPress' own language; '' otherwise. Visitor-facing strings follow it. */ public static function page_locale() { if ( is_admin() || ! function_exists( 'get_language_attributes' ) || ! preg_match( '/lang="([A-Za-z]{2,3})(?:[-_]([A-Za-z]{2}))?/', get_language_attributes(), $m ) ) { return ''; } $lang = strtolower( $m[1] ) . ( isset( $m[2] ) && '' !== $m[2] ? '_' . strtoupper( $m[2] ) : '' ); $site = function_exists( 'determine_locale' ) ? determine_locale() : get_locale(); if ( strtok( $lang, '_' ) === strtok( $site, '_' ) ) { return ''; } /** * Filters the locale used for a table's visitor-facing strings ('' keeps the site language). * * @param string $lang Locale from . */ return (string) apply_filters( 'nitida_tables_page_locale', 'en' === $lang ? 'en_US' : $lang ); } public static function strings( array $t, $n ) { $page = self::page_locale(); $switched = '' !== $page && function_exists( 'switch_to_locale' ) && switch_to_locale( $page ); $s = array( 'search' => '' !== (string) Settings::get( 'search_placeholder' ) ? (string) Settings::get( 'search_placeholder' ) : __( 'Search this table', 'nitida-tables' ), /* translators: %d: number of rows */ 'rows' => _n( '%d row', '%d rows', (int) $n, 'nitida-tables' ), /* translators: 1: rows that match the search, 2: all rows */ 'rows_filtered' => __( '%1$d of %2$d rows', 'nitida-tables' ), 'highlight' => Settings::highlight_label(), 'empty' => __( 'No rows match your search.', 'nitida-tables' ), 'clear' => __( 'Clear search', 'nitida-tables' ), 'sort_by' => __( 'Sort by', 'nitida-tables' ), 'sort_order' => __( 'Original order', 'nitida-tables' ), /* translators: %s: column name */ 'sort_asc' => __( '%s, ascending', 'nitida-tables' ), /* translators: %s: column name */ 'sort_desc' => __( '%s, descending', 'nitida-tables' ), ); if ( $switched ) { restore_previous_locale(); } /** * Filters the visitor-facing strings of a table. * * @param array $s Strings: search, rows (with %d), rows_filtered (with %1$d and %2$d), highlight, empty, clear, sort_by, sort_order, sort_asc, sort_desc. * @param array $t Table. * @param int $n Number of visible rows. */ $f = apply_filters( 'nitida_tables_front_strings', $s, $t, (int) $n ); return is_array( $f ) ? array_map( 'strval', array_merge( $s, $f ) ) : $s; } /** * Estimated height in px of the content of one phone card (title line plus one line per other visible column), * used as the content-visibility placeholder size so long tables do not jump while scrolling. * * @param int $cols Visible column count. * @return int */ public static function card_height( $cols ) { return (int) round( 41 + 32.5 * max( 0, (int) $cols - 1 ) ); } /** Attribute string from an array (class may be an array). Keys are kept as given; values are escaped. */ public static function attrs( array $a ) { $out = ''; foreach ( $a as $k => $v ) { if ( null === $v || false === $v ) { continue; } if ( is_array( $v ) ) { $v = implode( ' ', array_filter( array_map( 'strval', $v ), 'strlen' ) ); } $k = preg_replace( '/[^a-zA-Z0-9_:\-]/', '', (string) $k ); if ( '' === $k ) { continue; } $out .= ' ' . $k . '="' . esc_attr( (string) $v ) . '"'; } return $out; } /* --------------------------------------------------------------------- * Body cache: the rendered rows of large tables are kept in a transient, so a page with a big table does not * sanitize every cell on every request. The key covers the rows, columns, kinds, labels, badge and plugin * version; extensions that change rows or cells add their own settings through nitida_tables_render_cache_salt. * ------------------------------------------------------------------ */ const CACHE_INDEX = 'nitida_tables_render_cache'; const CACHE_MAX_BYTES = 4194304; // 4 MB: larger bodies are not stored (database packet limits on shared hosts). const CACHE_PER_TABLE = 6; // Variants per table (for example a page in two languages). /** Transient name for the body, or '' when this render must not be cached. */ public static function body_cache_key( array $t, array $ctx, array $body_rows, array $cols, array $kinds, array $labels, $badge, $spans = null ) { $id = isset( $t['id'] ) ? (int) $t['id'] : 0; $context = isset( $ctx['context'] ) ? (string) $ctx['context'] : ''; if ( $id <= 0 || ! in_array( $context, array( 'shortcode', 'block', 'compat' ), true ) || isset( $ctx['cell'] ) ) { return ''; } /** * Minimum number of body rows for the cache. Small tables render in a few milliseconds. * * @param int $min Rows. * @param array $t Table. */ if ( count( $body_rows ) < (int) apply_filters( 'nitida_tables_render_cache_min_rows', 200, $t ) ) { return ''; } /** * Whether the body of this table may be cached. * * @param bool $use Use the cache. * @param array $t Table. * @param array $ctx Render context. */ if ( ! apply_filters( 'nitida_tables_render_cache', true, $t, $ctx ) ) { return ''; } /** * Extra key material from extensions whose row or cell filters depend on their own settings. * * @param string $salt Salt. * @param array $t Table. * @param array $ctx Render context. */ $salt = (string) apply_filters( 'nitida_tables_render_cache_salt', '', $t, $ctx ); $key = array( NITIDA_TABLES_VERSION, $body_rows, $cols, $kinds, $labels, (string) $badge, $salt ); if ( $spans ) { $key[] = $spans; } $sig = md5( serialize( $key ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- only hashed. return 'nitida_tables_body_' . $id . '_' . $sig; } /** Stores a body and remembers its key, so saving or deleting the table can drop it. */ private static function cache_store( $id, $key, $body ) { if ( ! set_transient( $key, $body, WEEK_IN_SECONDS ) ) { return; } $idx = get_option( self::CACHE_INDEX, array() ); $idx = is_array( $idx ) ? $idx : array(); $list = isset( $idx[ $id ] ) && is_array( $idx[ $id ] ) ? array_values( array_diff( $idx[ $id ], array( $key ) ) ) : array(); $list[] = $key; while ( count( $list ) > self::CACHE_PER_TABLE ) { delete_transient( array_shift( $list ) ); } $idx[ $id ] = $list; update_option( self::CACHE_INDEX, $idx, false ); } /** Drops the cached bodies of a table (no id: of all tables). */ public static function flush_cache( $id = null ) { $idx = get_option( self::CACHE_INDEX, array() ); if ( ! is_array( $idx ) || ! $idx ) { return; } $ids = null === $id ? array_keys( $idx ) : array( (int) $id ); foreach ( $ids as $i ) { if ( empty( $idx[ $i ] ) || ! is_array( $idx[ $i ] ) ) { continue; } foreach ( $idx[ $i ] as $key ) { delete_transient( $key ); } unset( $idx[ $i ] ); } if ( $idx ) { update_option( self::CACHE_INDEX, $idx, false ); } else { delete_option( self::CACHE_INDEX ); } } /** [nitida_table id="N"] */ public static function shortcode( $atts ) { $atts = shortcode_atts( array( 'id' => '' ), (array) $atts, 'nitida_table' ); return self::output( (string) $atts['id'], 'shortcode' ); } /** Shared by the shortcode, the compat shortcode and the block. */ public static function output( $id, $context ) { $id = trim( (string) $id ); $t = ctype_digit( $id ) ? Store::get( (int) $id ) : null; if ( ! $t ) { return current_user_can( Settings::capability() ) /* translators: %s: table number */ ? '

' . esc_html( sprintf( __( 'Nitida Tables: table %s was not found.', 'nitida-tables' ), $id ) ) . '

' : ''; } self::enqueue(); return self::render_table( $t, array( 'context' => $context ) ); } /* --------------------------------------------------------------------- * Assets * ------------------------------------------------------------------ */ public static function register_assets() { // Called from the block registration (init) and wp_enqueue_scripts; inline CSS must be added only once. if ( wp_style_is( 'nitida-tables', 'registered' ) ) { return; } $inline = 'inline' === Settings::get( 'css_mode' ); if ( $inline ) { wp_register_style( 'nitida-tables', false, array(), NITIDA_TABLES_VERSION ); wp_add_inline_style( 'nitida-tables', self::file( 'assets/css/frontend.css' ) ); wp_register_script( 'nitida-tables', false, array(), NITIDA_TABLES_VERSION, true ); wp_add_inline_script( 'nitida-tables', self::file( 'assets/js/frontend.js' ) ); } else { wp_register_style( 'nitida-tables', NITIDA_TABLES_URL . 'assets/css/frontend.css', array(), NITIDA_TABLES_VERSION ); wp_register_script( 'nitida-tables', NITIDA_TABLES_URL . 'assets/js/frontend.js', array(), NITIDA_TABLES_VERSION, array( 'in_footer' => true, 'strategy' => 'defer' ) ); } $extra = self::settings_css(); if ( '' !== $extra ) { wp_add_inline_style( 'nitida-tables', $extra ); } } /** Wrapper classes from the settings (style, density, header, dark mode, cards). */ public static function wrapper_classes() { $c = array( 'nitida-table' ); if ( 'clean' !== Settings::get( 'style' ) ) { $c[] = 'nitida-table--style-' . Settings::get( 'style' ); } if ( 'compact' === Settings::get( 'density' ) ) { $c[] = 'nitida-table--compact'; } if ( 'accent' === Settings::get( 'header_style' ) ) { $c[] = 'nitida-table--head-accent'; } if ( 'auto' === Settings::get( 'dark_mode' ) ) { $c[] = 'nitida-table--dark-auto'; } if ( 'off' === Settings::get( 'cards' ) ) { $c[] = 'nitida-table--no-cards'; } return $c; } /** Card rules for narrow containers, built from the media-query block of frontend.css. */ public static function cards_css( $width ) { $css = self::file( 'assets/css/frontend.css' ); $a = strpos( $css, '/* cards:start */' ); $b = strpos( $css, '/* cards:end */' ); if ( false === $a || false === $b || (int) $width <= 0 ) { return ''; } $body = substr( $css, $a + 17, $b - $a - 17 ); return '@container nitidatable (max-width: ' . (int) $width . 'px){' . preg_replace( '/\s+/', ' ', $body ) . '}'; } /** CSS from the settings: accent color, corner radius, card width and the dark-mode selector. */ public static function settings_css() { $css = ''; $accent = (string) Settings::get( 'accent' ); $vars = ''; if ( '' !== $accent ) { // A theme variable that is missing on some pages (or in previews) falls back to the default blue. if ( 0 === strpos( $accent, 'var(' ) ) { $accent = substr( $accent, 0, -1 ) . ',#2563eb)'; } $vars .= '--tt-accent:' . $accent . ';'; } if ( 12 !== (int) Settings::get( 'radius' ) ) { $vars .= '--tt-radius:' . (int) Settings::get( 'radius' ) . 'px;'; } if ( '' !== $vars ) { $css .= '.nitida-table{' . rtrim( $vars, ';' ) . '}'; } if ( 'off' !== Settings::get( 'cards' ) ) { $css .= self::cards_css( (int) Settings::get( 'cards' ) ); } $sel = (string) Settings::get( 'dark_selector' ); if ( 'selector' === Settings::get( 'dark_mode' ) && '' !== $sel ) { $parts = array_filter( array_map( 'trim', explode( ',', $sel ) ) ); $css .= implode( ',', array_map( function ( $p ) { return $p . ' .nitida-table'; }, $parts ) ) . '{' . self::dark_vars() . '}'; // The minimal style has no surface of its own: it keeps the theme's background and text color. $css .= implode( ',', array_map( function ( $p ) { return $p . ' .nitida-table.nitida-table--style-minimal'; }, $parts ) ) . '{--tt-bg:transparent;--tt-text:currentColor;--tt-hover:color-mix(in srgb,currentColor 7%,transparent)}'; } return $css; } /** Dark palette (also used inside frontend.css for prefers-color-scheme). */ public static function dark_vars() { return '--tt-border:#2c3341;--tt-line:#252b37;--tt-head:#1c212b;--tt-bg:#151920;--tt-text:#e6e9ef;--tt-muted:#98a2b3;--tt-hover:#1b2029;--tt-ok:#5fd4a0;--tt-ok-bg:#143327;--tt-link:color-mix(in srgb,var(--tt-accent) 60%,#fff)'; } /** Enqueue early when the main post uses a table, so styles load in the head. */ public static function maybe_enqueue_early() { if ( ! is_singular() ) { return; } $post = get_post(); if ( ! $post ) { return; } $c = (string) $post->post_content; if ( has_shortcode( $c, 'nitida_table' ) || has_block( 'nitida-tables/table', $post ) || ( Settings::get( 'compat_shortcode' ) && has_shortcode( $c, 'table' ) ) ) { self::enqueue(); } } public static function enqueue() { if ( self::$enqueued ) { return; } self::$enqueued = true; if ( ! wp_style_is( 'nitida-tables', 'registered' ) ) { self::register_assets(); } wp_enqueue_style( 'nitida-tables' ); wp_enqueue_script( 'nitida-tables' ); } /** Reads a bundled asset file (used for the inline mode and the editor preview). */ public static function file( $rel ) { $path = NITIDA_TABLES_DIR . ltrim( $rel, '/' ); return is_readable( $path ) ? (string) file_get_contents( $path ) : ''; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents } }