package Data::JavaScript::Anon;

# This package provides a mechanism to convert the main basic Perl structures
# into JavaScript structures, making it easier to transfer data
# from Perl to JavaScript.

use strict;
use UNIVERSAL 'isa';

use vars qw{$VERSION $errstr};
BEGIN {
	$VERSION = "0.1";
	$errstr = ''; 
}





#####################################################################
# Top Level Dumping Methods

sub anon_dump {
	my $class = shift;
	my $something = shift;
	my $processed = shift || {};

	# Handle the undefined case
	return 'undefined' unless defined $something;

	# Handle the basic non-reference case
	return $class->anon_scalar( $something ) unless ref $something;

	# Check to see if we have processed this reference before.
	# This should catch circular, cross-linked, or otherwise complex things
	# that we can't handle.
	if ( $processed->{$something} ) {
		return $class->_err_found_twice( $something );
	} else {
		$processed->{$something} = 1;
	}

	# Handle the SCALAR reference case, which in our case we treat
	# like a normal scalar.
	if ( isa( $something, 'SCALAR' ) ) {
		return $class->anon_scalar( $something );
	}

	# Handle the array case by generating an anonymous array
	if ( isa( $something, 'ARRAY' ) ) {
		# Create and return the array
		return "[ "
			. join( ', ', map {
				$class->anon_dump($_, $processed)
				} @$something )
			. " ]";
	}

	# Handle the hash case by generating an anonymous object/hash
	if ( isa( $something, 'HASH' ) ) {
		# Create and return the anonymous hash
		return "{ "
			. join( ', ', map {
				$class->anon_hash_key( $_ )
				. ': '
				. $class->anon_dump( $something->{$_}, $processed )
				} keys %$something )
			. " }";
	}

	return $class->_err_not_supported( $something );
}

# Same thing, but creating a variable
sub var_dump {
	my $class = shift;
	my $name = shift or return undef;
	my $something = shift;

	return "var $name = "
		. $class->anon_dump( $something )
		. ';';
}

# Wrap some JavaScript in a HTML script tag
sub script_wrap {
	my $class = shift;
	my $javascript = shift;

	return "<script language=\"JavaScript\" type=\"text/JavaScript\">\n"
		. "<!--\n\n"
		. $javascript
		. "\n// -->\n"
		. "</script>";
}





#####################################################################
# Basic Variable Creation Statements

# Create a Javascript scalar given the javascript variable name
# and a reference to the scalar.
sub var_scalar {
	my $class = shift;
	my $name = shift or return undef;
	my $scalar_ref = isa( $_[0], 'SCALAR' )
		? shift : return undef;

	# Return the string
	return "var $name = "
		. $class->js_value( $$scalar_ref )
		. ";";
}

# Create a Javascript array given the javascript array name
# and a reference to the array.
sub var_array {
	my $class = shift;
	my $name = shift or return undef;
	my $array_ref = isa( $_[0], 'ARRAY' )
		? shift : return undef;

	# Create and return the array
	return "var $name = new Array( "
		. join( ', ', map { $class->anon_dump($_) } @$array_ref )
		. " );";
}

# Create a Javascript hash ( which is just an object ), given
# the variable name, and a reference to a hash.
sub var_hash {
	my $class = shift;
	my $name = shift or return undef;
	my $hash_ref = isa( $_[0], 'HASH' )
		? shift : return undef;

	# Create and return the hash
	return "var $name = " . $class->anon_hash( $hash_ref ) . ";";
}






#####################################################################
# Basic Serialisation And Escaping Methods

# Turn a single perl value into a single javascript value
sub anon_scalar {
	my $class = shift;
	my $value = isa( $_[0], 'SCALAR' ) ? ${shift()} : shift;
	return 'null' unless defined $value;
	{ no warnings;
		if ( $value eq '0' or $value != 0 ) {
			return $value;
		} else {
			$value =~ s/"/\\"/g;
			return '"' . $value . '"';
		}
	}
}

# Turn a single perl value into a javascript hash key
sub anon_hash_key {
	my $class = shift;
	my $value = shift;
	return undef unless defined $value;
	{ no warnings;
		if ( $value eq '0' or $value != 0 ) {
			return $value;
		}
	}
	
	# Don't quote if it is just a set of word characters
	return $value if $value =~ /^\w+$/;
	
	# Escape as normal
	$value =~ s/"/\\"/g;
	return '"' . $value . '"';
}

# Create a Javascript array given the javascript array name
# and a reference to the array.
sub anon_array {
	my $class = shift;
	my $name = shift or return undef;
	my $array_ref = isa( $_[0], 'ARRAY' )
		? shift : return undef;

	# Create and return the array
	return "[ "
		. join( ', ', map {
			$class->anon_scalar($_)
			} @$array_ref )
		. " ]";
}

# Create a Javascript hash ( which is just an object ), given
# the variable name, and a reference to a hash.
sub anon_hash {
	my $class = shift;
	my $name = shift or return undef;
	my $hash_ref = isa( $_[0], 'HASH' )
		? shift : return undef;

	# Create and return the hash
	return "{ "
		. join( ', ', map {
			$class->anon_hash_key( $_ )
			. ': '
			. $class->anon_scalar( $hash_ref->{$_} )
			} keys %$hash_ref )
		. " }";
}





#####################################################################
# Utility and Error Methods

sub _err_found_twice {
	my $class = shift;
	my $something = shift;
	$errstr = 'Found ' . (ref $something or 'a reference')
		. ' in your dump more than once. '
		. 'Serialize::Javascript does not support complex, circular, or cross-linked data structures';
	return undef;
}

sub _err_not_supported {
	my $class = shift;
	my $something = shift;
	$errstr = (ref $something or 'A reference of unknown type')
		. ' was found in the dump struct. '
		. 'Serialize::Javascript only supports objects based on, or references to SCALAR, ARRAY and HASH type variables.';
	return undef;
}

1;

__END__

=head1 NAME

Data::JavaScript::Anon - Create big, dumb and/or anonymous data structures in JavaScript

=head1 SYNOPSIS

  # Dump an arbitrary structure to javascript
  Data::JavaScript::Anon->anon_dump( [ 'a', 'b', { a => 1, b => 2 } ] );

=head1 DESCRIPTION

Data::JavaScript::Anon provides the ability to dump large simple data
structures to JavaScript. That is, things that don't need to be a class,
or have special methods or whatever.

The method it uses is to write anonymous variables, in the same way you
would in Perl. The following shows some examples.

  # Perl anonymous array
  [ 1, 'a', 'Foo Bar' ]
  
  # JavaScript equivalent ( yes, it's exactly the same )
  [ 1, 'a', 'Foo Bar' ]
  
  # Perl anonymous hash
  { foo => 1, bar => 'bar' }
  
  # JavaScript equivalent
  { foo: 1, bar: 'bar' }

One advantage of doing it in this method is that you do not have to
co-ordinate variable names between your HTML templates and Perl. You
could use a simple Template Toolkit phrase like the following to get
data into your HTML templates.

  var javascript_data = [% data $];

In this way, it doesn't matter WHAT the HTML template calls a
particular variables, the data dumps just the same. This could help
you keep the work of JavaScript and Perl programmers ( assuming you
were using different people ) seperate, without creating work
cross dependencies.

The variables you dump can also be of arbitrary depth and complexity,
with a few limitations.

=over 4

=item ARRAY and HASH only

Since arrays and hashs are all that is supported by JavaScript, they
are the only things you can use in your structs. Although not supported,
they will be detected, and an error returned.

=item No Circular References

Since circular references can't be defined in a single anonymous struct,
they are not allowed. Try something like L<Data::JavaScript> instead.
Although not supported, they will be detected, and an error returned.

=back

=head1 MAIN METHODS

All methods are called as methods directly, in the form
C<< Data::JavaScript::Anon->anon_dump( [ 'etc' ] ) >>.

=head2 anon_dump( struct )

The main method of the class, anon_dump takes a single arbitrary data
struct, and converts it into an anonymous JavaScript struct.

If needed, the argument can even be a normal text string, although it
wouldn't do a lot to it. :)

Returns a string containing the JavaScript struct on success, or C<undef>
if an error is found.

=head2 var_dump( $name, struct )

As above, but the C<var_dump> method allows you to specify a variable name,
with the resulting JavaScript being C<var name = struct;>. Note that the
method WILL put the trailing semi-colon on the string.

=head2 script_wrap( $javascript )

The C<script_wrap> method is a quick way of wrapping a normal JavaScript html
tag around your JavaScript.

=head1 SECONDARY METHODS

The following are a little less general, but may be of some use.

=head2 var_scalar( $name, \$scalar )

Creates a named variable from a scalar reference.

=head2 var_array( $name, \@array )

Creates a named variable from an array reference.

=head2 var_hash( $name, \%hash )

Creates a named variable from a hash reference.

=head2 anon_scalar( \$scalar )

Creates an anonymous JavaScript value from a scalar reference.

=head2 anon_array( \@array )

Creates an anonymous JavaScript array from an array reference.

=head2 anon_hash( \%hash )

Creates an anonymous JavaScript object from a hash reference.

=head2 anon_hash_key( $value )

Applys the formatting for a key in a JavaScript object


=head1 SUPPORT

Contact the author or file a bug at

http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Data%3A%3AJavaScript%3A%3AAnon

=head1 AUTHOR

    Adam Kennedy
    cpan@ali.as
    http//ali.as/

=head1 COPYRIGHT

Copyright (c) 2003 Adam Kennedy. All rights reserved.
This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.

=cut
