8,037 Matching Annotations
  1. Aug 2023
    1. ```js function createPromiseWithData() { let resolveFn;

      const promise = new Promise((resolve, reject) => { resolveFn = resolve; });

      return { promise, resolveFn }; }

      // Usage const { promise, resolveFn } = createPromiseWithData();

      // Later, when you have the data you want to pass const data = 'Future data';

      // Resolve the promise with the data resolveFn(data);

      // Use the promise promise.then((result) => { console.log('Promise resolved with:', result); }); ```

    1. Add aliases to vite.config.ts

      ```js import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path';

      // https://vitejs.dev/config/ export default defineConfig({ resolve: { alias: { '@': path.resolve(__dirname, './src'), '@assets': path.resolve(__dirname, './src/assets'), '@components': path.resolve(__dirname, './src/components'), }, }, plugins: [react()] }) ```

      Add aliases to tsconfig.json

      ```js { "compilerOptions": { // ... your other compiler options "baseUrl": ".", "paths": { "@/": ["src/"], "@components/": ["src/components/"], "@assets/": ["src/assets/"] }, }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ````

      Use alias

      js import image from `@assets/image.png`

    1. ```js / * .env.development VITE_API_URL=http://localhost:1337/api/blog-posts /

      / * .env.production VITE_API_URL=https://APP.herokuapp.com/api/blog-posts /

      import { error, type Load } from '@sveltejs/kit';

      import { VITE_API_URL } from '$env/static/private';

      export const load: Load = async () => { const res = await fetch(VITE_API_URL); const { data } = await res.json();

      if (res.ok) return { blogs: data }; throw error(404, 'Unable to fetch blogs'); }; ```

    1. A spec to optimize ad targeting (respectful of privacy, they say... 😂🤣).

      Fuck you Google with your dystopian API:

      ```js // document.browsingTopics() returns an array of BrowsingTopic objects. const topics = await document.browsingTopics();

      // Get data for an ad creative. const response = await fetch('https://ads.example/get-creative', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(topics) });

      // Get the JSON from the response. const creative = await response.json();

      // Display the ad. (or not) ```

    1. On-device ad auctions to serve remarketing and custom audiences, without cross-site third-party tracking.

      Naming a thing with a meaning opposite to what the named thing is...

      Google is insatiable when it regards to accessing users private data. Let's block that bullshit.

    1. SvelteKit will automatically await the fetchPost call before it starts rendering the page, since it’s at the top level. However, it won’t wait for the nested fetchComments call to complete – the page will render and data.streamed.comments will be a promise that will resolve as the request completes. We can show a loading state in the corresponding +page.svelte using Svelte’s await block:

      js export const load: PageServerLoad = () => { return { post: fetchPost(), streamed: { comments: fetchComments() } }; }; ```svelte

      <script lang="ts"> import type { PageData } from './$types'; export let data: PageData; </script> <article> {data.post} </article>

      {#await data.streamed.comments} Loading... {:then value} <br />

        {#each value as comment}
      1. {comment}
      2. {/each}

      {/await} ```

    1. ```js // CSRF

      /* @type {import('@sveltejs/kit').Config} / const config = { kit: { checkOrigin?: true, } };   export default config; ```

    2. ```js // CSP svelte.config.js

      /* @type {import('@sveltejs/kit').Config} / const config = { kit: { csp: { directives: { 'script-src': ['self'] }, reportOnly: { 'script-src': ['self'] } } } };

      export default config; ```

    1. ```js // Create a portal with the wikipedia page, and embed it // (like an iframe). You can also use the <portal> tag instead. portal = document.createElement('portal'); portal.src = 'https://en.wikipedia.org/wiki/World_Wide_Web'; portal.style = '...'; document.body.appendChild(portal);

      // When the user touches the preview (embedded portal): // do fancy animation, e.g. expand … // and finish by doing the actual transition. // For the sake of simplicity, this snippet will navigate // on the onload event of the Portals element. portal.addEventListener('load', (evt) => { portal.activate(); });

      // Adding some styles with transitions const style = document.createElement('style'); style.innerHTML = portal { position:fixed; width: 100%; height: 100%; opacity: 0; box-shadow: 0 0 20px 10px #999; transform: scale(0.4); transform-origin: bottom left; bottom: 20px; left: 20px; animation-name: fade-in; animation-duration: 1s; animation-delay: 2s; animation-fill-mode: forwards; } .portal-transition { transition: transform 0.4s; } @media (prefers-reduced-motion: reduce) { .portal-transition { transition: transform 0.001s; } } .portal-reveal { transform: scale(1.0) translateX(-20px) translateY(20px); } @keyframes fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }; const portal = document.createElement('portal'); // Let's navigate into the WICG Portals spec page portal.src = 'https://wicg.github.io/portals/'; // Add a class that defines the transition. Consider using // prefers-reduced-motion media query to control the animation. // https://developers.google.com/web/updates/2019/03/prefers-reduced-motion portal.classList.add('portal-transition'); portal.addEventListener('click', (evt) => { // Animate the portal once user interacts portal.classList.add('portal-reveal'); }); portal.addEventListener('transitionend', (evt) => { if (evt.propertyName == 'transform') { // Activate the portal once the transition has completed portal.activate(); } }); document.body.append(style, portal); ```

      ```js // Feature detection

      if ('HTMLPortalElement' in window) { // If this is a platform that have Portals... const portal = document.createElement('portal'); ... } ```

      js // Detect whether this page is hosted in a portal if (window.portalHost) { // Customize the UI when being embedded as a portal }

      ```js // Send message to the portal element const portal = document.querySelector('portal'); portal.postMessage({someKey: someValue}, ORIGIN);

      // Receive message via window.portalHost window.portalHost.addEventListener('message', (evt) => { const data = evt.data.someKey; // handle the event }); ```

    1. ```html

      <style> kbd { background-color: #eee; border-radius: 3px; border: 1px solid #b4b4b4; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 2px 0 0 rgba(255, 255, 255, 0.7) inset; color: #333; display: inline-block; font-size: 0.85em; font-weight: 700; line-height: 1; padding: 2px 4px; white-space: nowrap; } </style>

      Please press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> to re-render an MDN page.

      ```

    1. ```html

      <title>HTML Standard</title>

      <body> <hgroup id="document-title">

      HTML: Living Standard

      Last Updated 12 July 2022

      </hgroup>

      Some intro to the document.

      Table of contents

      First section

      Some intro to the first section.

      </body>

      ```

    1. ```html

      <header>

      Movie website

      <search> <form action="./search/"> <label for="movie">Find a Movie</label> <input type="search" id="movie" name="q" /> <button type="submit">Search</button> </form> </search> </header>

      ```

      ```html <search> <label> Find and filter your query <input type="search" id="query" /> </label> <label> <input type="checkbox" id="exact-only" /> Exact matches only </label>

      <section>

      Results:

      <output id="no-results"> </output> </section>

      </search> ```

    1. ```toml type = "webpack" webpack_config = "webpack.config.js"

      these will be used in production

      vars = { WORKER_ENV = "production", SENTRY_ENABLED = true }

      [env.local]

      these will be used only when --env=local

      vars = { WORKER_ENV = "local", SENTRY_ENABLED = false } ```

      wrangler dev --env=local

    1. ```js // Auth Worker

      export default { async fetch(request, env) { // Read x-custom-token header and make sure it matches SECRET_TOKEN if (request.headers.get('x-custom-token') === env.SECRET_TOKEN) { return new Response('Request allowed', { status: 200 }); } else { return new Response('x-custom-token does not match, request not allowed', { status: 403 }); } }, }; ```

      ```js // Gateway Worker

      export default { async fetch(request, env) { // Fetch AUTH service and pass request const authResponse = await env.auth.fetch(request.clone());

      // Return response from the AUTH service if the response status is not 200
      // It would return 403 'x-custom-token does not match, request not allowed' response in such case
      if (authResponse.status !== 200) {
        return authResponse;
      }
      
      // Request allowed
      // You can write application logic here
      // In this case we delegate the logic to an `application` Worker
      return await env.application.fetch(request)
      

      }, }; ```

    1. ```html

      <body style="visibility: hidden;"> <script>0</script> </body> <noscript> <style>body { visibility: visible; }</style> </noscript>

      ```

  2. Jul 2023
    1. html <meta http-equiv="Accept-CH" content="DPR, Viewport-Width, Width"> ... <picture> <!-- serve WebP to Chrome and Opera --> <source media="(min-width: 50em)" sizes="50vw" srcset="/image/thing-200.webp 200w, /image/thing-400.webp 400w, /image/thing-800.webp 800w, /image/thing-1200.webp 1200w, /image/thing-1600.webp 1600w, /image/thing-2000.webp 2000w" type="image/webp"> <source sizes="(min-width: 30em) 100vw" srcset="/image/thing-crop-200.webp 200w, /image/thing-crop-400.webp 400w, /image/thing-crop-800.webp 800w, /image/thing-crop-1200.webp 1200w, /image/thing-crop-1600.webp 1600w, /image/thing-crop-2000.webp 2000w" type="image/webp"> <!-- serve JPEGXR to Edge --> <source media="(min-width: 50em)" sizes="50vw" srcset="/image/thing-200.jpgxr 200w, /image/thing-400.jpgxr 400w, /image/thing-800.jpgxr 800w, /image/thing-1200.jpgxr 1200w, /image/thing-1600.jpgxr 1600w, /image/thing-2000.jpgxr 2000w" type="image/vnd.ms-photo"> <source sizes="(min-width: 30em) 100vw" srcset="/image/thing-crop-200.jpgxr 200w, /image/thing-crop-400.jpgxr 400w, /image/thing-crop-800.jpgxr 800w, /image/thing-crop-1200.jpgxr 1200w, /image/thing-crop-1600.jpgxr 1600w, /image/thing-crop-2000.jpgxr 2000w" type="image/vnd.ms-photo"> <!-- serve JPEG to others --> <source media="(min-width: 50em)" sizes="50vw" srcset="/image/thing-200.jpg 200w, /image/thing-400.jpg 400w, /image/thing-800.jpg 800w, /image/thing-1200.jpg 1200w, /image/thing-1600.jpg 1600w, /image/thing-2000.jpg 2000w"> <source sizes="(min-width: 30em) 100vw" srcset="/image/thing-crop-200.jpg 200w, /image/thing-crop-400.jpg 400w, /image/thing-crop-800.jpg 800w, /image/thing-crop-1200.jpg 1200w, /image/thing-crop-1600.jpg 1600w, /image/thing-crop-2000.jpg 2000w"> <!-- fallback for browsers that don't support picture --> <img src="/image/thing.jpg" width="50%"> </picture>

    1. ```js // Log the full user-agent data navigator .userAgentData.getHighEntropyValues( ["architecture", "model", "bitness", "platformVersion", "fullVersionList"]) .then(ua => { console.log(ua) });

      // output { "architecture":"x86", "bitness":"64", "brands":[ { "brand":" Not A;Brand", "version":"99" }, { "brand":"Chromium", "version":"98" }, { "brand":"Google Chrome", "version":"98" } ], "fullVersionList":[ { "brand":" Not A;Brand", "version":"99.0.0.0" }, { "brand":"Chromium", "version":"98.0.4738.0" }, { "brand":"Google Chrome", "version":"98.0.4738.0" } ], "mobile":false, "model":"", "platformVersion":"12.0.1" } ```

    1. ```idl dictionary NavigatorUABrandVersion { DOMString brand; DOMString version; };

      dictionary UADataValues { DOMString architecture; DOMString bitness; sequence<NavigatorUABrandVersion> brands; DOMString formFactor; sequence<NavigatorUABrandVersion> fullVersionList; DOMString model; boolean mobile; DOMString platform; DOMString platformVersion; DOMString uaFullVersion; // deprecated in favor of fullVersionList boolean wow64; };

      dictionary UALowEntropyJSON { sequence<NavigatorUABrandVersion> brands; boolean mobile; DOMString platform; };

      [Exposed=(Window,Worker)] interface NavigatorUAData { readonly attribute FrozenArray<NavigatorUABrandVersion> brands; readonly attribute boolean mobile; readonly attribute DOMString platform; Promise<UADataValues> getHighEntropyValues (sequence<DOMString> hints ); UALowEntropyJSON toJSON (); };

      interface mixin NavigatorUA { [SecureContext] readonly attribute NavigatorUAData userAgentData ; };

      Navigator includes NavigatorUA; WorkerNavigator includes NavigatorUA; ```