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

style(preview_onFocus): try_add_borders_in_field_preview_when_edit_field_is_onFocus #20

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
48 changes: 36 additions & 12 deletions netlify-cms@2/packages/netlify-cms-core/src/actions/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export const DRAFT_CREATE_FROM_ENTRY = 'DRAFT_CREATE_FROM_ENTRY';
export const DRAFT_CREATE_EMPTY = 'DRAFT_CREATE_EMPTY';
export const DRAFT_DISCARD = 'DRAFT_DISCARD';
export const DRAFT_CHANGE_FIELD = 'DRAFT_CHANGE_FIELD';
export const DRAFT_FOCUS_FIELD = 'DRAFT_FOCUS_FIELD';
export const DRAFT_VALIDATION_ERRORS = 'DRAFT_VALIDATION_ERRORS';
export const DRAFT_CLEAR_ERRORS = 'DRAFT_CLEAR_ERRORS';
export const DRAFT_LOCAL_BACKUP_RETRIEVED = 'DRAFT_LOCAL_BACKUP_RETRIEVED';
Expand Down Expand Up @@ -433,6 +434,29 @@ export function changeDraftField({
};
}

export function focusDraftField({
field,
value,
metadata,
entries,
i18n,
}: {
field: EntryField;
value: string;
metadata: Record<string, unknown>;
entries: EntryMap[];
i18n?: {
currentLocale: string;
defaultLocale: string;
locales: string[];
};
}) {
return {
type: DRAFT_FOCUS_FIELD,
payload: { field, value, metadata, entries, i18n },
};
}

export function changeDraftFieldValidation(
uniquefieldId: string,
errors: { type: string; parentIds: string[]; message: string }[],
Expand Down Expand Up @@ -610,7 +634,7 @@ export function loadEntries(collection: Collection, page = 0) {
entries: EntryValue[];
} = await (loadAllEntries
? // nested collections require all entries to construct the tree
provider.listAllEntries(collection).then((entries: EntryValue[]) => ({ entries }))
provider.listAllEntries(collection).then((entries: EntryValue[]) => ({ entries }))
: provider.listEntries(collection, page));
response = {
...response,
Expand All @@ -622,10 +646,10 @@ export function loadEntries(collection: Collection, page = 0) {
// cursor, which behaves identically to no cursor at all.
cursor: integration
? Cursor.create({
actions: ['next'],
meta: { usingOldPaginationAPI: true },
data: { nextPage: page + 1 },
})
actions: ['next'],
meta: { usingOldPaginationAPI: true },
data: { nextPage: page + 1 },
})
: Cursor.create(response.cursor),
};

Expand Down Expand Up @@ -776,13 +800,13 @@ export function createEmptyDraft(collection: Collection, search: string) {

interface DraftEntryData {
[name: string]:
| string
| null
| boolean
| List<unknown>
| DraftEntryData
| DraftEntryData[]
| (string | DraftEntryData | boolean | List<unknown>)[];
| string
| null
| boolean
| List<unknown>
| DraftEntryData
| DraftEntryData[]
| (string | DraftEntryData | boolean | List<unknown>)[];
}

export function createEmptyDraftData(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
createEmptyDraft,
discardDraft,
changeDraftField,
focusDraftField,
changeDraftFieldValidation,
persistEntry,
deleteEntry,
Expand All @@ -39,6 +40,7 @@ import withWorkflow from './withWorkflow';
export class Editor extends React.Component {
static propTypes = {
changeDraftField: PropTypes.func.isRequired,
focusDraftField: PropTypes.func.isRequired,
changeDraftFieldValidation: PropTypes.func.isRequired,
collection: ImmutablePropTypes.map.isRequired,
createDraftDuplicateFromEntry: PropTypes.func.isRequired,
Expand Down Expand Up @@ -201,6 +203,11 @@ export class Editor extends React.Component {
this.props.changeDraftField({ field, value, metadata, entries, i18n });
};

handleFocusDraftField = (field, value, metadata, i18n) => {
const entries = [this.props.unPublishedEntry, this.props.publishedEntry].filter(Boolean);
this.props.focusDraftField({ field, value, metadata, entries, i18n });
};

handleChangeStatus = newStatusName => {
const { entryDraft, updateUnpublishedEntryStatus, collection, slug, currentStatus, t } =
this.props;
Expand Down Expand Up @@ -383,6 +390,7 @@ export class Editor extends React.Component {
fieldsMetaData={entryDraft.get('fieldsMetaData')}
fieldsErrors={entryDraft.get('fieldsErrors')}
onChange={this.handleChangeDraftField}
onFocus={this.handleFocusDraftField}
onValidate={changeDraftFieldValidation}
onPersist={this.handlePersistEntry}
onDelete={this.handleDeleteEntry}
Expand Down Expand Up @@ -471,6 +479,7 @@ function mapStateToProps(state, ownProps) {

const mapDispatchToProps = {
changeDraftField,
focusDraftField,
changeDraftFieldValidation,
loadEntry,
loadEntries,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ class EditorControl extends React.Component {
mediaPaths: ImmutablePropTypes.map.isRequired,
boundGetAsset: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func,
openMediaLibrary: PropTypes.func.isRequired,
addAsset: PropTypes.func.isRequired,
removeInsertedMedia: PropTypes.func.isRequired,
Expand Down Expand Up @@ -177,6 +178,7 @@ class EditorControl extends React.Component {
mediaPaths,
boundGetAsset,
onChange,
onFocus,
openMediaLibrary,
clearMediaControl,
removeMediaControl,
Expand Down Expand Up @@ -290,6 +292,7 @@ class EditorControl extends React.Component {
mediaPaths={mediaPaths}
metadata={metadata}
onChange={(newValue, newMetadata) => onChange(field, newValue, newMetadata)}
onFocus={(newValue, newMetadata) => onFocus(field, newValue, newMetadata)}
onValidate={onValidate && partial(onValidate, this.uniqueFieldId)}
onOpenMediaLibrary={openMediaLibrary}
onClearMediaControl={clearMediaControl}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export default class ControlPane extends React.Component {
};

render() {
const { collection, entry, fields, fieldsMetaData, fieldsErrors, onChange, onValidate, t } =
const { collection, entry, fields, fieldsMetaData, fieldsErrors, onChange, onFocus, onValidate, t } =
this.props;

if (!collection || !fields) {
Expand Down Expand Up @@ -227,6 +227,10 @@ export default class ControlPane extends React.Component {
console.log('newMeta', newMetadata);
onChange(field, newValue, newMetadata, i18n);
}}
onFocus={(field, newValue, newMetadata) => {
console.log('newMeta', newMetadata);
onFocus(field, newValue, newMetadata, i18n);
}}
onValidate={onValidate}
processControlRef={this.controlRef.bind(this)}
controlRef={this.controlRef}
Expand All @@ -251,5 +255,6 @@ ControlPane.propTypes = {
fieldsMetaData: ImmutablePropTypes.map.isRequired,
fieldsErrors: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
onValidate: PropTypes.func.isRequired,
};
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export default class Widget extends Component {
metadata: ImmutablePropTypes.map,
fieldsErrors: ImmutablePropTypes.map,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,

onValidate: PropTypes.func,
onOpenMediaLibrary: PropTypes.func.isRequired,
onClearMediaControl: PropTypes.func.isRequired,
Expand Down Expand Up @@ -257,6 +259,7 @@ export default class Widget extends Component {
mediaPaths,
metadata,
onChange,
onFocus,
onValidateObject,
onOpenMediaLibrary,
onRemoveMediaControl,
Expand Down Expand Up @@ -303,6 +306,7 @@ export default class Widget extends Component {
mediaPaths,
metadata,
onChange,
onFocus,
onChangeObject: this.onChangeObject,
onValidateObject,
onOpenMediaLibrary,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ class EditorInterface extends Component {
fieldsMetaData,
fieldsErrors,
onChange,
onFocus,
showDelete,
onDelete,
onDeleteUnpublishedChanges,
Expand Down Expand Up @@ -247,6 +248,7 @@ class EditorInterface extends Component {
fieldsMetaData,
fieldsErrors,
onChange,
onFocus,
onValidate,
};

Expand Down Expand Up @@ -405,6 +407,7 @@ EditorInterface.propTypes = {
fieldsMetaData: ImmutablePropTypes.map.isRequired,
fieldsErrors: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
onValidate: PropTypes.func.isRequired,
onPersist: PropTypes.func.isRequired,
showDelete: PropTypes.bool.isRequired,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
DRAFT_CREATE_EMPTY,
DRAFT_DISCARD,
DRAFT_CHANGE_FIELD,
DRAFT_FOCUS_FIELD,
DRAFT_VALIDATION_ERRORS,
DRAFT_CLEAR_ERRORS,
DRAFT_LOCAL_BACKUP_RETRIEVED,
Expand Down Expand Up @@ -117,7 +118,29 @@ function entryDraftReducer(state = Map(), action) {
state.set(
'hasChanged',
!entries.some(e => newData.equals(e.get(...dataPath))) ||
!entries.some(e => newMeta.equals(e.get('meta'))),
!entries.some(e => newMeta.equals(e.get('meta'))),
);
});
}
case DRAFT_FOCUS_FIELD: {
return state.withMutations(state => {

const { field, value, metadata, entries, i18n } = action.payload;
const name = field.get('name');
window.storefrontCmsFocusField = {
name: field.get('name'),
label: field.get('label'),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O label aqui funciona com nested props?
Por exemplo, ficaria settings.primary_color ou só primary_color?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Humm esse label é para identificar o componente que foi triggado. Posso montar o objeto de outra forma.
Seria colocar as características da borda ai nesse componente, isso?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Não não, na verdade seria pra eu conseguir identificar o field que foi alterado em nested objects...
Um exemplo com as sections:

"sections": [
  {
    "type": "banner",
    "image": {
      "src": ""
    }
  }
]

Se ele editar a imagem do banner, eu só conseguiria identificar qual elemento foi alterado se o field vier algo como sections[0].image.src (dot notation), se vier só como src não tem como a gente saber no custom preview qual banner está sendo alterado, e portanto não teria como colocar a borda no banner certo, faz sentido?

}
const dataPath = (i18n && getDataPath(i18n.currentLocale, i18n.defaultLocale)) || ['data'];
state.setIn(['entry', 'meta', name], value);

state.mergeDeepIn(['fieldsMetaData'], fromJS(metadata));
const newData = state.getIn(['entry', ...dataPath]);
const newMeta = state.getIn(['entry', 'meta']);
state.set(
'hasFocused',
!entries.some(e => newData.equals(e.get(...dataPath))) ||
!entries.some(e => newMeta.equals(e.get('meta'))),
);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export default class CodeControl extends React.Component {
static propTypes = {
field: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
value: PropTypes.node,
forID: PropTypes.string.isRequired,
classNameWrapper: PropTypes.string.isRequired,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ function toValue(value, field) {

function CodePreview(props) {
return (
<WidgetPreviewContainer>
<WidgetPreviewContainer
style={{
borderStyle:
props?.field.get('name') === window?.storefrontCmsFocusField?.name && props?.field.get('label') === window?.storefrontCmsFocusField?.label
? 'dotted' : 'none'
}}>
<pre>
<code>{toValue(props.value, props.field)}</code>
</pre>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const SettingsSectionTitle = styled.h3`
}
`;

function SettingsSelect({ value, options, onChange, forID, type, autoFocus }) {
function SettingsSelect({ value, options, onChange, forID, type, autoFocus, onFocus }) {
return (
<Select
inputId={`${forID}-select-${type}`}
Expand All @@ -50,6 +50,7 @@ function SettingsSelect({ value, options, onChange, forID, type, autoFocus }) {
menuPlacement="auto"
captureMenuScroll={false}
autoFocus={autoFocus}
onFocus={opt => onFocus(opt.value)}
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const ClickOutsideDiv = styled.div`
export default class ColorControl extends React.Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
forID: PropTypes.string,
value: PropTypes.node,
classNameWrapper: PropTypes.string.isRequired,
Expand Down Expand Up @@ -110,8 +111,15 @@ export default class ColorControl extends React.Component {
: color.hex;
this.props.onChange(formattedColor);
};
handleFocus = color => {
const formattedColor =
color.rgb.a < 1
? `rgba(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b}, ${color.rgb.a})`
: color.hex;
this.props.onFocus(formattedColor);
};
render() {
const { forID, value, field, onChange, classNameWrapper, setActiveStyle, setInactiveStyle } =
const { forID, value, field, onChange, onFocus, classNameWrapper, setActiveStyle, setInactiveStyle } =
this.props;

const allowInput = field.get('allowInput', false);
Expand Down Expand Up @@ -144,6 +152,7 @@ export default class ColorControl extends React.Component {
color={value || ''}
onChange={this.handleChange}
disableAlpha={!field.get('enableAlpha', false)}
onFocus={this.handleFocus}
/>
</ColorPickerContainer>
)}
Expand All @@ -154,7 +163,7 @@ export default class ColorControl extends React.Component {
className={classNameWrapper}
value={value || ''}
onChange={e => onChange(e.target.value)}
onFocus={setActiveStyle}
onFocus={e => { onFocus(e.target.value); this.props.setActiveStyle() }}
onBlur={setInactiveStyle}
style={{
paddingLeft: '75px',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React from 'react';
import PropTypes from 'prop-types';
import { WidgetPreviewContainer } from 'netlify-cms-ui-default';

function ColorPreview({ value }) {
return <WidgetPreviewContainer>{value}</WidgetPreviewContainer>;
function ColorPreview({ value, field }) {
return <WidgetPreviewContainer style={{ borderStyle: field?.get('name') === window?.storefrontCmsFocusField?.name && field?.get('label') === window?.storefrontCmsFocusField?.label ? 'dotted' : 'none' }}>{value}</WidgetPreviewContainer>;
}

ColorPreview.propTypes = {
Expand Down
17 changes: 17 additions & 0 deletions netlify-cms@2/packages/netlify-cms-widget-date/src/DateControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export default class DateControl extends React.Component {
field: PropTypes.object.isRequired,
forID: PropTypes.string,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
classNameWrapper: PropTypes.string.isRequired,
setActiveStyle: PropTypes.func.isRequired,
setInactiveStyle: PropTypes.func.isRequired,
Expand Down Expand Up @@ -101,6 +102,21 @@ export default class DateControl extends React.Component {
onChange(value);
}
};
handleFocus = datetime => {
if (!this.isValidDate(datetime)) {
return;
}
const { onFocus } = this.props;
const { format } = this.formats;

if (format) {
const formattedValue = datetime ? moment(datetime).format(format) : '';
onFocus(formattedValue);
} else {
const value = moment.isMoment(datetime) ? datetime.toDate() : datetime;
onFocus(value);
}
};

onClose = datetime => {
const { setInactiveStyle } = this.props;
Expand Down Expand Up @@ -132,6 +148,7 @@ export default class DateControl extends React.Component {
timeFormat={timeFormat}
value={moment(value, format)}
onChange={this.handleChange}
onFocus={this.handleFocus}
onOpen={setActiveStyle}
onClose={this.onClose}
inputProps={{ className: classNameWrapper, id: forID }}
Expand Down
Loading