AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-1238244

lharby's questions

Martin Hope
lharby
Asked: 2025-03-30 19:17:47 +0800 CST

Use opentypejs para percorrer todos os glifos em uma fonte e exibi-los na página

  • 5

TL/DR: Como exibir cada glifo de um arquivo de fonte usando algum método de análise que mostre todos os caracteres.

Estou tentando criar um visualizador de glifos para uma das diversas fontes que desejo mostrar em uma página.

Atualmente tenho este codesandbox (ele é apertado, então há uma versão de página inteira aqui )

Aqui está meu JS:

import opentype from "opentype.js";
const htmlElem = document.querySelector("html");

const fontPath = "/src/resources";

const fontMap = (fontName) => {
  const url = `${fontPath}/${fontName}`;
  const buffer = fetch(url).then((res) => res.arrayBuffer());

  buffer.then((data) => {
    const wrapper = htmlElem.querySelector(".characters ul");
    const font = opentype.parse(data);
    const glyphs = font.glyphs.glyphs;
    for (const [key, value] of Object.entries(glyphs)) {
      if (value.name !== null) {
        const template = `<li>${value.name}</li>`;
        wrapper.insertAdjacentHTML("beforeend", template);
        console.log(value);
      }
    }
  });
};

fontMap("Calluna-Regular.otf");

Quando registro cada glifo, obtenho muitos dados sobre o elemento, no entanto, quero saber como acessá-lo na página usando a propriedade correta.

insira a descrição da imagem aqui

Atualmente estou tentando acessar item.nameo que funciona bem para 'A', 'B', 'C' etc., mas os números são nomeados por extenso 'um', 'dois', etc. E sinais de pontuação, acho que o nome faz sentido.

Tentei adicionar um prefixo para gerar a saída como entidades HTML, como <li>&${value.name};</li>, mas é claro que isso prefixará o padrão 'A' com um '&'.

Existe uma maneira universal de analisar cada caractere e usar alguma codificação para exibir cada item na página? Hex talvez, mas não transformar os caracteres simples. A outra coisa que eu queria saber é se certos glifos têm propriedades particulares que os distinguem. Acho que a propriedade unicode é a única que posso acessar que vai me ajudar.

Também nesta fonte a letra 'A' está unicode: 64no mapeamento, mas o caractere unicode universal para 'A' é U+0041 (ou já foi convertido usando algum sistema), não sei se isso é alguma peculiaridade do arquivo da fonte.

Qualquer ajuda será muito apreciada.

javascript
  • 1 respostas
  • 29 Views
Martin Hope
lharby
Asked: 2025-01-22 20:08:27 +0800 CST

O JavaScript embaralha elementos, mas rastreia o índice original ou usa o módulo para inseri-los na marcação pai

  • 6

Tenho a seguinte marcação:

<div class="">
  <div class="tiled-gallery__gallery">
    <div class="tiled-gallery__row columns-1">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-dan/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-jessica/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=1132%2C1132&amp;strip=info&amp;ssl=1 1132w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/rebecca-2/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=1333%2C1333&amp;strip=info&amp;ssl=1 1333w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-2/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-4/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-teram-test-3/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-1/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
  </div>
</div>

Quero poder embaralhar cada item: <div class="tiled-gallery__item">em uma posição aleatória, porém o problema que tenho é que o primeiro item tem um contêiner pai que especifica 1 coluna, columns-1embora a maior parte da marcação use a classe de layout de 2 colunas columns-2.

Eu escrevi um shuffle básico usando este javascript:

const shuffleElems = () => {
  const wrapper = document.querySelector(".tiled-gallery__gallery");
  const items = wrapper.querySelectorAll(
    ".tiled-gallery__row .tiled-gallery__col"
  );

  for (var i = items.length; i >= 0; i--) {
    wrapper.appendChild(items[(Math.random() * i) | 0]);
  }
};

shuffleElems();

Isso funciona porque reorganiza os itens, mas poderia adicionar um único item em uma coluna que deveria levar dois. Então, presumo que preciso de alguma forma de rastrear o índice original e o novo, e usar um módulo ou verificar a classe pai. Ou possivelmente embaralhar tudo nas classes da coluna 2 e então apenas trocar a única linha no final?

Espero que isso faça sentido, todo o código está em codesandbox .

Adicionarei uma captura de tela em breve.

javascript
  • 1 respostas
  • 34 Views
Martin Hope
lharby
Asked: 2024-05-12 06:08:08 +0800 CST

Execute a chamada de busca dentro da função map (ou loop for)

  • 5

Estou tentando iterar sobre uma matriz de objetos e, dependendo do conteúdo de alguns desses objetos, preciso executar uma função de busca, aguardar o resultado antes de atualizar a nova matriz.

Aqui está meu js:

const allPosts = [
{
    "type": "image",
    "is_blocks_post_format": true,
    "blog_name": "jessicaharbydotcom",
    "id": 744489834793566200,
    "id_string": "744489834793566208",
    "is_blazed": false,
    "is_blaze_pending": false,
    "can_blaze": false,
    "post_url": "https://jessicaharbydotcom.tumblr.com/post/744489834793566208/shield-2018-wax-display-case-light-shield-is-a",
    "slug": "shield-2018-wax-display-case-light-shield-is-a",
    "date": "2024-03-09 16:13:54 GMT",
    "timestamp": 1710000834,
    "state": "published",
    "format": "html",
    "reblog_key": "4O3x5WWb",
    "tags": [
        "shield"
    ],
    "note_count": 0,
    "title": "",
    "body": "<div class=\"npf_row\"><figure class=\"tmblr-full\" data-orig-height=\"4032\" data-orig-width=\"2640\"><img src=\"https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s640x960/d85c9c2f7f4ff41832f548cc2cac89905e6fe01b.jpg\" data-orig-height=\"4032\" data-orig-width=\"2640\" srcset=\"https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s75x75_c1/eb876d72933b6138eeba73ca59499c3809975b61.jpg 75w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s100x200/21f86af6b60e44ba7d90090281dc1a1461494805.jpg 100w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s250x400/eba73e6b36bf95f9473e9276592794923583d9de.jpg 250w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s400x600/f202a41604edd3e6cfeee2f9457620bbc87accff.jpg 393w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s500x750/3def886512d22590bb2b72396d147cb8007ccd46.jpg 491w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s540x810/d83eb22083d9dafb4feae95e2f4a2ca0553e0ae8.jpg 530w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s640x960/d85c9c2f7f4ff41832f548cc2cac89905e6fe01b.jpg 629w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s1280x1920/1c03d83fdad14df8334745de77595cd9d2215ce7.jpg 1257w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s2048x3072/ee6e6bf1448c6304fbf6cbed93062b9ca520baf3.jpg 2011w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"/></figure></div><p>Shield<br/>2018<br/>Wax, display case, light</p><p>Shield is a meditation on masculinity and power. The tiles are wax casts of the substantial belt buckle once belonging to the artist&rsquo;s grandfather, who was a Chicago Police Sergeant investigated in the 1970s as part of a ring of police shaking down motorists for payoffs. While eventually granted immunity from prosecution by the state, he was indicted, along with two fellow policemen, for perjury by a grand jury for lying about his involvement.</p>",
    "reblog": {
        "comment": "<p><div class=\"npf_row\"><figure class=\"tmblr-full\" data-orig-height=\"4032\" data-orig-width=\"2640\"><img src=\"https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s640x960/d85c9c2f7f4ff41832f548cc2cac89905e6fe01b.jpg\" data-orig-height=\"4032\" data-orig-width=\"2640\" srcset=\"https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s75x75_c1/eb876d72933b6138eeba73ca59499c3809975b61.jpg 75w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s100x200/21f86af6b60e44ba7d90090281dc1a1461494805.jpg 100w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s250x400/eba73e6b36bf95f9473e9276592794923583d9de.jpg 250w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s400x600/f202a41604edd3e6cfeee2f9457620bbc87accff.jpg 393w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s500x750/3def886512d22590bb2b72396d147cb8007ccd46.jpg 491w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s540x810/d83eb22083d9dafb4feae95e2f4a2ca0553e0ae8.jpg 530w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s640x960/d85c9c2f7f4ff41832f548cc2cac89905e6fe01b.jpg 629w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s1280x1920/1c03d83fdad14df8334745de77595cd9d2215ce7.jpg 1257w, https://64.media.tumblr.com/49d61fefb0215ba9d4b0af70a6e5c688/2c5835b67d79732a-9a/s2048x3072/ee6e6bf1448c6304fbf6cbed93062b9ca520baf3.jpg 2011w\" sizes=\"(max-width: 1280px) 100vw, 1280px\"></figure></div><p>Shield<br>2018<br>Wax, display case, light</p><p>Shield is a meditation on masculinity and power. The tiles are wax casts of the substantial belt buckle once belonging to the artist’s grandfather, who was a Chicago Police Sergeant investigated in the 1970s as part of a ring of police shaking down motorists for payoffs. While eventually granted immunity from prosecution by the state, he was indicted, along with two fellow policemen, for perjury by a grand jury for lying about his involvement.</p></p>",
        "tree_html": ""
    },
    "can_reply": false,
    "display_avatar": true
},
    {
    "type": "video video-embed",
    "is_blocks_post_format": true,
    "blog_name": "jessicaharbydotcom",
    "id": 744485994035904500,
    "id_string": "744485994035904513",
    "is_blazed": false,
    "is_blaze_pending": false,
    "can_blaze": false,
    "post_url": "https://jessicaharbydotcom.tumblr.com/post/744485994035904513/referendum-ask-me-how-do-i-feel",
    "slug": "referendum-ask-me-how-do-i-feel",
    "date": "2024-03-09 15:12:51 GMT",
    "timestamp": 1709997171,
    "state": "published",
    "format": "html",
    "reblog_key": "qL2EmJnA",
    "tags": [
        "referendum"
    ],
    "short_url": "https://tmblr.co/ZXen9PfKyX4kmu01",
    "summary": "Referendum (Ask Me How Do I Feel)",
    "should_open_in_legacy": false,
    "recommended_source": null,
    "recommended_color": null,
    "note_count": 0,
    "title": "",
    "body": "<p class=\"npf_link\" data-npf='{\"type\":\"link\",\"url\":\"https://vimeo.com/181950781\",\"display_url\":\"https://vimeo.com/181950781\",\"title\":\"Referendum (Ask Me How Do I Feel)\",\"description\":\"Referendum (Ask Me How Do I Feel) uses footage from the classic film A Matter of Life and Death to create a new narrative. The film speaks d\",\"site_name\":\"Vimeo\",\"poster\":[{\"media_key\":\"ad17645e0781329536708048ee806163:9100d8a78851c197-1c\",\"type\":\"image/webp\",\"width\":1920,\"height\":1080}]}'><a href=\"https://vimeo.com/181950781\" target=\"_blank\">Referendum (Ask Me How Do I Feel)</a></p><p>Referendum (Ask Me How Do I Feel) <br/>2016<br/>Single channel video</p><p>Referendum (Ask Me How Do I Feel) uses footage from the classic film A Matter of Life and Death to create a new narrative, speaking directly to the viewer as the men onscreen debate and decide important matters, failing to provide answers to the direct questions posed. </p>",
    "reblog": {
        "comment": "<p class=\"npf_link\" data-npf='{\"type\":\"link\",\"url\":\"https://vimeo.com/181950781\",\"display_url\":\"https://vimeo.com/181950781\",\"title\":\"Referendum (Ask Me How Do I Feel)\",\"description\":\"Referendum (Ask Me How Do I Feel) uses footage from the classic film A Matter of Life and Death to create a new narrative. The film speaks d\",\"site_name\":\"Vimeo\",\"poster\":[{\"media_key\":\"ad17645e0781329536708048ee806163:9100d8a78851c197-1c\",\"type\":\"image/webp\",\"width\":1920,\"height\":1080}]}'><a href=\"https://vimeo.com/181950781\" target=\"_blank\">Referendum (Ask Me How Do I Feel)</a></p><p>Referendum (Ask Me How Do I Feel) <br>2016<br>Single channel video</p><p>Referendum (Ask Me How Do I Feel) uses footage from the classic film A Matter of Life and Death to create a new narrative, speaking directly to the viewer as the men onscreen debate and decide important matters, failing to provide answers to the direct questions posed. </p>",
        "tree_html": ""
    },
    "can_reply": false,
    "display_avatar": true
},
{
    "type": "video video-embed",
    "is_blocks_post_format": true,
    "blog_name": "jessicaharbydotcom",
    "id": 744393264438837200,
    "id_string": "744393264438837248",
    "is_blazed": false,
    "is_blaze_pending": false,
    "can_blaze": false,
    "post_url": "https://jessicaharbydotcom.tumblr.com/post/744393264438837248/affirmation-2016",
    "slug": "affirmation-2016",
    "date": "2024-03-08 14:38:57 GMT",
    "timestamp": 1709908737,
    "state": "published",
    "format": "html",
    "reblog_key": "jniGZGhJ",
    "tags": [
        "affirmation"
    ],
    "short_url": "https://tmblr.co/ZXen9PfKdRha4W00",
    "summary": "Affirmation (2016)",
    "should_open_in_legacy": false,
    "recommended_source": null,
    "recommended_color": null,
    "note_count": 0,
    "title": "",
    "body": "<p class=\"npf_link\" data-npf='{\"type\":\"link\",\"url\":\"https://vimeo.com/153949952?share=copy\",\"display_url\":\"https://vimeo.com/153949952?share=copy\",\"title\":\"Affirmation (2016)\",\"description\":\"Affirmation (2016) uses footage from the 1923 Buster Keaton film Three Ages as the basis for a guided meditation in vulnerability. Keaton wa\",\"site_name\":\"Vimeo\",\"poster\":[{\"media_key\":\"cd78c9656df6b9381417c980464efff7:86fa2ab3c65a5863-70\",\"type\":\"image/webp\",\"width\":1920,\"height\":1080}]}'><a href=\"https://vimeo.com/153949952?share=copy\" target=\"_blank\">Affirmation (2016)</a></p><p>Affirmation <br/>2016<br/>Single channel video</p><p>Affirmation uses footage from the 1923 Buster Keaton film Three Ages as the basis for a guided meditation in vulnerability. Keaton was badly injured shooting this portion of the film and chose to keep the jarring moment of impact in the finished comedy.</p>",
    "reblog": {
        "comment": "<p class=\"npf_link\" data-npf='{\"type\":\"link\",\"url\":\"https://vimeo.com/153949952?share=copy\",\"display_url\":\"https://vimeo.com/153949952?share=copy\",\"title\":\"Affirmation (2016)\",\"description\":\"Affirmation (2016) uses footage from the 1923 Buster Keaton film Three Ages as the basis for a guided meditation in vulnerability. Keaton wa\",\"site_name\":\"Vimeo\",\"poster\":[{\"media_key\":\"cd78c9656df6b9381417c980464efff7:86fa2ab3c65a5863-70\",\"type\":\"image/webp\",\"width\":1920,\"height\":1080}]}'><a href=\"https://vimeo.com/153949952?share=copy\" target=\"_blank\">Affirmation (2016)</a></p><p>Affirmation <br>2016<br>Single channel video</p><p>Affirmation uses footage from the 1923 Buster Keaton film Three Ages as the basis for a guided meditation in vulnerability. Keaton was badly injured shooting this portion of the film and chose to keep the jarring moment of impact in the finished comedy.</p>",
        "tree_html": ""
    },
    "can_reply": false,
    "display_avatar": true
},
{
    "type": "video",
    "is_blocks_post_format": true,
    "blog_name": "jessicaharbydotcom",
    "id": 744393060798136300,
    "id_string": "744393060798136320",
    "is_blazed": false,
    "is_blaze_pending": false,
    "can_blaze": false,
    "post_url": "https://jessicaharbydotcom.tumblr.com/post/744393060798136320/very-realistic-2021-single-channel-video-in-the",
    "slug": "very-realistic-2021-single-channel-video-in-the",
    "date": "2024-03-08 14:35:43 GMT",
    "timestamp": 1709908543,
    "state": "published",
    "format": "html",
    "reblog_key": "hpmXLQE1",
    "tags": [
        "very realistic"
    ],
    "short_url": "https://tmblr.co/ZXen9PfKdOjw8u00",
    "summary": "Very Realistic\n2021\nSingle channel video \nIn The Great Muppet Caper (1981), reporters Kermit, Fozzie, and Gonzo travel to London...",
    "should_open_in_legacy": false,
    "recommended_source": null,
    "recommended_color": null,
    "note_count": 0,
    "title": "",
    "body": "<figure class=\"tmblr-full tmblr-embed\" data-provider=\"vimeo\" data-url=\"https://vimeo.com/544276930?share=copy\" data-orig-width=\"540\" data-orig-height=\"304\"><iframe src=\"https://player.vimeo.com/video/544276930?title=0&amp;byline=0&amp;portrait=0&amp;app_id=122963\" width=\"540\" height=\"304\" frameborder=\"0\" allow=\"autoplay; fullscreen; picture-in-picture; clipboard-write\" title=\"Very Realistic (2021)\"></iframe></figure><p>Very Realistic<br/>2021<br/>Single channel video </p><p>In The Great Muppet Caper (1981), reporters Kermit, Fozzie, and Gonzo travel to London to investigate a jewel theft. Whilst riding in a red double-decker bus over the Thames, the following exchange takes place:</p><p>Fozzie: Wow, look at the scenery!<br/>Gonzo: It’s very realistic.</p><p>It is 2021, we have lived/are living through a collective trauma and during a car ride the landscape turned to a throbbing reality and we secretly begged to be let back inside.</p>",
    "reblog": {
        "comment": "<p><figure class=\"tmblr-full tmblr-embed\" data-provider=\"vimeo\" data-url=\"https://vimeo.com/544276930?share=copy\" data-orig-width=\"540\" data-orig-height=\"304\"><iframe src=\"https://player.vimeo.com/video/544276930?title=0&amp;byline=0&amp;portrait=0&amp;app_id=122963\" width=\"540\" height=\"304\" frameborder=\"0\" allow=\"autoplay; fullscreen; picture-in-picture; clipboard-write\" title=\"Very Realistic (2021)\"></iframe></figure><p>Very Realistic<br>2021<br>Single channel video </p><p>In The Great Muppet Caper (1981), reporters Kermit, Fozzie, and Gonzo travel to London to investigate a jewel theft. Whilst riding in a red double-decker bus over the Thames, the following exchange takes place:</p><p>Fozzie: Wow, look at the scenery!<br>Gonzo: It’s very realistic.</p><p>It is 2021, we have lived/are living through a collective trauma and during a car ride the landscape turned to a throbbing reality and we secretly begged to be let back inside.</p></p>",
        "tree_html": ""
    },
    "can_reply": false,
    "display_avatar": true
}
]
let filteredPosts = [];
const output = document.querySelector('.output');
const parser = new DOMParser();

const setPostsByType = () => {
let doc;
let videoThumbnail = '';
for (let i = 0; i < allPosts.length; i++) {
    const item = allPosts[i];
    if (item.body) {
        doc = parser.parseFromString(item.body, 'text/html');
    }
    if (item.type.includes('video')) {
        let videoID = doc.querySelector('a')?.getAttribute('href')?.split('vimeo.com/')[1] 
        ||
        doc.querySelector('[data-url]')?.getAttribute('data-url')?.split('vimeo.com/')[1];
        if (videoID && videoID.includes('?')) {
            videoID = videoID.split('?')[0];
        }
        console.log(videoID);
        fetch(`https://vimeo.com/api/v2/video/${videoID}.json`)
            .then((response) => {
                return response.text();
            })
            .then((data) => {
                const { thumbnail_large } = JSON.parse(data)[0];
                videoThumbnail = thumbnail_large + '.jpg';
                console.log(videoThumbnail);
                return videoThumbnail; // this is asynchronous so being returned after the rest of my function is processed
            })
            .catch((error) => {
                console.log(error);
            });
    }
    const postObject = {
        id: item.id,
        post_id: `postid__${item.id}`,
        body: item.body,
        video_thumbnail_id: videoThumbnail, // this is always empty due to the fetch being asynchronous
        type: item.type,
        tags: item.tags,
        date: item.date
    }
    filteredPosts.push(postObject);
}
};

setPostsByType();
output.textContent = JSON.stringify(filteredPosts, null, 4);
<pre class="output"></pre>

Desculpe, há muitos dados, este já é um conjunto filtrado. Há também um JSFIDDLE aqui: https://jsfiddle.net/lharby/wrLpheok/ que contém um conjunto maior de dados.

Eu sei que o problema é que a busca é assíncrona e que os mapas for loops são executados de acordo com a ordem do evento. O conteúdo id'sde cada postagem de vídeo é registrado no console, mas depois que o filteredPostsarray é enviado.

Aqui está o que eu tentei:

  • Envolvendo tudo dentro de uma função assíncrona.
  • Crie uma função que deve retornar o postObject e executá-lo dentro da fetch .then()função (mas é claro que isso está envolvido em uma instrução if, portanto, filtra os itens no array com base no tipo de postagem)
  • Use um mapa em vez de um loop for.

Tenho visto mais perguntas sobre SO em que os usuários desejam chamar primeiro um endpoint da API de busca e depois mapear itens, mas meu problema é o contrário, só posso chamar a função de busca depois de iterar em cada corpo da postagem e ela tiver atendido minha condição.

Qualquer ajuda será muito apreciada.

javascript
  • 1 respostas
  • 61 Views
Martin Hope
lharby
Asked: 2024-04-07 20:45:17 +0800 CST

Permitir arrastar itens abaixo da altura da janela. JavaScript baunilha

  • 5

Estou tentando construir um site para meu cliente, que não seja diferente do Miro (ou de outros aplicativos de quadro branco).

O conceito é que os elementos individuais são dispostos usando posicionamento absoluto, mas o administrador pode arrastá-los na janela de visualização e definir propriedades de largura e altura para cada elemento.

Não consigo fazer funcionar nenhum método que permita arrastar abaixo da altura original da janela (mesmo que todo o documento tenha elementos com alturas definidas maiores que a altura da janela).

Eu tentei 3 métodos:

  1. Defina alguma propriedade de altura grande no wrapper. https://jsfiddle.net/lharby/afjwsm75/

const draggingClass = 'dragging';

class draggable {
    constructor(element, node = [ document ] ) {
        this.node = node;
        this.el = element;

        if ( this.el ) {
            this.mouseDown = this.mouseDown.bind(this);
            this.mouseUp = this.mouseUp.bind(this);
            this.mouseMove = this.mouseMove.bind(this);
        }
    }

    setHandle( handle ) {
        this.handle = handle;
        return this;
    }

    setCallback( callback ) {
        this.callback = callback;
        return this;
    }

    mouseDown( event ) {
        if ( this.callback?.start ) this.callback.start( event, this.el )
        else this.el.classList.add(draggingClass)        
        for ( const node of this.node ) {
            node.addEventListener('mouseup', this.mouseUp);
            node.addEventListener('mousemove', this.mouseMove);
            node.addEventListener('mouseleave', this.mouseUp);
        }
        this.el.addEventListener('mouseleave', this.mouseUp);
    }

    mouseUp( event ) {
        if ( this.callback?.end ) this.callback.end( event, this.el )
        else this.el.classList.remove(draggingClass)
        for ( const node of this.node ) {
            node.removeEventListener('mouseup', this.mouseUp);
            node.removeEventListener('mousemove', this.mouseMove);
            node.removeEventListener('mouseleave', this.mouseUp);
        }
        this.el.removeEventListener('mouseleave', this.mouseUp);
    }

    mouseMove(event) {
        if ( this.callback?.move ) {
            this.callback.move( event, this.el );
        } else {
            const style = window.getComputedStyle(this.el);
            const x = (parseFloat(style.getPropertyValue('left')) || 0) + event.movementX;
            const y = (parseFloat(style.getPropertyValue('top')) || 0) + event.movementY;
            const rect = this.el.getBoundingClientRect();
            const viewHeight = window.innerHeight || document.documentElement.clientHeight;
            const viewWidth = window.innerWidth || document.documentElement.clientWidth;
            const maxX = viewWidth - rect.width;
            const maxY = viewHeight - rect.height;
            const constrainedX = Math.max(0, Math.min(x, maxX));
            const constrainedY = Math.max(0, Math.min(y, maxY));
            this.el.style.position = 'absolute';
            this.el.style.top = constrainedY + 'px';
            this.el.style.left = constrainedX + 'px';
        }
    }

    run() {
        const handle = this.handle ?? this.el
        handle.addEventListener('mousedown', this.mouseDown)
    }

    stop() {
        const handle = this.handle ?? this.el
        handle.removeEventListener('mousedown', this.mouseDown)
    }
}

const boxes = document.querySelectorAll('.box');
const movable1 = new draggable(boxes[0]);
const movable2 = new draggable(boxes[1]);
movable1.run();
movable2.run();
body {
    font-family: monospace;
}

.wrapper {
    min-height: 400vh;
    background-color: rgb(255 0 0 / 10%);
    top: 10px;
    right: 10px;
    bottom: 10px;
    left: 10px;
    overflow-y: scroll;
}

.box {
    position: absolute;
    padding: 10px;
    resize: both;
    height: 150px;
    width: 150px;
    margin-bottom: 20px;
    background: #f0f0f0;
    border: 2px solid #555;
    overflow: auto;
    background-image: linear-gradient(-45deg, #ccc 10px, transparent 10px);
}

.second {
    top: 50px;
    left: 50px;
}

.third {
    top: 100px;
    left: 100px;
}

.heading {
    background: red;
    padding: 5px 10px;
}

.dragging {
    opacity: 0.9;
    border: 2px dashed #8181b9;
    user-select: none;
    z-index: 2;
    cursor: move;
}

.actions {
    display: flex;
    flex-direction: column;
    position: absolute;
    right: 0;
    z-index: 1;
}
<div class="outer">
    <div class="wrapper">
        <div class="box">
            I am box 1
        </div>
        <div class="box second">
            I am box 2
        </div>

        <div class="box second third dragging">
            I am box 3
        </div>
    </div>
</div>

  1. Defina o html para uma posição fixa sem rolagem e coloque caixas dentro de um div que permita a rolagem com uma altura grande. https://jsfiddle.net/lharby/25oqth67/

HTML é igual ao anterior, mas usando este CSS

html.no-scroll {
    overflow-y: hidden;
}

.outer {
    position: fixed;
    top: 0;
    bottom: 0;
    width: 100%;
}

.wrapper {
    height: 100%;
    background-color: rgb(255 0 0 / 10%);
    top: 10px;
    right: 10px;
    bottom: 10px;
    left: 10px;
    overflow-y: scroll;
}

.box {
    position: relative; // I also added a JS toggle to switch position from relative to absolute
    ...
}
  1. Tente definir dinamicamente a altura do documento ou a altura da janela. https://jsfiddle.net/lharby/e8fb6537/

HTML e CSS semelhantes aos exemplos anteriores, mas aqui estão alguns JS

let vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);

const trigger = document.querySelector('.actions button');
trigger.addEventListener('click', () => {
    let root = document.querySelector(':root');
    let docHeight = document.documentElement.clientHeight;
    let winHeight = window.innerHeight;
    docHeight = 1200; // also tried `${1200}px`
    winHeight = 1300; // also tried `${1300}px`
    root.style.height = `${1400}px`;
    console.log(docHeight, winHeight, root.style.height);
    console.log(vh);
});

Também tentei adicionar um elemento abaixo do wrapper arrastável. Além de definir propriedades de altura no HTML e no corpo. Parece que nada permitirá ao usuário arrastar as caixas abaixo da altura original da janela. A menos que esteja faltando alguma correção fácil de CSS.

Os JSFiddles contêm todas as outras funcionalidades (caixas de arrastar) que funcionam como estão, mas adicionei um trecho de código ao primeiro exemplo, que seria o mais fácil de descobrir, pois presumo que possa ser CSS puro.

Curiosamente, se você pesquisar este tópico no Google, parece haver uma abundância de respostas sobre como limitar o arrasto para dentro de um contêiner específico.

Prefiro evitar uma biblioteca, se possível.

https://www.google.com/search?q=javascript+drag+item+beyond+window+height+site%3Astackoverflow.com

Qualquer ajuda muito apreciada.

javascript
  • 1 respostas
  • 18 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve