Etapa 14: Usar Estilos Personalizados Quando o Componente é Renderizado em um iFrame

Os componentes renderizados em um iframe não têm acesso direto ao arquivo design.css. Em vez disso, há uma etapa adicional para obter o URL do arquivo design.css em seu componente e adicioná-lo à página. Atualize então seu componente para refletir o estilo selecionado do usuário.

Para incluir e usar o arquivo design.css, seu componente exige alterações no arquivo render.html:
  1. Localize e inclua o URL no arquivo design.css

  2. Obtenha o valor da classe de estilo de seleção sempre que ele for alterado

  3. Atualize o modelo para refletir o styleClass selecionado

  4. Reflita no seu componente as alterações na classe de estilo selecionada

  5. Certifique-se de que o iframe seja redimensionado quando o estilo for alterado

Aqui estão as instruções detalhadas para editar o arquivo render.html:

  1. Localize e inclua o URL no arquivo design.css

    Adicione dinamicamente o arquivo design.css à seção <head> da página. Após o carregamento, defina a altura do iframe porque ela pode ter sido alterada com a aplicação dos estilos.

    Adicione o seguinte código ao objeto viewModel:

    // Dynamically add any theme design URL to the <head> of the page
    self.loadStyleSheet = function (url) {
        var $style,
            styleSheetDeferred = new $.Deferred(),
            attempts = 100,
            numAttempts = 0,
            interval = 50,
            pollFunction = function () {
                // try to locate the style sheet
                for (var i = 0; i < document.styleSheets.length; i++) {
                    try {
                        // locate the @import sheet that has an href based on our expected URL
                        var sheet = document.styleSheets[i],
                            rules = sheet && sheet.cssRules,
                            rule = rules && rules[0];
                        // check whether style sheet has been loaded
                        if (rule && (rule.href === url)) {
                            styleSheetDeferred.resolve();
                            return;
                        }
                    } catch (e) {}
                }
                if (numAttempts < attempts) {
                    numAttempts++;
                    setTimeout(pollFunction, interval);
                } else {
                    // didn't find style sheet so complete anyway
                    styleSheetDeferred.resolve();
                }
            };
     
        // add the themeDesign stylesheet to <head>
        // use @import to avoid cross domain security issues when determining when the stylesheet is loaded
        $style = $('<style type="text/css">@import url("' + url + '")</style>');
        $style.appendTo('head');
     
        // kickoff the polling
        pollFunction();
     
        // return the promise
        return styleSheetDeferred.promise();
    };
     
    // update with the design.css from the Sites Page
    SitesSDK.getSiteProperty('themeDesign', function (data) {
        if (data && data.themeDesign && typeof data.themeDesign === 'string') {
            // load the style sheet and then set the height
            self.loadStyleSheet(data.themeDesign).done(self.setHeight);
        }
    });
  2. Obtenha o valor da classe de estilo de seleção sempre que ele for alterado

    Crie um elemento observável para rastrear quando o valor da propriedade styleClass for alterado:

    self.selectedStyleClass = ko.observable();

    Observe que não podemos renderizar até que tenhamos a classe de estilo. Altere este código:

    self.customSettingsDataInitialized = ko.observable(false);
    self.initialized = ko.computed(function () {
        return self.customSettingsDataInitialized();
    }, self);

    Em seu lugar, use este código:

    self.customSettingsDataInitialized = ko.observable(false);
    self.styleClassInitialized = ko.observable(false);
    self.initialized = ko.computed(function () {
        return self.customSettingsDataInitialized() && self.styleClassInitialized();
    }, self);

    Obtenha o valor inicial da classe de estilo selecionada adicionando:

    self.updateStyleClass = function (styleClass) {
        self.selectedStyleClass((typeof styleClass === 'string') ? styleClass : 'hello-world-default-style'); // note that this 'hello-world' prefix is based on the app name
        self.styleClassInitialized(true);
    };
    SitesSDK.getProperty('styleClass', self.updateStyleClass);
  3. Atualize o modelo para refletir a propriedade styleClass. Altere este código:

    <p data-bind="attr: {id: 'titleId'}, text: titleText"></p>

    Em seu lugar, use este código:

    <p data-bind="attr: {id: 'titleId'}, text: titleText, css: selectedStyleClass"></p>
  4. Reflita no seu componente as alterações na classe de estilo selecionada Altere este código:

    if (settings.property === 'customSettingsData') {
        self.updateCustomSettingsData(settings.value);
    }

    Em seu lugar, use este código:

    if (settings.property === 'customSettingsData') {
        self.updateCustomSettingsData(settings.value);
    }
    if (settings.property === 'styleClass') {
        self.updateStyleClass(settings.value);
    }
  5. Certifique-se de que o iframe seja redimensionado quando o estilo for alterado. Altere este código:

    // create dependencies on any observables so this handler is called whenever it changes
    var imageWidth = viewModel.imageWidth(),
          imageUrl = viewModel.imageUrl(),
          titleText = viewModel.titleText(),
          userText = viewModel.userText();

    Em seu lugar, use este código:

    // create dependencies on any observables so this handler is called whenever it changes
    var imageWidth = viewModel.imageWidth(),
          imageUrl = viewModel.imageUrl(),
          titleText = viewModel.titleText(),
          userText = viewModel.userText(),
          selectedStyleClass = viewModel.selectedStyleClass();  
  6. Salve e sincronize seus arquivos com o servidor de instância do Oracle Content Management.

Verificar os Resultados da Etapa 14

  1. Atualize sua página no site para que o Site Builder possa selecionar as alterações no componente.

  2. Coloque a página no modo de Edição.

  3. Arraste e solte o componente na página.

  4. Abra o painel Definições no seu componente.

  5. Vá para a guia Estilo.

  6. Alterne entre os estilos Gothic e Plain definidos em seu arquivo design.json.

    Você notará que o tamanho da fonte em seu componente se ajusta para refletir as alterações conforme alterna entre a classe CSS aplicada para cada seleção.

Continue em Etapa 15: Integração com o Comportamento Desfazer e Refazer da Página.