spscript icon indicating copy to clipboard operation
spscript copied to clipboard

Modern Theme Utilities

Open DroopyTersen opened this issue 5 years ago • 0 comments

ctx.themes namespace?

  • getTheme(themeName)
  • getThemes()
  • applyTheme(themeName)
  • createTheme
  • deleteTheme
const findTheme = async function(siteUrl, themeName) {
  let ctx = SPScript.createContext(siteUrl);
  let response = await ctx.get("/thememanager/GetTenantThemingOptions").then(SPScript.utils.validateODataV2);
  let themes = response.GetTenantThemingOptions.themePreviews.results;
  return themes.find(t => t.name === themeName);
};
const applyTheme = async function(siteUrl, themeName) {
  let ctx = SPScript.createContext(siteUrl);
  let theme = await findTheme(siteUrl, themeName);
  if (theme) {
    await ctx.authorizedPost("/thememanager/ApplyTheme", theme);
  }
};
export function getCurrentTheme() : object {
    let currentTheme = getValue(window, "__globalSettings__.customizations.settings.theme.palette")
    if (!currentTheme) currentTheme = defaultTheme;
    return currentTheme;
}

export async function deleteTenantTheme(name:string) {
    let ctx = SPScript.createContext((window as any)._siteUrl);
    let existingThemes = await getTenantThemes();
    let exists = existingThemes && existingThemes.find(t => t.name === name);
    let path = `/themeManager/DeleteTenantTheme`
    if (exists) {
        return ctx.authorizedPost(path, { name: name })
    }
}
export async function saveTenantTheme(theme:SavedTheme) {
    let ctx = SPScript.createContext((window as any)._siteUrl);
    let existingThemes = await getTenantThemes();
    let exists = existingThemes && existingThemes.find(t => t.name === theme.name);

    let path = `/themeManager/${exists ? "Update" : "Add"}TenantTheme`
    return ctx.authorizedPost(path, { name: theme.name, themeJson: JSON.stringify(theme)})
}

export async function getCurrentUser() {
    let ctx = SPScript.createContext((window as any)._siteUrl);
    let user = await ctx.web.getUser();
    return user as SPCurrentUser;
}
export async function getTenantThemes() : Promise<SavedTheme[]> {
    let ctx = SPScript.createContext((window as any)._siteUrl);
    let data = await ctx.authorizedPost("/thememanager/GetTenantThemingOptions")
                        .then(SPScript.utils.validateODataV2);

    try {
        let rawThemes = data.GetTenantThemingOptions.themePreviews.results
        let themes = rawThemes.map(raw => JSON.parse(raw.themeJson) as SavedTheme);
        return themes;
    } catch (err) {
        return [];
    }
}

DroopyTersen avatar Mar 19 '19 00:03 DroopyTersen