@home

November 23, 2022 Reading time: ~1 minute

Welcome

You reached a self-hosted website with no ambition except being some kind of a notepad as well as a personal sandbox. But feel free to take away anything you may find useful.

I'm considering publishing here short articles about what I'm learning. I'll avoid hosting images because I don't have much storage available.

Stay tuned!


grid overview

February 19, 2024 Reading time: 4 minutes

Two steps are required when it comes to building grid designs:

  1. slice a container into... a grid
  2. fill the cells or area of cells with elements

Imagine we work with following code:

<div id="container">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
</div>

The corresponding CodePen is of course available.

Slicing

First, we need our container to display its content as a grid : #container { display: grid; }. After that we need to slice down the container. There's two ways to do that:

Classic way

#container {
display: grid;
grid-gap: 1em;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}

Here we'll have a grid of 2 columns and 2 rows.

By name

#container {
display: grid;
grid-gap: 1em;
grid-template-areas:
"div1 div2"

"div3 div4"
}

Same here but we use names. In both cases we set up a gap, which is the space between the child element of the container.

Filling

Classic way

#div1 {
grid-column: 1;
grid-row: 1;

}

div1 will go in first column and first row.

By name

#div1 {
grid-area: div1;
}

Here we declare the element's name. As div1 was the first name on the first line, #div1 element will go on first column and first row.

Units and functions

For the slicing part, we can use different units, exclusively or in a combination, such as:

  • fraction (fr) - the browser divides the screen with the all fractions that were specified
  • relative units: %, vw, vh, auto...
  • fixed units: px
  • keywords: min or max-content, auto

We can also use functions, exclusively or in combination, such as:

  • repeat(nbOfTimes, unit)
  • minmax(minSize, maxSize)

Coordinates

For the filling part, we can set up precise coordinates which will be a line or a column line number with the syntax from / to

For instance, if our first div was supposed to fill the entire first line, we could write:

#div1 {
grid-column: 1 / 3;
grid-row: 1;

}

Where we are telling the brower to extend #div1 on column 1 and 2 (column 1 is between number 1 and 2 and column 2 between number 2 and 3).


CSS selectors

February 11, 2024 Reading time: 4 minutes

Target the right element is a must-know. Here's a recap of the available options. Examples are for the following structure:

<h2>Some title</h2>
<p>A paragraph</p>
<div>
<p>I am child of div</p>
<p>The guy up there is my bro.</p>
<section>
<p>Lonely paragraph</p>
</section>
<p>Third brother.</p>
</div>
<p>Out of div</p>
<p>Same</p>

As always, a demo is available on CodePen.

Combinators

Target a list of elements

Separate the elements with a ,.

h2, section {
font-weight: bolder;
color: navy;
}

Target all descendants of an element

Separate the parent element from the descendant element with a space.

div p {
text-decoration: underline;
}

Target all children of an element

Separate the parent element from the child element with a >.

body > p {
font-family: monospace;
}

Target the next sibling

Separate the first bro element from the second with a +.

div + p {
text-align: center;
}

Target all next siblings

Separate the first bro element from the other ones ~.

div ~ p {
width: 20%;
padding: 0.5em;
border: 0.25em solid indianred;
}

Pseudo-class selectors

A full list can be found on MDN Web Docs.

Target all first child from a parent element

Use a pseudo class after the element's name you want to target:

p:first-child {
letter-spacing: 0.25em;
}

Target every x element of a type from a parent

p:nth-of-type(3n) {
color: blue;
}

Pseudo-elements

Locate a starting point then create inline elements or specific decoration. For instance:

h2::before {
content: "♥ ";
}

h2::selection {
background-color: gold;
}

Attribute selectors

There's no attribute in the demo page. See attribute selectors


xHTML vs HTML5

January 26, 2024 Reading time: ~1 minute

I may have been stuck in xml model or several years ago but in the Uni course I learned that a HTML5 document doesn't validate if you close self-closing elements. You should write <img src="" alt="">, <br>, <hr> etc. and not <br/> and so on.

Here's the W3C HTML5 validator: https://validator.w3.org/nu/#textarea. You can also add an extension to your code editor.

Also, the closing tag may be omitted if a block element follows, for instance:

<p>Some text added
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>

is valid.

Confusing, eh!


A look back at 2023

January 6, 2024 Reading time: 6 minutes

Happy New Year from New Zealand! This is a schedulded post

2023 was amazingly dense. Here's a snapshot of my walk through the year.

Computer science

Web development

Thanks to FreeCodeCamp and W3Schools I made first steps with JavaScript libraries like React and jQuery and with CSS libraries like Bootstrap and Sass. React in particular was quite a challenge but in the end it was a good introduction to the component world, I feel like it will be very useful - and that is just the beginning.

Also, after proof-reading the two books that were released at les éditions du samedi in October, I went back into building EPUBs. I’m more comfortable in this exercise now I’m more familiar with command line (for executing epubcheck for instance) and since I’ve refreshed my HTML/CSS knowledge. I'm rather happy with the result!

Last but not least, I made progress in understanding and utilizing GitHub for Qwixx project and some others, like making my first pull request. I'm also discovering how Bludit is built and the existing plugins, for example I installed Disqus to allow comments!

Hardware

My Raspberry Pi, transformed into a server thanks to Yunohost, crashed due to its SD card that was corrupted. I rebooted it and now try to maintain it better than I did. I’m proud I found what the issue was and study how to prevent it. It was also the occasion of finding where to configure IPV6 ports and how to access the www folder via an FTP client.

My laptop is aging and the lack of memory made it freeze when coding or surfing on Firefox so I found out I could gently reboot as well as allow some more memory with a “swap file”. I’m happy I can make my computer last a little longer. My father-in-law also helped me with the electricty supply which was flickering.

Methodology

I try to be patient. I try to be kind to myself. These are not my strongest skills and I often feel like I'm wasting precious time trying to resolve a problem or understand a concept without making progress. Fortunately my wife* helps me and encourages me. Future me, please remember you have the right to find a topic challenging. Give it the time it needs and let it rest for a while if you feel you're stuck.

On the other hand, I think I'm rather good at planning. I'm happy I found a way to make progress on the Qwixx project by cutting it down to managable improvments (adding controls on user input), one step at a time. I also find it useful to blog on what I learn, at the moment (searching, explaining with my words) and later on (I'm often looking for previous posts for Boilerplates or Flexbox for instance!).

Aaand there's work as well. 4 days a week, not nothing! I was not far away from a burn out at the beginning of the year but it was better and brighter on the end. There is some projects to come I'm very excited about and I feel I'm more efficient with my programming skills (on XSLTs) and with understanding how things go together.

Life!

Well, it's been a year that a close friend is imprisoned. He’s keeping up. I would very much like to hug him again. Also on the dark side, my wife lost a childhood friend and my best friend lost her father-in-law. I did my best to give them support. Show love when you can!

*Yes, on the bright side the big news is that I got married! It was a lot of stress, of money and prep but well, love shines above all haha It was a beautiful and rainy and awesome day but wah, this is exhausting and neverending (thank you cards to send!)

What's next?

In 2024 I'll take a University course on my free time. So I think I'll continue learning web development!

What I'd like to achieve on computer science side:

  • writing article about jQuery
  • home server: autosave on dedicated USB key
  • laptop: add memory
  • Qwixx project: release v1, work on planning for v2
  • obtain my degree

React at a glance

November 26, 2023 Reading time: 19 minutes

Learning React on FreeCodeCamp was confusing. For the first time in the curriculum I had to find some tutorials and go through W3C course as well to help me out. Let's hope writing down will help me understand how to use it.

What

A JavaScript library to build user interfaces thanks to its own markup language called JSX (combination of HTML and JavaScript). It was created and is maintained by Facebook.

Render

React splits up the web page structure to separate components that can be displayed (rendered) according to a set of rules. To execute the rendition, the browser will need a transpiler (a converter) such as Babel.

Virtual DOM

React uses a virtual DOM where it does all the changes before passing them to the browser DOM.

Initiate

On CodePen

Pen Settings/JS tab: select Babel as JavaScript Preprocessor

On JS tab add

import * as ReactDOM from "https://cdn.skypack.dev/react-dom@18.2.0";
import * as React from "https://cdn.skypack.dev/react@18.2.0";

ReactDOM.render(
  <React.StrictMode>
   <App />
  </React.StrictMode>,
  document.getElementById("root")
)

And on HTML tab add

<div id="root"></div>

On computer

Make sure npx and Node.js are installed, then open a terminal and

  1. Go to the where you would like to create your application (ncd Documents/...)
  2. Run npx create-react-app my-react-app (my-react-app is the name of your app/directory)

Wait a few minutes and it the React environment be ready. Then (and anytime later when located on your project directory), just run npm start. A new browser window will pop up with your newly created React App! If not, open your browser and type localhost:3000 in the address bar. Changes you make will be visible immediately after you save the file, without reloading.

Basics

See all basics examples on CodePen. Each part is rendered in a different section for a better understanding but in this article we keep the rendering in a div with an id of root which is more common in real life.

Components

React components are named functions that return HTML. If you have a project on your hardrive, you can split your work: 1 component equals 1 js file (Capitalized).

For instance:

in App.css

.red {color: red}

in Hello.js

function Hello() {
return <h2>Hello World!</h2>
}

export default Hello;

in App.js

import Hello from './Hello'
import './App.css';

function App() {
  return <>
   <h1 className="red">This is the App Name</h1>
    <Hello/>
  </>
}

Will be translated as:

<div id="root">
<h1 class="red">This is the App Name</h1>
<h2>Hello World!</h2>
</div>

Observations:

  • Use <> and </> fragment to enclose your code if there's no HTML tag to encapsulate it.
  • You can call a component in another
  • The HTML class attribute has to be changed to className because class is a reserved keyword in JavaScript (and so, in JSX)
  • Vanilla HTML would have be enough for this example

Props & children

Components can recieve properties (which would act as function arguments) from element's attributes. For instance:

function Yummy(prop) {
return <p>I love {prop.treat}!</p>  
}

ReactDOM.render(
<React.StrictMode>
<Yummy treat="cookies" />
  </React.StrictMode>,
  document.getElementById("root")
)

prop will regroup all attributes and children that where provided in an object, this is why we use the dot notation un Yummy fonction. If there's only a few attributes, we can just import in the function the needed key:

function Yummy( {treat, children} ) {
return <p>I love {treat}! {children ? <strong>{children}</strong> : "Reasonably."}</p>
}

ReactDOM.render(
<React.StrictMode>
<Yummy treat="chocolate">
<em>Too much, actually.</em>
</Yummy>
  </React.StrictMode>,
  document.getElementById("root")
)

Note that the code to be treated as JavaScript should be within curly braces. Methods (functions) can be passed as properties.

Events

Let's have a look at this example for W3schools:

function Football() {
  const shoot = (a) => {
    alert(a);
  }
 
    return (
    <button onClick={() => shoot("Goal!")}>Take the shot!</button>
  );
}

ReactDOM.render(
<React.StrictMode>
<Football />
  </React.StrictMode>,
  document.getElementById("root")
)

Observations:

  • events are written in camelCase syntax (onClick instead of onclick)
  • event handlers are written inside curly braces
  • to pass arguments we need to use an arrow function

Conditional rendering

In this example, also from W3schools, we use two methods: && operator and ternary operator. We could also have used a classic if/else statement based on a prop value for instance (if prop is true, show this, else, show that).

function Garage(props) {
const cars = props.cars;
const message = `You have ${cars.length} cars in your garage.`;

return (
<>
<h3>Garage</h3>
{cars.length > 0 &&
<p>
Using && :<br/>
{message}
</p>
}

{
cars.length > 0 ?
<p>Using ternary operator :<br/>{message}</p> :
null
}
</>
);
}

const listofcars = [
{id: 1, brand: 'Ford'},
{id: 2, brand: 'BMW'},
{id: 3, brand: 'Audi'}
]

ReactDOM.render(
<React.StrictMode>
<Garage cars={listofcars} />
  </React.StrictMode>,
  document.getElementById("root")
)

Note: to use a variable within a string, nest the string intro backticks (`) and let you variable into curly brackets be preceded by a $ sign.

Keys

Use key for re-rendering only the element of a list that has been updated. Using the same listofcars constant from above as well as the map JavaScript method (which iterates every item of provided list):

function Car(props) {
return <li>{ props.brand }</li>;
}

function Vroum() {
return (
<>
<h1>List of cars</h1>
<ul>
{listofcars.map((listofcars) => <Car key={listofcars.id} brand={listofcars.brand} />)}
</ul>
</>
);
}

ReactDOM.render(
<React.StrictMode>
<Vroum />
  </React.StrictMode>,
  document.getElementById("root")
)

Hooks

Hooks connects rendering to particular changes which will be described here after. They replace class components since version 16.8. They can be customed, otherwise some are pre-made. All examples comes from W3Schools and are available on this CodePen.

Import

First of all, if you have not imported all React features (using import * as React from...), import the hooks you need, for instance:

import { useState, useEffect } from "react";

Doing so you are destructuring useState from react and can use it as is (rather than specify React.useState like in CodePen).

And keep in mind these 3 rules from W3Schools:

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional

In this article we'll just focus on three main hooks but feel free to explore the other existing ones (useContext, useReducer, useCallback, useMemo).

useState

Links a variable (its current state) to an updater function.

function App() {
const [color, setColor] = useState("yellow");
 
  return <>
    <p>My favorite color is {color}!</p>
    <button
        type="button"
        onClick={() => setColor("blue")}
      >Blue</button>
  </>
}

Observations:

  • to make the link, we use an array containing the variable and the function (commonly setVariablename)
  • useState("yellow") initiates the variable to the value "yellow" (a string)
  • read this variable in the return statement, simply calling it
  • update this variable with the function which contains "blue" as an argument (setting up a new state for color)

useState on an object

function App() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });

  const updateColor = () => {
    setCar(previousState => {
      return { ...previousState, color: "blue" }
    });
  }

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
      <button
        type="button"
        onClick={updateColor}
      >Blue</button>
    </>
  )
}

Observations:

  • we can read corresponding value of the object's property using the dot notation
  • we can't simply update a particular value in an object, we have to rewrite it (copy with ...previousState) and indicate the change afterwards. Otherwise the entire object will be replaced with the only pair color: "blue".

useEffect

Perform side effect like fetching data, updating DOM, play with timers and runs on every render. Don't forget the second parameter (an empty array or an array containing dependencies) which will prevent auto re-rendering.

function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);

useEffect(() => {
    setCalculation(() => count * 2);
  }, [count]); // if count updates, update calculation variable

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setCount((c) => c + 1)}>+</button>
      <p>Calculation: {calculation}</p>
    </>
  );
}

If there's a useEffect hook on a timer, it should be disposed to reduce memory leaks; for this name the te timer and use a return statement to clear it:

function Timer() {
const [count, setCount] = useState(0);

useEffect(() => {
    let timer = setTimeout(() => {
      setCount((count) => count + 1);
  }, 1000);

  return () => clearTimeout(timer)
  }, []);

  return <h1>I've rendered {count} times!</h1>;
}

useRef

Can be used to access a DOM element directly or to keep track of previous state value. useRef() returns an object called current which should be intialized.

DOM pointer

function Pointer() {
const inputElement = useRef();

  const focusInput = () => {
    inputElement.current.focus();
  };

  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

Using useRef, we associate the inputElement variable and the HTML element which have a ref attribute containing the variable's name. This is useful when we can't use getElementBySomething because the real DOM is not already built.

Previous state

function Before() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");

useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);

  return (
   <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
   </>
  );
}

Both inputValue and previousInputValue are initialized to an empty string. Each time there's an event (e) in the input field:

  • inputValue is updated via the setInputValue useState function and the variable equals field's content
  • as inputValue is changed and as it's a depedancy, useEffect comes in and replaces the value of current property to be equal to the inputValue. It is not re-rendered until there's another event in the input field.

We're done for now! Happy coding


zoom on some HTML tags

August 6, 2023 Reading time: 11 minutes

I'm taking w3schools HTML course as a refresher and I learned a few things along the way.

quotations

I knew about blockquote but not sure about the other two.

Quote from another source:

  • use blockquote tag with cite attribute containing URL to the source
  • browser behaviour: usually indent

Short inline quote:

  • use q tag
  • browser behaviour: usually add quotation mark

Indicate the title of a work:

  • use cite tag
  • browser behaviour: usually render in italic

td

td stands for table data! th (table header) and tr (table row) were clear to me but I always wondered why a table cell was written "td". Now I can properly read the code in my head haha

image size

In the img tag, prefer using style attribute with width and height properties inside rather than width and height attributes. style attribute takes precedence over the style defined in the linked CSS file (for instance max-width: 100%;) or at the HTML page level, but width and height attributes come second.

W3Schools recommends to always specify the width and height of an image. If not, the web page might flicker while the image loads.

picture

This element is new to me. Inside you can define a list of images to display acording to the screen size, so to save bandwith and cover different format supporting from the browsers. It should always ends with an img tag. For instance (from W3Schools):

<picture>
  <source media="(min-width: 650px)" srcset="img_food.jpg">
  <source media="(min-width: 465px)" srcset="img_car.jpg">
  <img src="img_girl.jpg" style="width:auto;">
</picture>

lists

Can't always remember of dl (description list) with dt (term) and a dd (description), so now it's somewhere on this blog.

Also, it's good to now that there's a type attribute for ordered list (ol) to specify the type of the list item marker:

  • type="1" for number marker (default)
  • type="A" for uppercase letter marker
  • type="a" for lowercase letter marker
  • type="I" for uppercase roman number marker
  • type="i" for lowercase roman number marker

As well as a start attribute to chose from which number to start.

iframe

iframe stand for inline frame. It is used to embed another document in current document (just like a Youtube video for instance). Don't forget title attribute for screen readers. Default display will add borders so make sure you remove them with CSS or style attribute.

An iframe can be the target of a link, just refer to it with it's name: (example from W3Schools):

<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe Example"></iframe>
<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>

noscript

Don't forget to let the user know JavaScript is needed for this or this functionnality with noscript tag:

<noscript>Sorry but the game relies on JavaScript. Have a look at your browser's settings if you wish to play it.</noscript>

list of semantic elements and definition

From W3Schools.

  • article -> defines an independent, self-contained content
  • details -> defines additional details that the user can open and close on demand
  • summary -> defines a heading for the details element
  • figcaption -> defines a caption for a <figure> element. The <figcaption> element can be placed as the first or as the last child of a <figure> element.
  • figure -> defines self-contained content, like illustrations, diagrams, photos, code listings, etc.
  • img -> defines the actual image/illustration
  • mark -> defines marked/highlighted text
  • time -> defines a date/time

Landmarks

Landmarks define some parts of the page to jump to with the help of a screen reader #accessibility

  • header -> defines a header for a document or a section
  • nav -> defines a set of navigation links
  • main -> defines the main content of a document. Should be unique.
  • aside -> defines content aside from the content (like a sidebar)
  • section -> defines a section in a document
  • footer -> defines a footer for a document or a section

A section can include article and an article section, depends of the content.

A header can be found in several zones in an HTML document except in a footer, address or header element.

A footer is also repeatable in the HTML document.

Note that a button element should be used for any interaction that performs an action on the current page. The a element should be used for any interaction that navigates to another view.

kbd

kbd stands for keyboard inuput. Default browser's display is monospace font.

Use lowercase for file names

Some web servers (Apache, Unix) are case sensitive about file names: "london.jpg" cannot be accessed as "London.jpg".

Other web servers (Microsoft, IIS) are not case sensitive: "london.jpg" can be accessed as "London.jpg".

time

Nesting time or duration information into a time element is useful for any automatic reading of a page, from a search engine for instance.

I'll be celebrating my birthday on <time datetime="2024-09-21T20:00">September 21<sup>st</sup></time> for <time datetime="PT2H30M">2h30m</time>.