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

feat(editor): Update sticky content when checkbox state changes #9596

Merged
merged 17 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
80 changes: 77 additions & 3 deletions packages/design-system/src/components/N8nSticky/Sticky.vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@
@resize="onResize"
@resizestart="onResizeStart"
>
<div v-show="!editMode" :class="$style.wrapper" @dblclick.stop="onDoubleClick">
<div
v-show="!editMode"
ref="markdownContainer"
:class="$style.wrapper"
@dblclick.stop="onDoubleClick"
>
<N8nMarkdown
theme="sticky"
:content="modelValue"
Expand Down Expand Up @@ -58,12 +63,13 @@
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import N8nInput from '../N8nInput';
import N8nMarkdown from '../N8nMarkdown';
import N8nResizeWrapper, { type ResizeData } from '../N8nResizeWrapper/ResizeWrapper.vue';
import N8nText from '../N8nText';
import { useI18n } from '../../composables/useI18n';
import { replaceNth } from '../../utils/markdown';

interface StickyProps {
modelValue?: string;
Expand Down Expand Up @@ -105,6 +111,8 @@ const $emit = defineEmits<{
const { t } = useI18n();
const isResizing = ref(false);
const input = ref<HTMLTextAreaElement | undefined>(undefined);
const markdownContainer = ref<HTMLDivElement | undefined>(undefined);
const checkboxListeners = ref<Map<string, EventListener>>(new Map());

const resHeight = computed((): number => {
return props.height < props.minHeight ? props.minHeight : props.height;
Expand All @@ -124,17 +132,29 @@ const shouldShowFooter = computed((): boolean => resHeight.value > 100 && resWid
watch(
() => props.editMode,
(newMode, prevMode) => {
setTimeout(() => {
setTimeout(async () => {
if (newMode && !prevMode && input.value) {
if (props.defaultText === props.modelValue) {
input.value.select();
}
input.value.focus();
}
if (!newMode && prevMode) {
// Init checkbox events after editor is closed
await resetCheckboxListeners();
}
}, 100);
},
);

onMounted(() => {
initCheckboxEvents();
});

onBeforeUnmount(() => {
removeCheckboxListeners();
});

const onDoubleClick = () => {
if (!props.readOnly) $emit('edit', true);
};
Expand Down Expand Up @@ -171,6 +191,56 @@ const onInputScroll = (event: WheelEvent) => {
event.stopPropagation();
}
};

// TODO: Ideally, this should be part of the Markdown component
const initCheckboxEvents = () => {
const markdownContainerEl = markdownContainer.value;
const checkboxes = markdownContainerEl?.querySelectorAll('input[type="checkbox"]');
if (checkboxes) {
checkboxes.forEach((checkbox, position) => {
const handler: EventListener = onCheckboxChange.bind(null, checkbox, position);
checkbox.addEventListener('change', handler);
checkboxListeners.value.set(checkbox.id, handler);
});
}
};

const removeCheckboxListeners = () => {
const markdownContainerEl = markdownContainer.value;
const checkboxes = markdownContainerEl?.querySelectorAll('input[type="checkbox"]');
if (checkboxes) {
checkboxes.forEach((checkbox) => {
const handler = checkboxListeners.value.get(checkbox.id);
if (handler) {
checkbox.removeEventListener('change', handler);
checkboxListeners.value.delete(checkbox.id);
}
});
}
};

const resetCheckboxListeners = async () => {
removeCheckboxListeners();
await nextTick();
initCheckboxEvents();
};

// Update markdown when checkbox state changes
const onCheckboxChange = async (checkbox: HTMLInputElement, position: number) => {
const currentContent = props.modelValue;
if (!currentContent) {
return;
}
// We are using position to connect the checkbox with the corresponding line in the markdown
const newContent = replaceNth(
currentContent,
/\- \[[x|\s]\]/gim,
checkbox.checked ? '- [x]' : '- [ ]',
position + 1,
);
$emit('update:modelValue', newContent);
await resetCheckboxListeners();
};
</script>

<style lang="scss" module>
Expand All @@ -195,6 +265,10 @@ const onInputScroll = (event: WheelEvent) => {
cursor: pointer;
}

input[type='checkbox'] + label {
cursor: pointer;
}

.wrapper {
width: 100%;
height: 100%;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { render, fireEvent } from '@testing-library/vue';
import N8nSticky from '../Sticky.vue';
import N8nMarkdown from '../../N8nMarkdown/Markdown.vue';

describe('components', () => {
describe('Sticky', () => {
it('should update markdown when checkbox is clicked', async () => {
const wrapper = render(N8nSticky, {
props: {
editMode: false,
modelValue:
'### Checkboxes test\n- [x] One\n- [x] Two\n- Something else\n- [ ] Three\n- [ ] Four',
},
global: {
components: {
'n8n-markdown': N8nMarkdown,
},
},
});
const checkboxes = wrapper.container.querySelectorAll('input[type="checkbox"][checked]');
const allCheckboxes = wrapper.container.querySelectorAll('input[type="checkbox"]');
expect(checkboxes).toHaveLength(2);
// Should emit modelValue update when checkbox is clicked
await fireEvent.change(allCheckboxes[2], { target: { checked: true } });
expect(wrapper.emitted()['update:modelValue']).toBeDefined();
MiloradFilipovic marked this conversation as resolved.
Show resolved Hide resolved
// Emitted value should contain the new content (3rd checkbox checked)
const newContent = (wrapper.emitted()['update:modelValue'][0] as string[])[0];
expect(newContent).toContain('- [x] Three');
});
});
});
18 changes: 18 additions & 0 deletions packages/design-system/src/utils/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,21 @@ export const escapeMarkdown = (html: string | undefined): string => {

return withQuotes;
};

/**
* Replace nth occurrence of a regex match in a string
* @param markdown string to replace in
* @param regex regex to match
* @param replacement string to replace with
* @param index position of the occurrence to replace
*/
export const replaceNth = (markdown: string, regex: RegExp, replacement: string, index: number) => {
let occurrence = 0;
return markdown.replace(regex, (match) => {
occurrence++;
if (occurrence === index) {
return replacement;
}
return match;
});
};
Loading