Category: code

  • Svelte Test

    Svelte Test

    Is it possible to add a Svelte app into the WordPress website? Let’s try.

    I will use the default example from the docs:

    npm create vite@latest my-basic-app -- --template svelte

    Next i’ll upload the code that has been built in the dist folder after running:

    npm run build

    I will add the html block that it requires:

    <div id="app"></div>

    Wait! I’m gonna have to do some boiler plate code, create a child theme and upload the files that way. Meh!

    I create a new directory and a css file to register the child theme /themes/twenty-twenty-five-child

    style.css
    /*
     Theme Name:   Some Very New Theme
     Template:     twenty-twenty-five
    */

    then add an js/index.js

    console.log("Custom JS loaded on the About page.");

    These files need to be registered for the page to pick. To do this add functions.php with the code below. In order to prevent the js being loaded in every page i’ve added an if statement (the-post-name bit) which i ‘ll know after the page is created

    <?php
    // Enqueue parent and child styles
    function svn_child_enqueue_styles() {
        wp_enqueue_style(
            'parent-style',
            get_template_directory_uri() . '/style.css'
        );
    }
    add_action('wp_enqueue_scripts', 'svn_child_enqueue_styles');
    
    // Enqueue your custom JS only on a specific page (e.g., 'about')
    function svn_child_enqueue_scripts() {
      //  if (is_single('the-post-name')) {
            wp_enqueue_script(
                'custom-js',
                get_stylesheet_directory_uri() . '/js/index.js',
                array(),
                null,
                true // Load in footer
            );
     //   }
    }
    add_action('wp_enqueue_scripts', 'svn_child_enqueue_scripts');
    

    Now i upload this directory with all the files and can see in appearance/themes a new child theme is there. Once activated i reload the page and can indeed see `Custom JS loaded on the About page.` printed out in the browser console.

    Progress!

    Lets go back to the /dist folder from svelte

    we can see the index we want has other characters in. I’m going to just copy and paste the content into my index.js for now and i should expect that to work.

    The page got published and when i view other pages some errors are showing in the console. This is down to the index.js expecting there to be a div with the id=”app”. I’ll tidy up that if statement from earlier as i now know the post is called ‘svelte-test’ and update the functions.php

    ...
    function svn_child_enqueue_scripts() {
        if (is_single('svelte-test')) {
            wp_enqueue_script(
    ...

    Now the index only runs for this page.

    Ok so here is the basic svelt app embedded this this wordpress post:



    The way to know its working is the counter increments correctly.

    Conclusion

    It is indeed possible to embed a Svelte app within WordPress.

    The process to do this is a little cumbersome in that i had to create a theme template, add some code to tell the page only to display on this post.

    If i ever want to update this then there is some copying and pasting required. The next step would be to automate this and directly using ftp or something.

    I did this as proof of concept as i would like to add a bigger piece of functionality into a different page.

    Maybe another approach would be an iframe and do some kind of apache http routing for a specific route to the files instead of embedding it as part of a WordPress page. Another triage for another time.

    Thanks for reading.

  • The Sierpinski triangle in HTML and Typescript

    The Sierpinski triangle in HTML and Typescript

    I saw some video on one of the socials about this so thought i would give it a go.

    The Sierpinski Triangle is named after Wacław Franciszek Sierpiński (1882 – 1969) and consists of fractal equilateral triangles.

    full-fractal

    Essentially how it works is that you select a point anywhere in a triangle. Draw a line from that point to any of the corners. Then mark the middle of that line with a dot. From that dot go to any corner again, draw a line and mark the middle with a dot. Keep repeating.

    To picture this look at the diagram, starting and point 1. This could be anywhere in the triangle and draw a line to any corner. 2 is the middle point where that then goes to any corner. The middle point of that is number 3.

    Continue to repeat this and see the magic:

    A simple html canvas will be created and some typescript for the logic.

    The main page is a simple html page with a canvas on it

    index.html

    1. Create the HTML canvas

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>TypeScript App</title>
      <script defer src="index.js"></script>
    </head>
    <body>
    <canvas id="canvas" width="1000" height="1000"></canvas>
    </body>
    </html>

    2. Draw an equilateral triangle on to the canvas.

    const canvas = document.getElementById("canvas") as HTMLCanvasElement;
    const ctx = canvas.getContext("2d")!;
    
    type Point = { x: number; y: number };
    type Triangle = [Point, Point, Point];
    
    const sideLength = 1000;
    const height = (Math.sqrt(3) / 2) * sideLength;
    const centerX = 500;
    const centerY = 650;
    const debug = false;
    
    const triangle: Triangle = [
      {x: centerX - sideLength / 2, y: centerY + height / 3}, //bottom left
      {x: centerX + sideLength / 2, y: centerY + height / 3}, //bottom right
      {x: centerX, y: centerY - (2 * height) / 3} // center top
    ];
    
    // Function to draw the triangle
    function drawTriangle() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.beginPath();
      ctx.moveTo(triangle[0].x, triangle[0].y);
      ctx.lineTo(triangle[1].x, triangle[1].y);
      ctx.lineTo(triangle[2].x, triangle[2].y);
      ctx.closePath();
      ctx.fillStyle = "lightblue";
      ctx.fill();
      ctx.stroke();
    }
    
    drawTriangle();

    This will draw a simple equilateral triangle

    Note the triangle array index:

    0 – bottom left

    1 – bottom right

    2 – top center

    Notice the centerX and centerY are used as offsets to position the triangle.

    3. Start and mark the points

    We start with setting a random point within the triangle 250,250

    The choose a corner at random which is any of the triangle array elements. Calculate the length to that corner and get the middle coordinate.

    Draw a dot at the middle point.

    let randomPoint = {x: 250, y: 250};
    function drawSierpinskiTriangle(x: number, y: number) {
      randomPoint = getMidpointToRandomCorner(x, y);
      drawDot(randomPoint.x, randomPoint.y);
    }
    
    function getMidpointToRandomCorner(px: number, py: number) {
      const vertex = triangle[getRandomNumber(3) - 1];
      return getMidpoint(px, py, vertex.x, vertex.y);
    }
    
    function getRandomNumber(x: number): number {
      return Math.floor(Math.random() * x) + 1;
    }
    
    function getMidpoint(x1: number, y1: number, x2: number, y2: number) {
      return {x: (x1 + x2) / 2, y: (y1 + y2) / 2};
    }
    
    function drawDot(x: number, y: number) {
      ctx.beginPath();
      ctx.arc(x, y, 1, 0, Math.PI * 2);
      ctx.fillStyle = "black";
      ctx.fill();
    }
    
    drawSierpinskiTriangle(randomPoint.x, randomPoint.y)

    Use this middle point and loop around

    for (let i = 0; i < 25000; i++) {
      setTimeout( () => drawSierpinskiTriangle(randomPoint.x, randomPoint.y), 500);
    }

    add a timeout so that you can see the the pattern emerging.

    Demo

    See this in action and test out some iterations and see how many times it loops before the pattern emerges.