package HTML::Strip::Whitespace;
$HTML::Strip::Whitespace::VERSION = '0.2.3';
use strict;
use warnings;

use 5.016;

package HTML::Strip::Whitespace::State;
$HTML::Strip::Whitespace::State::VERSION = '0.2.3';
sub new
{
    my $class = shift;
    my $self  = {};
    bless $self, $class;
    $self->initialize(@_);
    return $self;
}

sub to_array
{
    my $v = shift;
    return ( ref($v) eq "ARRAY" ? (@$v) : $v );
}

sub initialize
{
    my $self = shift;
    my %args = (@_);
    $self->{'prev'} = undef;
    $self->{'next'} = undef;
    $self->{'this'} = undef;
    $self->{'parser'} =
        HTML::TokeParser::Simple->new( to_array( $args{'parser_args'} ) );

    $self->{'strip_newlines'} = $args{'strip_newlines'} || 0;
    $self->{'out_fh'}         = $args{'out_fh'};

    # Get the first element to initialize the parser
    # Otherwise the first call to next_state would return undef;
    $self->next_state();

    return 0;
}

sub next_state
{
    my $self = shift;
    ( $self->{'prev'}, $self->{'this'}, $self->{'next'} ) =
        ( $self->{'this'}, $self->{'next'}, $self->{'parser'}->get_token() );
    return defined( $self->{'this'} );
}

sub prev
{
    my $self = shift;
    return $self->{'prev'};
}

sub next
{
    my $self = shift;
    return $self->{'next'};
}

sub this
{
    my $self = shift;
    return $self->{'this'};
}

sub text_strip
{
    my $self = shift;

    # my $p = $self->prev();
    # my $n = $self->next();

    my $text = $self->this()->as_is();

    $text =~ s{([\s\n]+)}{($1 =~ /\n/) ? "\n" : " "}eg;

    return $text;
}

my %preserving_start_tags = ( 'pre' => 1, );

sub is_preserving_start_tag
{
    my $self = shift;
    my $t    = $self->this();
    if ( $t->is_start_tag()
        && exists( $preserving_start_tags{ $t->get_tag() } ) )
    {
        return $t->get_tag();
    }
    return '';
}

sub handle_text
{
    my $state = shift;

    if ( $state->this->is_text() )
    {
        $state->out( $state->text_strip() );
        return 0;
    }
    else
    {
        return 1;
    }
}

sub out
{
    my $self   = shift;
    my $what   = shift;
    my $out_fh = $self->{'out_fh'};

    if ( ref($out_fh) eq "CODE" )
    {
        &{$out_fh}($what);
    }
    elsif ( ref($out_fh) eq "SCALAR" )
    {
        $$out_fh .= $what;
    }
    elsif ( ref($out_fh) eq "GLOB" )
    {
        print { *{$out_fh} } $what;
    }

    return 0;
}

sub out_this
{
    my $state = shift;
    $state->out( $state->this()->as_is() );
}

sub process
{
    my $state = shift;

    my $tag_type;

    while ( $state->next_state() )
    {
        if ( !$state->handle_text() )
        {
            # Text was handled
        }

        # If it's a preserving start tag, preserve all the text inside it.
        # This is for example, a <pre> tag in which the spaces matter.
        elsif ( $tag_type = $state->is_preserving_start_tag() )
        {
            my $do_once = 1;
            while ( $do_once || $state->next_state() )
            {
                $do_once = 0;
                $state->out_this();
                last if ( $state->this()->is_end_tag($tag_type) );
            }
        }
        else
        {
            $state->out_this();
        }
    }

    # Return 0 on success.
    return 0;
}

package HTML::Strip::Whitespace;

use 5.016;
use strict;
use warnings;

use HTML::TokeParser::Simple;

use parent 'Exporter';
use vars qw(@EXPORT @EXPORT_OK %EXPORT_TAGS);

%EXPORT_TAGS = (
    'all' => [
        qw(
            html_strip_whitespace
        )
    ]
);

@EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

@EXPORT = qw(

);

# Preloaded methods go here.

sub html_strip_whitespace
{
    my %args   = (@_);
    my $source = $args{'source'}
        or die "source argument not specified.";
    my $strip_newlines = $args{'strip_newlines'} || 0;
    my $out_fh         = $args{'out'}
        or die "out argument not specified.";
    my $state = HTML::Strip::Whitespace::State->new(
        'parser_args'    => $source,
        'strip_newlines' => $strip_newlines,
        'out_fh'         => $out_fh,
    );

    return $state->process();
}

# Autoload methods go after =cut, and are processed by the autosplit program.

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

HTML::Strip::Whitespace - Perl extension for stripping whitespace out of
HTML.

=head1 VERSION

version 0.2.3

=head1 SYNOPSIS

    use HTML::Strip::Whitespace qw(html_strip_whitespace);

    my $html = <<"EOF";
    <html>
    <body>

    <p>
        Hello there!
    </p>

    </body>
    </html>
    EOF
    my $buffer = "";

    html_strip_whitespace(
        'source' => \$html,
        'out' => \$buffer
        );

=head1 DESCRIPTION

This module tries to strip as much whitespace from an HTML as it can
without eliminating valid whitespace (like the one inside <pre>).

To use it call the function C<HTML::Strip::Whitespace::html_strip_whitespace>,
with named parameters. C<source> is the HTML::TokeParser source for the
HTML. C<out> can be a reference to a buffer which will be filled with the
stripped HTML, or alternatively a reference to a sub-routine or a file handle
that will output it.

=head1 FUNCTIONS

=head2 html_strip_whitespace(source => $src, out => $out, strip_newlinews => $strip)

C<source> is the HTML::TokeParser source for the
HTML. C<out> can be a reference to a buffer which will be filled with the
stripped HTML, or alternatively a reference to a sub-routine or a file handle
that will output it.

=head1 LINKS

=over 4

=item * Homepage

L<http://web-cpan.shlomifish.org/modules/HTML-Strip-Whitespace/>

=item * Bitbucket.org (Mercurial) Repository

L<http://bitbucket.org/shlomif/perl-html-strip-whitespace>

=back

=head1 SEE ALSO

HTML Tidy with its Perl binding, which probably does a better and faster job
of performing this task.

L<HTML::Clean> is a module which also aims to optimise the size of HTML.

=head1 AUTHOR

Shlomi Fish, L<http://www.shlomifish.org/> (E-mail C<shlomif@cpan.org> ).

=head1 COPYRIGHT & LICENSE

Copyright 2004 by Shlomi Fish

This program is distributed under the MIT (X11) License:
L<http://www.opensource.org/licenses/mit-license.php>

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

=for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 SUPPORT

=head2 Websites

The following websites have more information about this module, and may be of help to you. As always,
in addition to those websites please use your favorite search engine to discover more resources.

=over 4

=item *

MetaCPAN

A modern, open-source CPAN search engine, useful to view POD in HTML format.

L<https://metacpan.org/release/HTML-Strip-Whitespace>

=item *

RT: CPAN's Bug Tracker

The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.

L<https://rt.cpan.org/Public/Dist/Display.html?Name=HTML-Strip-Whitespace>

=item *

CPANTS

The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.

L<http://cpants.cpanauthors.org/dist/HTML-Strip-Whitespace>

=item *

CPAN Testers

The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.

L<http://www.cpantesters.org/distro/H/HTML-Strip-Whitespace>

=item *

CPAN Testers Matrix

The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.

L<http://matrix.cpantesters.org/?dist=HTML-Strip-Whitespace>

=item *

CPAN Testers Dependencies

The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.

L<http://deps.cpantesters.org/?module=HTML::Strip::Whitespace>

=back

=head2 Bugs / Feature Requests

Please report any bugs or feature requests by email to C<bug-html-strip-whitespace at rt.cpan.org>, or through
the web interface at L<https://rt.cpan.org/Public/Bug/Report.html?Queue=HTML-Strip-Whitespace>. You will be automatically notified of any
progress on the request by the system.

=head2 Source Code

The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)

L<https://github.com/shlomif/perl-html-strip-whitespace>

  git clone git://github.com/shlomif/perl-html-strip-whitespace.git

=head1 AUTHOR

Shlomi Fish

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website
L<https://github.com/shlomif/perl-html-strip-whitespace/issues>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2024 by Shlomi Fish.

This is free software, licensed under:

  The MIT (X11) License

=cut
