<?php if (!defined('PmWiki')) exit();
/** sagecell.php
 *	Embed an interactive SageCell in a wikipage
 */
$RecipeInfo['SageCell']['Version'] = '2025-01-18';

SDV($SageCellDefaultArgs, array(
	"evalButtonText"	=>	"Evaluate",
	"autoeval"			=>	"false",
	"editor"			=>	"codemirror",
	"languages"			=>	"sage",
	"replaceOutput"		=>	"true",
	"hide"				=>	""
));

Markup('sage', 'fulltext', '/\(:sage(?:\s+([^\n]+))?:\)(.*?)\(:sageend:\)/si', 'SageCell');
function SageCell($m) {
	static $sage_id = 1;
	static $sage_linked_cells = array();

	global $SageCellDefaultArgs;
	$args = array_merge($SageCellDefaultArgs, array_slice(ParseArgs($m[1]), 1));
	SageRectifyArgs($args);
	
	$input_location = isset($args['linked']) 
					  ? ".sage_linked_{$args['linked']}"
					  : "#sage_{$sage_id}";

	if (   isset($args['linked']) == false
		|| $sage_linked_cells[$args['linked']] == null) {
		if (isset($args['linked']))
			$sage_linked_cells[$args['linked']] = 1;
		$args['linked'] = isset($args['linked']) ? 'true' : 'false';
		
		global $HTMLFooterFmt;
		$sagecell_script = "
<script>
$(function () {
	sagecell.makeSagecell({ inputLocation:	'{$input_location}',
                            evalButtonText:	 {$args['evalButtonText']},
                            autoeval:		 {$args['autoeval']},
                            editor:			 {$args['editor']},
                            languages:		 {$args['languages']},
                            linked:			 {$args['linked']},
                            replaceOutput:	 {$args['replaceOutput']},
                            hide:			 {$args['hide']}
                            });
 });
</script>
";
		$HTMLFooterFmt[] = $sagecell_script;
	}
	
	$class = ($input_location[0] == '.') 
			 ? 'sage ' . substr($input_location, 1) 
			 : 'sage';
	$out = "<div id='sage_{$sage_id}' class='$class'><script type='text/x-sage'>";
	$out .= $m[2];
	$out .= '</script></div>';

	SageCellAppendFooter();
	$sage_id++;
	return Keep($out);
}

function SageCellAppendFooter () {
	static $ran_once = false;
	if (!$ran_once) {
		global $HTMLHeaderFmt;
		$HTMLHeaderFmt['SageCell'] = '
		<script src="https://sagecell.sagemath.org/static/jquery.min.js"></script>
		<script src="https://sagecell.sagemath.org/static/embedded_sagecell.js"></script>
		';
	}
	$ran_once = true;
}

function SageRectifyArgs(&$args) {
	$args_to_enquote = array(
		'evalButtonText',
		'editor'
	);
	foreach ($args_to_enquote as $a) {
		enquote($args[$a]);
	}
	
	if ($args['languages'] == 'allLanguages')
		$args['languages'] = 'sagecell.allLanguages';
	else
		$args['languages'] = "[ '" . implode("', '", explode(',', $args['languages'])) . "' ]";
		
	$args['hide'] = "[ '" . implode("', '", explode(',', $args['hide'])) . "' ]";
}
function enquote(&$string, $double = false) {
	$q = $double ? '"' : "'";
	$string = $q.$string.$q;
}