Skip to content

Commit

Permalink
#590 - Fix image update in block
Browse files Browse the repository at this point in the history
  • Loading branch information
estruyf committed Jun 21, 2023
1 parent b644cab commit c9095ca
Show file tree
Hide file tree
Showing 10 changed files with 126 additions and 34 deletions.
1 change: 0 additions & 1 deletion src/dashboardWebView/components/Contents/Item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ export const Item: React.FunctionComponent<IItemProps> = ({
const { getColors } = useThemeColors();

const escapedTitle = useMemo(() => {
console.log('escapedTitle', title, cardFields?.title, pageData);
let value = title;

if (cardFields?.title) {
Expand Down
38 changes: 38 additions & 0 deletions src/helpers/ContentType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,14 @@ export class ContentType {
return emptyFields || [];
}

/**
* Find fields by type (deep search)
* @param fields
* @param type
* @param parents
* @param parentFields
* @returns
*/
public static findFieldsByTypeDeep(
fields: Field[],
type: FieldType,
Expand Down Expand Up @@ -482,6 +490,36 @@ export class ContentType {
return parents;
}

/**
* Retrieve the block field groups
* @param field
* @returns
*/
public static getBlockFieldGroups(field: Field): FieldGroup[] {
const groups =
field.fieldGroup && Array.isArray(field.fieldGroup) ? field.fieldGroup : [field.fieldGroup];
if (!groups) {
return [];
}

const blocks = Settings.get<FieldGroup[]>(SETTING_TAXONOMY_FIELD_GROUPS);
if (!blocks) {
return [];
}

let foundBlocks = [];
for (const group of groups) {
const block = blocks.find((block) => block.id === group);
if (!block) {
continue;
}

foundBlocks.push(block);
}

return foundBlocks;
}

/**
* Find all the required fields in the content type
* @param fields
Expand Down
1 change: 0 additions & 1 deletion src/helpers/ImageHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ export class ImageHelper {
* @param parents
*/
public static processImageFields(updatedMetadata: any, fields: Field[], parents: string[] = []) {
// TODO: Support image fields from blocks
const imageFields = fields.filter((field) => field.type === 'image');
const panel = ExplorerView.getInstance();

Expand Down
16 changes: 6 additions & 10 deletions src/listeners/panel/DataListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,7 @@ export class DataListener extends BaseListener {
const dateFields = ContentType.findFieldsByTypeDeep(contentType.fields, 'datetime');
const imageFields = ContentType.findFieldsByTypeDeep(contentType.fields, 'image');
const fileFields = ContentType.findFieldsByTypeDeep(contentType.fields, 'file');

// const dateFields = contentType.fields.filter((f) => f.type === 'datetime');
// const imageFields = contentType.fields.filter((f) => f.type === 'image' && f.multiple);
// const fileFields = contentType.fields.filter((f) => f.type === 'file' && f.multiple);
// const fieldsWithEmojiEncoding = contentType.fields.filter((f) => f.encodeEmoji);
const fieldsWithEmojiEncoding = contentType.fields.filter((f) => f.encodeEmoji);

// Support multi-level fields
const parentObj = DataListener.getParentObject(article.data, article, parents, blockData);
Expand All @@ -206,14 +202,14 @@ export class DataListener extends BaseListener {
const multiImageFieldsArray = imageFields.find((f: Field[]) => {
const lastField = f?.[f.length - 1];
if (lastField) {
return lastField.name === field;
return lastField.name === field && lastField.multiple;
}
});

const multiFileFieldsArray = fileFields.find((f: Field[]) => {
const lastField = f?.[f.length - 1];
if (lastField) {
return lastField.name === field;
return lastField.name === field && lastField.multiple;
}
});

Expand Down Expand Up @@ -253,9 +249,9 @@ export class DataListener extends BaseListener {
}
}
} else {
// if (fieldsWithEmojiEncoding.some((f) => f.name === field)) {
// value = encodeEmoji(value);
// }
if (fieldsWithEmojiEncoding.some((f) => f.name === field)) {
value = encodeEmoji(value);
}
parentObj[field] = value;
}

Expand Down
2 changes: 0 additions & 2 deletions src/listeners/panel/FieldsListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ export class FieldsListener extends BaseListener {
});
const pageResults = results.map((page) => page.item);

console.log('pageResults', pageResults);

this.sendRequest(command, requestId, pageResults || []);
});
}
Expand Down
41 changes: 41 additions & 0 deletions src/listeners/panel/MediaListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { DashboardData, PostMessageData } from '../../models';
import { Command } from '../../panelWebView/Command';
import { CommandToCode } from '../../panelWebView/CommandToCode';
import { BaseListener } from './BaseListener';
import { Preview } from '../../commands';

export class MediaListener extends BaseListener {
/**
Expand All @@ -26,6 +27,46 @@ export class MediaListener extends BaseListener {
case CommandToCode.getImageUrl:
this.generateUrl(msg.payload);
break;
case CommandToCode.processMediaData:
this.processMedia(msg.command, msg.payload, msg.requestId);
break;
}
}

private static processMedia(command: string, payload: any, requestId?: string) {
if (!requestId || !payload) {
return;
}

const panel = ExplorerView.getInstance();

if (typeof payload === 'string') {
const imagePath = payload;
const filePath = window.activeTextEditor?.document.uri.fsPath || Preview.filePath;
if (!filePath) {
return;
}

const imageAbsPath = imagePath.startsWith('http')
? imagePath
: ImageHelper.relToAbs(filePath, imagePath);

let preview = undefined;
if (imageAbsPath) {
preview =
typeof imageAbsPath === 'string'
? imageAbsPath
: panel.getWebview()?.asWebviewUri(imageAbsPath);
}

const imageData = {
original: imagePath,
absPath: imageAbsPath,
webviewUrl: preview ? preview.toString() : null
};

this.sendRequest(command, requestId, imageData);
return;
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/panelWebView/CommandToCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,6 @@ export enum CommandToCode {
generateSlug = 'generate-slug',
stopServer = 'stop-server',
aiSuggestTaxonomy = 'ai-suggest-taxonomy',
searchByType = 'search-by-type'
searchByType = 'search-by-type',
processMediaData = 'process-media-data'
}
2 changes: 0 additions & 2 deletions src/panelWebView/components/DataBlock/DataBlockField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ export const DataBlockField: React.FunctionComponent<IDataBlockFieldProps> = ({

const onFieldUpdate = useCallback(
(crntField: string | undefined, crntValue: any, parents: string[]) => {
debugger;
const dataClone: any[] = Object.assign([], value);

if (!crntField) {
Expand Down Expand Up @@ -242,7 +241,6 @@ export const DataBlockField: React.FunctionComponent<IDataBlockFieldProps> = ({
);

const getSelectedIndex = useCallback(() => {
console.log(blockData)
let crntValue = [];

if (blockData?.selectedIndex !== null && blockData?.selectedIndex !== undefined) {
Expand Down
55 changes: 39 additions & 16 deletions src/panelWebView/components/Fields/PreviewImageField.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Messenger } from '@estruyf/vscode/dist/client';
import { Messenger, messageHandler } from '@estruyf/vscode/dist/client';
import { PhotographIcon } from '@heroicons/react/outline';
import * as React from 'react';
import { useCallback, useMemo } from 'react';
import { useCallback, useEffect, useMemo } from 'react';
import { DefaultFieldValues } from '../../../constants';
import { BaseFieldProps, BlockFieldData } from '../../../models';
import { CommandToCode } from '../../CommandToCode';
Expand All @@ -15,7 +15,7 @@ export interface PreviewImageValue {
}

export interface IPreviewImageFieldProps
extends BaseFieldProps<PreviewImageValue | PreviewImageValue[] | null> {
extends BaseFieldProps<PreviewImageValue | PreviewImageValue[] | string[] | null> {
fieldName: string;
filePath: string | null;
parents?: string[];
Expand All @@ -36,6 +36,8 @@ export const PreviewImageField: React.FunctionComponent<IPreviewImageFieldProps>
parents,
required
}: React.PropsWithChildren<IPreviewImageFieldProps>) => {
const [imageData, setImageData] = React.useState<PreviewImageValue | PreviewImageValue[] | null>(null);

const selectImage = useCallback(() => {
Messenger.send(CommandToCode.selectImage, {
filePath: filePath,
Expand All @@ -49,14 +51,13 @@ export const PreviewImageField: React.FunctionComponent<IPreviewImageFieldProps>
});
}, [filePath, fieldName, value, multiple, parents]);

const onImageRemove = (imageToRemove: string) => {
debugger;
const onImageRemove = useCallback((imageToRemove: string) => {
const newValue =
value && Array.isArray(value)
? value.filter((image) => (image?.original || image) !== imageToRemove).map((i) => (i?.original || i as any as string))
imageData && Array.isArray(imageData)
? imageData.filter((image) => image.original !== imageToRemove).map((i) => i.original)
: null;
onChange(newValue);
};
}, [imageData]);

const isFaultyImage = useMemo(() => {
return typeof value === 'string' && value === DefaultFieldValues.faultyCustomPlaceholder;
Expand All @@ -66,17 +67,39 @@ export const PreviewImageField: React.FunctionComponent<IPreviewImageFieldProps>
return required && (isFaultyImage || !value);
}, [required, value, isFaultyImage]);

useEffect(() => {
if (typeof value === 'string') {
messageHandler.request<PreviewImageValue>(CommandToCode.processMediaData, value).then((data) => {
setImageData(data);
});
} else if (Array.isArray(value)) {
Promise.all(
value.map((v) => {
if (typeof v === 'string') {
return messageHandler.request<PreviewImageValue>(CommandToCode.processMediaData, v);
} else {
return Promise.resolve(v);
}
})
).then((data) => {
setImageData(data);
});
} else {
setImageData(value);
}
}, [value]);

return (
<div className={`metadata_field`}>
<FieldTitle label={label} icon={<PhotographIcon />} required={required} />

<div
className={`metadata_field__preview_image ${multiple && value && (value as PreviewImageValue[]).length > 0
className={`metadata_field__preview_image ${multiple && imageData && (imageData as PreviewImageValue[]).length > 0
? `metadata_field__multiple_images`
: ''
} ${showRequiredState ? 'required' : ''}`}
>
{(!value || isFaultyImage || multiple) && (
{(!imageData || isFaultyImage || multiple) && (
<button
className={`metadata_field__preview_image__button`}
title={`Add your ${label?.toLowerCase() || 'image'}`}
Expand All @@ -88,16 +111,16 @@ export const PreviewImageField: React.FunctionComponent<IPreviewImageFieldProps>
</button>
)}

{value && !Array.isArray(value) && !isFaultyImage && (
<PreviewImage value={value} onRemove={() => onChange(null)} />
{imageData && !Array.isArray(imageData) && !isFaultyImage && (
<PreviewImage value={imageData} onRemove={() => onChange(null)} />
)}

{multiple &&
value &&
Array.isArray(value) &&
imageData &&
Array.isArray(imageData) &&
!isFaultyImage &&
value.map((image) => (
<PreviewImage key={image?.original || image as any as string} value={image} onRemove={() => onImageRemove(image?.original || image as any as string)} />
imageData.map((image) => (
<PreviewImage key={image.original} value={image} onRemove={() => onImageRemove(image.original)} />
))}
</div>

Expand Down
1 change: 0 additions & 1 deletion src/panelWebView/components/Fields/WrapperField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,6 @@ export const WrapperField: React.FunctionComponent<IWrapperFieldProps> = ({
</FieldBoundary>
);
} else if (field.type === 'image') {
console.log('image', field, fieldValue);
return (
<FieldBoundary key={field.name} fieldName={field.title || field.name}>
<PreviewImageField
Expand Down

0 comments on commit c9095ca

Please sign in to comment.