
<script>

	import Button from './Chat_button.svelte';
	import Msg from './Chat_msg.svelte';

	export let layout = "";
	export let back = "";

	let msg = "";
	let text_area;
	let index = 0;
	let msgs = [];

	function add_msg(from, the_msg)
	{
		msgs = [...msgs, { id: index, content: the_msg, name: from }];
		index++;
	}

	function send_msg()
	{
		msg = msg.trim();

		if (msg.length > 0) {
			//socket.emit('sendmsg', msg);
			add_msg("me", msg);
		}

		msg = "";
		text_area.focus();
	}

	function send_msg_if(evt)
	{
		if (evt.shiftKey && evt.key === "Enter")
		{
			evt.preventDefault();
			send_msg();
		}
	}

</script>

<div class="grid_box">

	<!-- back -->
	<Button bind:layout new_layout={back} my_class="back icon" my_title="go back {back}">
		back
	</Button>

	<!-- room_name -->
	<Button bind:layout new_layout="room_set" my_class="room_name transparent">
		&lt;room_name&gt;
	</Button>

	<!-- close -->
	<Button bind:layout new_layout="close" my_class="close icon">
		close
	</Button>

	<!-- msg -->
	<div class="panel panel_msg">
		<div class="msg_thread">
			{#each msgs as msg}
				<Msg name={msg.name} content={msg.content} />
			{/each}
		</div>
	</div>

	<!-- write -->
	<div class="panel_write">
		<div
			class="text_area"
			bind:innerHTML={msg}
			bind:this={text_area}
			on:keypress={send_msg_if}
			contenteditable="true"
		>
		</div>
	</div>

	<!-- send -->
	<Button my_class="send" on_click={send_msg}>
		send
	</Button>

</div>

<style>

	/* grid layout "room"
	*/
	.grid_box :global(.back       ) {grid-area: back;}
	.grid_box :global(.room_name  ) {grid-area: room_name;}
	.grid_box :global(.close      ) {grid-area: close;}
	.grid_box :global(.panel_msg  ) {grid-area: panel_msg;}
	.grid_box :global(.send       ) {grid-area: send;}
	.grid_box :global(.panel_write) {grid-area: panel_write;}
	.grid_box {
		grid:
			' back         room_name    room_name  close      ' auto
			' panel_msg    panel_msg    panel_msg  panel_msg  ' 1fr
			' panel_write  panel_write  send       send       ' auto
			/ auto         1fr          auto       auto       ;
	}


	/* write area
	*/
	.panel_write {
		border: none;
		overflow: visible;
	}
	.text_area {
		display: block;
		position: absolute;
		bottom: 0px;
		left: 0px;
		width: 100%;
		height: 100%;

		overflow-x: hidden;
		overflow-y: scroll;
		background-color: white;
		border: 1px solid black;
	}
	.text_area:focus {
		height: auto;
		min-height: 100%;
		max-height: 300px;
	}
	.panel_write .text_area :global(*) {
		display: block ruby;
	}


	/* msg area
	*/
	.panel_msg {
		flex-direction: column-reverse;
		border: 1px solid black;
	}
	.msg_thread {
		width: 100%;
		padding: 0px 5px;
	}

</style>


