SnippetVamp

Ne perds plus jamais de temps en cherchant tes snippets !

Bienvenue dans mon SnippetVamp.

1 - unicode2entity - convertir les caracteres unicode (même multiples) en leut codepoint
function unicode2entity($car){
		$code='';
		$l=mb_strlen($car);
		for ($i=0;$i<$l;$i++){
			$current_car=mb_substr($car, $i,1);
			$code.=sprintf("&#x%04X;", mb_ord($current_car,'UTF-8'));
		}
		return $code;
	}
			
2 - Styler les input radio sans framework
input[type="radio"] {
  /* Disable the browser's default radio button styles */
  appearance: none;
  margin: 0;

  /* Recreate the circle container */
  border: 1px solid black;
  background: white;
  border-radius: 50%;

  /* Center our dot in the container */
  display: inline-grid;
  place-content: center;

  /* Use a pseudo-element to display our "dot" */
  &::before {
    content: "";
    width: 0.75rem;
    height: 0.75rem;
    border-radius: 50%;
  }

  /* And display it when the radio button is checked */
  &:checked::before {
    background: black;
  }
}
			
4 - Modifier une couleur de base en CSS

*{
    --base-color:red;
}

/*Ajouter de la transparence*/
.transparent{
    hsl(from var(--base-color) h s calc(l + 12));
}

/* désaturer une couleur de base*/
.desat{
    color: hsl(from var(--base-color) h calc(s + -50) l);
}

/* complémentaire*/
.complementaire{
    hsl(from var(--base-color) calc(h + 180) s l);
}

/* plus loin : primary, seconday, tertiary*/
.primary{
    hsl(from var(--base-color) calc(h + 90) s l);
}
.secondary{
    hsl(from var(--base-color) calc(h + 180) s l);
}
.tertiary{
    hsl(from var(--base-color) calc(h + 270) s l);
}



			
6 - filtrer les caractéres interdits pour un fichier
// filtre tous les inputs ayant l'attribut alphanum-only

	on("input","[alphanum-only]",function(e){
		let obj=e.target;
		let cursor_position=obj.selectionStart;
		obj.value=obj.value.replace(new RegExp(/[^a-zA-z0-9\-_ ]/g), "");
		obj.selectionStart=cursor_position;
		obj.selectionEnd=cursor_position;
	});
			
8 - déclencher un download de données en js
// Objet JavaScript brut
const obj = { recette: 'Rôti au kiwi', duree: 120, ingredients: 3 };

// Données à exporter converties en chaîne de texte
const data = JSON.stringify(obj);

// Crée un blob à partir des données
const blob = new Blob([data], { type: 'application/json' });

// Génère une URL temporaire
const url = window.URL.createObjectURL(blob);

// Crée un lien et déclenche le téléchargement
const link = document.createElement('a');
link.href = url;
link.download = 'data.json';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

// Libère l’URL temporaire et la mémoire 🧹
window.URL.revokeObjectURL(url);
			
11 - IP du client (avec proxy)
function get_remote_ip(){
	$ip=!empty($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:false;
	$ip=!empty($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip; # throug proxy ?
	return $ip;
}
			
17 - sauvegarder un node en html
var doc=first('#node').innerHTML;
var name="filename.html";   
var myFile = new Blob([doc], {type: 'text/plain'});		
		
window.URL = window.URL || window.webkitURL;
var a= create('a',{href:window.URL.createObjectURL(myFile),download:name});
a.click();
			
18 - footer en bas de page en deux lignes
body{
	display:grid;
	grid-template-rows: auto 1fr auto;
}
avec une structure HTML:

<body>
    <header></header>
    <main></main>
    <footer></footer>
</body>
			
20 - Ajouter simplement une confirmation à un lien
<a href="lien" confirm="Êtes-vous sûr ?">Action à confirmer</a>

on("click","a[confirm]",function(e){
	msg=attr(e.target,"confirm");
	if(!msg){msg="Veuillez confirmer";}
	if (!confirm(msg)){
		e.preventDefault();
		return false;
	}
})
			
21 - Closure avec variable du scope exterieur
$closure=function ($arg1,$arg2) use ($var_exterieure){
    #come on, do something
};
			
24 - firstCap()
	function firstCap($str){
		$str=str_replace('_',' ', $str);
		$str=ucwords($str);
		$str=str_replace(' ','',$str);
		return $str;
	}
			
25 - labels input flottants CSS pur
// HTML
<body>
	<form>
		<h1>Please login</h1>
		<label><span>Username</span>
			<input type="text" name="login" value="" placeholder=" " >
		</label>
		<label><span>Password</span>
			<input type="password" name="pswd" value="" placeholder=" ">
		</label>

		<input type="submit" value="Ok">
		<hr>
		<h4>or <a href="">subscribe</a></h4>
	</form>

</body>

// CSS
body{
	height: 100%;
	max-height: 100%;
}
form{
	max-width:320px;
	margin:auto;
	border:1px solid rgba(0,0,0,0.2);
	border-radius: 0.5em;
	padding:0.5em;
	background:var(--color);
	
	position : relative;
    top: 50%;
    transform: translateY(-50%);

}
label{
	display: block;
	margin-top:1em;
}
input{
	outline: 0;
	display: block;
	width:100%;
	border-radius: 0.5em;
	border:1px solid rgba(0,0,0,0.2);
	margin-top:0.5em;
}

input[name="login"]{
	padding:0.5em;
	padding-left:24px;
	background: url(http://api.warriordudimanche.net/iconeleon/?i=fontawesome%20solid/circle-user.svg&c=black) no-repeat 4px center;
	background-size: 16px 16px;
}
input[type="password"]{
	padding:0.5em;
	padding-left:24px;
	background: url(http://api.warriordudimanche.net/iconeleon/?i=elusive/unlock-alt.svg&c=black) no-repeat 4px center;
	background-size: 16px 16px;
}

label span{
	position: relative;
	top:2em;
	left:24px;
	transition:all 500ms;
}
label:has(input:placeholder-shown) span{
	position: relative;
	top:2em;
	left:24px;
	transition:all 500ms;
}

label:has(input:focus) span,
label:has(input:not(:placeholder-shown)) span
{
	color:blue;
	top:0;
	left:0;
	transition:all 500ms;
}



			
26 - fonction PHP - servir un fichier avec headers corrects
function serveFile($path){

	if (is_file($path)){
		$mime=mime_content_type($path);
		header('Content-type: '.$mime.'; charset=utf-8');
		header('Content-Transfer-Encoding: binary');
		header('Content-Disposition: filename="'.tools::basename($path).'"');
		header('Content-Length: '.filesize($path));
		readfile($path);
		exit;
	}
        header("HTTP/1.1 404 Not Found");
        exit('404 - Not Found (╯°□°)╯︵ ┻━┻');

}
			
27 - folder2array()
function folder2array($path=''){
		//$path=empty($path)?'./':$path;
		$array=[];
		$current_dir=glob($path.'/*');
		if ($current_dir[0]==$path) unset($current_dir[0]);
		foreach ($current_dir as $key => $item) {
			if (is_file($item)){
				$array[]=$item;
			}else{
				$array[]=folder2array($item);
			}
		}
		return $array;
	}
			
28 - poster un blob vers PHP
// on utilise un filereader
function sendBlob(theBlob){  
  let reader = new FileReader();
  reader.addEventListener("loadend", function () {
    formData = new FormData();
    formData.append("blob", reader.result);
    formData.append("path", destination_folder);
    formData.append("token", token);
    postBlob(formData);
  });

  reader.readAsDataURL(theBlob);
}

function postBlob(data){
  fetch("index.php", { method: 'POST', body: data })
  .then((response)=>{return response.text()})
  .then((text)=>{
    token=text;
    alert("Fichier sauvegardé.");
  });
  
}
			
30 - trigger event on HTML element using JavaScript - 30 seconds of code
const triggerEvent = (el, eventType, detail) =>
  el.dispatchEvent(new CustomEvent(eventType, { detail }));

const myElement = document.getElementById('my-element');
myElement.addEventListener('click', e => console.log(e.detail));

triggerEvent(myElement, 'click');
// The event listener will log: null

triggerEvent(myElement, 'click', { username: 'bob' });
// The event listener will log: { username: 'bob' }