Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ASSETS-88897 - Polaris search API to Display latest 10 Assets Published #62

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions blocks/adp-campaign-assets/adp-campaign-assets.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
.section.adp-collection-header-left-container {
padding-right: 0;
}

.adp-collection-header {
display: flex;
height: 124px;
}

.adp-collection-header-left {
display: flex;
gap: 15px;
align-items: center;
width: 100%;
font-size: var(--header-font-size);
padding: 0;
top: 0.01rem;
padding-top: 0.88rem;
padding-bottom: 0.88rem;
z-index: 1;
}

.adp-collection-header-right {
margin-left: auto; /* This will push the element to the far right */
display: flex;
gap: 15px;
align-items: center;
font-size: var(--header-font-size);
padding: 0;
top: 0.01rem;
padding-top: 0.88rem;
padding-bottom: 0.88rem;
z-index: 1;
}


.adp-collection-header-left .adp-collection-title {
margin-bottom: 12px; /* Keeps space between title and items */
}

.adp-collection-subinfo {
display: flex;
/* justify-content: space-between; /* Aligns items to the left and select all to the right */
align-items: center; /* Centers items vertically */
}

.adp-collection-stats {
border: #E6E6E6 1px solid;
border-radius: 6px;
font: 11px/14px var(--body-font-family);
padding: 6px 10px;
flex-shrink: 0;
margin-right: 20px; /* Adjust the 20px to whatever fixed space you want between the items and the checkbox */
}

.adp-collection-select-all {
display: flex;
align-items: center; /* This will vertically align the checkbox and label */
}

.adp-collection-select-all input[type="checkbox"] {
margin-right: 5px; /* Adds some space between the checkbox and the label */
}


.adp-collection-header-left .back-button .icon {
height: 10px;
width: 18px;
vertical-align: text-bottom;
}

.adp-collection-header-collection-info {
display: flex;
flex-direction: column; /* Stack the title and sub-info vertically */
}

.adp-collection-header .adp-collection-title {
font: var(--collection-heading-font);
width: 100%;
}

.adp-collection-header .actions .adp-action {
text-wrap: nowrap;
align-items: center;
}

.adp-collection-header .actions {
/* vertically align center */
display: flex;
align-items: center;
justify-content: center;
}

.toast {
display: flex;
align-items: center;
background-color: #5258E4; /* Site used blue background */
color: white; /* White text color */
padding: 12px 24px; /* Padding inside the toast */
position: fixed; /* Positioning relative to the viewport */
z-index: 1; /* Make sure it is above other items */
bottom: 30px; /* Distance from the bottom */
left: 50%; /* Center the toast */
transform: translateX(-50%); /* Center the toast horizontally */
border-radius: 4px; /* Rounded corners */
box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.2); /* Shadow for 3D effect */
font-family: var(--body-font-family); /* Use site default font */
font-size: 0.9rem; /* Font size */
visibility: hidden; /* Hidden by default */
opacity: 0; /* Fully transparent */
transition: visibility 0s, opacity 0.5s linear; /* Transition for the toast */
}

.toast.show {
visibility: visible; /* Make the toast visible */
opacity: 1; /* Fully opaque */
}

.toast-icon {
margin-right: 12px; /* Space between icon and message */
font-size: 1.2rem; /* Icon size */
}

.toast-close {
margin-left: auto; /* Push the close button to the right */
background: none; /* No background */
border: none; /* No border */
color: white; /* White text color */
padding: 0; /* No padding */
cursor: pointer; /* Pointer cursor on hover */
font-size: 1.2rem; /* Size of the close button */
}

.toast-close:focus {
outline: none; /* Remove focus outline */
}
240 changes: 240 additions & 0 deletions blocks/adp-campaign-assets/adp-campaign-assets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
import { getBearerToken } from '../../scripts/security.js';
import {
getOptimizedPreviewUrl,
getSearchIndex,
getAssetHandlerApiKey,
getDeliveryEnvironment,
getBackendApiKey,
} from '../../scripts/polaris.js';

import {
isVideo, getFailedPlaceholderImgSrc, getFileType, getFileTypeCSSClass,
} from '../../scripts/filetypes.js';

import { logError } from '../../scripts/scripts.js';

import { decorateIcons, toCamelCase, toClassName } from '../../scripts/lib-franklin.js';

import { getCSSVar } from '../../scripts/shared.js';



/**
* Constructs and returns the base URL for search collections.
*
* @returns {string} The search collections URL.
*/
export function getSearchCollectionsUrl() {
return `${getDeliveryEnvironment()}/adobe/assets/search`;
}

async function getRequestHeadersSearchAssets() {
const token = await getBearerToken();
return {
'Content-Type': 'application/json',
'x-api-key': getBackendApiKey(),
Authorization: token,
'x-adobe-accept-experimental': '1',
'x-adp-request': 'search',
};
}

/**
* Get Latest Campaign Assets with optional limit parameter.
* @param {String} - The campaignName.
* @param {number} - The number of assets to retrieve.
* @returns {Promise<object>} A promise that resolves with a list of collections.
* @throws {Error} If an HTTP error or network error occurs.
*/

export async function getLatestCampaignAssets(campaignName, limit = 10) {
// Construct the query parameters
const queryParams = new URLSearchParams();

const indexName = getSearchIndex();

if (limit) {
queryParams.append('limit', limit);
}

if (campaignName) {
queryParams.append('campaignName', campaignName);
}

const data = {
requests: [
{
indexName: indexName,
params: {
"facetFilters": [
campaignName
],
highlightPostTag: '__/ais-highlight__',
highlightPreTag: '__ais-highlight__',
hitsPerPage: limit,
page: 0,
query: '',
tagFilters: ''
}
}
]
};

const options = {
method: 'POST',
headers: await getRequestHeadersSearchAssets(),
body: JSON.stringify(data),
};

// Include the query parameters in the URL
const queryString = queryParams.toString();
const url = `${getSearchCollectionsUrl()}${queryString ? `?${queryString}` : ''}`;

try {
const response = await fetch(url, options);
// Handle response codes
if (response.status === 200) {
// Collection retrieved successfully
const responseBody = await response.json();

return responseBody;
}
// Handle other response codes
throw new Error(`Failed to search list collection: ${response.status} ${response.statusText}`);
} catch (error) {
logError('getLatestCampaignAssets', error);
throw error;
}
}


function getMaxThumbnailWidth() {
let maxWidth = getCSSVar('--card-image-max-width');
if (maxWidth) {
maxWidth = maxWidth.replace('px', '');
if (!Number.isNaN(Number(maxWidth))) {
return Number(maxWidth);
}
}
return 100;
}

function getVideoOverlayCSSClass(format) {
if (isVideo(format)) {
return 'icon icon-videoThumbnailOverlay';
}
return '';
}

function createAssetThumbnail(card,id, name, title, mimeType) {
const previewElem = card.querySelector('.preview .thumbnail');
getOptimizedPreviewUrl(id, name, getMaxThumbnailWidth()).then((url) => {
const img = document.createElement('img');
img.src = url;
img.alt = title;
img.style.width = '100px';
img.style.height = '100px';
img.style.margin = '5px'; // Add some spacing between thumbnails
img.dataset.fileformat = mimeType;
img.onerror = () => {
createFailedImageReplacement(previewElem, img, mimeType);
};
previewElem.appendChild(img);
}).catch(() => {
const img = document.createElement('img');
img.alt = title;
img.style.width = '100px';
img.style.height = '100px';
img.style.margin = '5px'; // Add some spacing between thumbnails
img.dataset.fileformat = mimeType;
createFailedImageReplacement(previewElem, img, mimeType);
previewElem.appendChild(img);
});
// if it's a video, add the video play icon over the middle of the thumbnail
if (isVideo(mimeType)) {
// create <div class="preview-overlay"><span></span></div>
const div = document.createElement('div');
div.className = 'preview-overlay';
const span = document.createElement('span');
div.appendChild(span);
previewElem.appendChild(div);
span.className = getVideoOverlayCSSClass(mimeType);
}
}


function createCardElement(
mimeType,
id,
name,
title
) {
const fileType = getFileType(mimeType);

const card = document.createElement('div');
card.setAttribute('data-item-name', name);

card.innerHTML = `
<div class="preview preview-${toClassName(getFileType(mimeType))}">
<a class="thumbnail asset-link" href="">
</a>
</div>
`;
decorateIcons(card);
return card;
}


async function createCampaignAssets(block) {
// include back to collections listing similar to hide filters button
block.innerHTML = `
<div class="adp-campaign-assets">Latest Assets (10)</div>
`;

const campaignAssetsContainer = document.createElement('div');
campaignAssetsContainer.className = 'campaign-assets-thumbnails';

//Todo Hardcode the campaignName for now
const campaignAssets = await getLatestCampaignAssets('gmo-campaignName:Everyone Can', 10);

for (const hit of campaignAssets.results[0].hits) {

let card = createCardElement(hit["dc-format"],hit["assetId"],hit["repo-name"],hit["repo-name"]);

createAssetThumbnail(card,hit["assetId"], hit["repo-name"], hit["repo-name"], hit["dc-format"]);

/*
console.log('card');
console.log(card);

const imageUrl = await getOptimizedPreviewUrl(hit["assetId"], hit["repo-name"], 100, hit["dc-format"]);

// Create an img element and set its source to the imageUrl
const imageElement = document.createElement('img');
imageElement.src = imageUrl;
imageElement.alt = "Campaign Asset";
imageElement.style.width = '100px'; // Set a fixed width for thumbnails, adjust as necessary
imageElement.style.height = '100px'; // Set a fixed height for thumbnails, adjust as necessary
imageElement.style.margin = '5px'; // Add some spacing between thumbnails

// Append the image element to the campaignAssetsContainer
campaignAssetsContainer.appendChild(imageElement);

*/
// Append the image element to the campaignAssetsContainer
campaignAssetsContainer.appendChild(card);
}

// Append the campaignAssetsContainer to the block after the loop completes
block.appendChild(campaignAssetsContainer);
decorateIcons(block);
return block;
}
export default async function decorate(block) {
block.innerHTML = '';
createCampaignAssets(block);
}




Loading
Loading