Skip to content
Merged
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
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
# Ignore exporting the adapter as it will be split off and released on its own.
/yii2-adapter export-ignore

# Workbench is only for development
/workbench export-ignore

# Identify generated files
/resources/translations/a*/app.php linguist-generated=true
/resources/translations/c*/app.php linguist-generated=true
Expand Down
54 changes: 50 additions & 4 deletions packages/craftcms-cp/src/utilities/dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ describe('appendHeadHtml', () => {

test('appends a script element to head', async () => {
const {appendHeadHtml} = await freshImport();
await appendHeadHtml(
const append = appendHeadHtml(
'<script src="https://example.com/script.js"></script>'
);
document.head.querySelector('script')!.dispatchEvent(new Event('load'));
await append;

const scripts = document.head.querySelectorAll('script');
expect(scripts.length).toBe(1);
expect(scripts[0]!.getAttribute('src')).toBe(
Expand Down Expand Up @@ -80,9 +83,12 @@ describe('appendHeadHtml', () => {

test('preserves script attributes when appending', async () => {
const {appendHeadHtml} = await freshImport();
await appendHeadHtml(
const append = appendHeadHtml(
'<script src="https://example.com/b.js" type="module" defer></script>'
);
document.head.querySelector('script')!.dispatchEvent(new Event('load'));
await append;

const script = document.head.querySelector('script')!;
expect(script.getAttribute('src')).toBe('https://example.com/b.js');
expect(script.getAttribute('type')).toBe('module');
Expand All @@ -106,11 +112,29 @@ describe('appendBodyHtml', () => {

test('appends script with src to body', async () => {
const {appendBodyHtml} = await freshImport();
await appendBodyHtml('<script src="https://example.com/body.js"></script>');
const append = appendBodyHtml(
'<script src="https://example.com/body.js"></script>'
);
document.body.querySelector('script')!.dispatchEvent(new Event('load'));
await append;

const scripts = document.body.querySelectorAll('script');
expect(scripts.length).toBe(1);
expect(scripts[0]!.getAttribute('src')).toBe('https://example.com/body.js');
});

test('appends elements to a provided parent', async () => {
const {appendElementHtml} = await freshImport();
const parent = document.createElement('div');

const dispose = await appendElementHtml('<p id="child">Hello</p>', parent);

expect(parent.querySelector('#child')!.textContent).toBe('Hello');

dispose();

expect(parent.querySelector('#child')).toBeNull();
});
});

describe('CSS deduplication', () => {
Expand Down Expand Up @@ -150,8 +174,12 @@ describe('JS deduplication', () => {
test('does not add duplicate script src', async () => {
const {appendBodyHtml} = await freshImport();
const js = '<script src="https://example.com/dup.js"></script>';
const firstAppend = appendBodyHtml(js);
document.body.querySelector('script')!.dispatchEvent(new Event('load'));
await firstAppend;

await appendBodyHtml(js);
await appendBodyHtml(js);

const scripts = document.body.querySelectorAll('script');
expect(scripts.length).toBe(1);
});
Expand All @@ -164,4 +192,22 @@ describe('JS deduplication', () => {
const scripts = document.body.querySelectorAll('script');
expect(scripts.length).toBe(2);
});

test('waits for external scripts before appending subsequent nodes', async () => {
const {appendElementHtml} = await freshImport();
const parent = document.createElement('div');
const append = appendElementHtml(
'<script src="https://example.com/ordered.js"></script><span id="after-script"></span>',
parent
);

await Promise.resolve();

expect(parent.querySelector('#after-script')).toBeNull();

parent.querySelector('script')!.dispatchEvent(new Event('load'));
await append;

expect(parent.querySelector('#after-script')).not.toBeNull();
});
});
21 changes: 18 additions & 3 deletions packages/craftcms-cp/src/utilities/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ let existingJs: string[] | null = null;
*/
export type AppendHtmlDisposer = () => void;

async function appendHtml(
function waitForScript(script: HTMLScriptElement): Promise<void> {
return new Promise((resolve) => {
script.addEventListener('load', () => resolve(), {once: true});
script.addEventListener('error', () => resolve(), {once: true});
});
}

export async function appendElementHtml(
html: string,
parent: HTMLElement
): Promise<AppendHtmlDisposer> {
Expand Down Expand Up @@ -72,6 +79,8 @@ async function appendHtml(

if (node instanceof HTMLScriptElement) {
const script = document.createElement('script');
let scriptLoaded: Promise<void> | null = null;

Array.from(node.attributes).forEach((attr) => {
script.setAttribute(attr.name, attr.value);
});
Expand All @@ -91,12 +100,18 @@ async function appendHtml(
existingJs.push(src);
jsAdded.push(src);
script.async = false;
scriptLoaded = waitForScript(script);
} else {
script.textContent = node.textContent;
}

parent.appendChild(script);
appended.push(script);

if (scriptLoaded) {
await scriptLoaded;
}

continue;
}

Expand All @@ -116,7 +131,7 @@ async function appendHtml(
export async function appendHeadHtml(
html: string
): Promise<AppendHtmlDisposer> {
return appendHtml(html, document.head);
return appendElementHtml(html, document.head);
}

/**
Expand All @@ -127,5 +142,5 @@ export async function appendHeadHtml(
export async function appendBodyHtml(
html: string
): Promise<AppendHtmlDisposer> {
return appendHtml(html, document.body);
return appendElementHtml(html, document.body);
}
101 changes: 101 additions & 0 deletions resources/js/common/components/HtmlFragmentRenderer.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<script setup lang="ts">
import {
appendBodyHtml,
appendElementHtml,
appendHeadHtml,
type AppendHtmlDisposer,
} from '@craftcms/cp';
import {onBeforeUnmount, ref, watch} from 'vue';

const props = defineProps<{
fragment?: CraftCms.Cms.View.HtmlFragment | null;
}>();

const container = ref<HTMLElement | null>(null);
const disposers: AppendHtmlDisposer[] = [];
let lastKey = '';
let runId = 0;

const disposeAll = () => {
while (disposers.length) {
disposers.pop()?.();
}
};

const remember = async (
promise: Promise<AppendHtmlDisposer>,
currentRunId: number
): Promise<boolean> => {
const dispose = await promise;

if (currentRunId !== runId) {
dispose();

return false;
}

disposers.push(dispose);

return true;
};

watch(
() => ({
element: container.value,
html: props.fragment?.html ?? '',
headHtml: props.fragment?.headHtml ?? '',
bodyHtml: props.fragment?.bodyHtml ?? '',
}),
async ({element, html, headHtml, bodyHtml}) => {
const key = `${headHtml}\u0000${html}\u0000${bodyHtml}`;

if (!element || key === '\u0000\u0000') {
runId++;
lastKey = '';
disposeAll();

return;
}

if (key === lastKey) {
return;
}

runId++;
const currentRunId = runId;
lastKey = key;
disposeAll();

if (
headHtml &&
!(await remember(appendHeadHtml(headHtml), currentRunId))
) {
return;
}

if (
html &&
!(await remember(appendElementHtml(html, element), currentRunId))
) {
return;
}

if (
bodyHtml &&
!(await remember(appendBodyHtml(bodyHtml), currentRunId))
) {
return;
}
},
{immediate: true}
);

onBeforeUnmount(() => {
runId++;
disposeAll();
});
</script>

<template>
<div v-if="fragment" ref="container"></div>
</template>
12 changes: 6 additions & 6 deletions resources/js/common/layouts/AppLayout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@

const page = usePage<{
title: string;
readOnly: boolean;
readOnly?: boolean;
crumbs?: Array<{
url?: string;
label: string;
Expand All @@ -70,7 +70,7 @@
{label: t('Skip to main section'), url: '#main'},
...(props.additionalSkipLinks ?? []),
]);
const readOnly = computed(() => page.props.readOnly);
const readOnly = computed(() => Boolean(page.props.readOnly));
const hasDetails = computed(() => Boolean(slots.details));
const sidebarToggle = useTemplateRef('sidebarToggle');
const primaryFormButton = 'primary';
Expand Down Expand Up @@ -153,9 +153,7 @@
}

function isFormButtonProcessing(key: string) {
return (
Boolean(props.form?.processing) && activeFormButton.value === key
);
return Boolean(props.form?.processing) && activeFormButton.value === key;
}

function activateFormButton(key: string) {
Expand Down Expand Up @@ -288,7 +286,9 @@
<craft-button
type="submit"
variant="accent"
:loading="isFormButtonProcessing(primaryFormButton)"
:loading="
isFormButtonProcessing(primaryFormButton)
"
:disabled="form.processing"
>
{{ t('Save') }}
Expand Down
8 changes: 6 additions & 2 deletions resources/js/pages/users/Permissions.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@
inheritAttrs: false,
});

const props =
usePage<CraftCms.Cms.Http.ViewModels.UserPermissionsViewModel>().props;
type UserPermissionsPageProps =
CraftCms.Cms.Http.ViewModels.UserPermissionsViewModel & {
details?: string | null;
};

const props = usePage<UserPermissionsPageProps>().props;

const form = useForm({
admin: props.user.admin,
Expand Down
Loading
Loading